diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 4fa1837bf4..02d2188ae6 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -51,6 +51,7 @@ var ActionManagerExist = !!cc.ActionManager; var emptyFunc = function () {}; var _mat4_temp = math.mat4.create(); var _vec3_temp = math.vec3.create(); +var _vec2_temp = math.vec2.create(); var _trans = affineTrans.make(); var _globalOrderOfArrival = 1; diff --git a/cocos2d/core/components/CCRenderComponent.js b/cocos2d/core/components/CCRenderComponent.js new file mode 100644 index 0000000000..fe8614d347 --- /dev/null +++ b/cocos2d/core/components/CCRenderComponent.js @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const Component = require('./CCComponent'); +const renderEngine = require('../renderer/render-engine'); +const gfx = renderEngine.gfx; + +var _defaultVertexFormat = new gfx.VertexFormat([ + { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, + { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true }, + { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 } +]); + +/** + * !#en + * Base class for components which supports rendering features. + * !#zh + * 所有支持渲染的组件的基类 + * + * @class RenderComponent + * @extends Component + */ +var RenderComponent = cc.Class({ + name: 'RenderComponent', + extends: Component, + + ctor: function() { + this._material = null; + this._customMaterial = false; + this._renderData = null; + this._vertexFormat = _defaultVertexFormat; + }, + + getEffect () { + if (this._material) { + return this._material.effect; + } + else { + return null; + } + }, +}); +RenderComponent._assembler = null; + +module.exports = RenderComponent; \ No newline at end of file diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 3c7a8668f1..7cf4a7c444 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -23,12 +23,12 @@ THE SOFTWARE. ****************************************************************************/ +const RenderComponent = require('./CCRenderComponent'); const renderer = require('../renderer'); const renderEngine = require('../renderer/render-engine'); const gfx = renderEngine.gfx; const SpriteMaterial = renderEngine.SpriteMaterial; -const SpriteModel = renderEngine.SpriteModel; -const SlicedModel = renderEngine.SlicedModel; +const RenderData = renderEngine.RenderData; /** * !#en Enum for sprite type. @@ -156,7 +156,7 @@ var State = cc.Enum({ */ var Sprite = cc.Class({ name: 'cc.Sprite', - extends: cc.Component, + extends: RenderComponent, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Sprite', @@ -164,12 +164,6 @@ var Sprite = cc.Class({ inspector: 'packages://inspector/inspectors/comps/sprite.js', }, - ctor: function() { - this._material = null; - this._customMaterial = false; - this._model = null; - }, - properties: { _spriteFrame: { default: null, @@ -246,9 +240,8 @@ var Sprite = cc.Class({ }, set: function (value) { if (this._type !== value) { - this._removeModel(); + RenderData.free(this._renderData); this._type = value; - this._activateModel(); } }, type: SpriteType, @@ -272,8 +265,8 @@ var Sprite = cc.Class({ }, set: function(value) { this._fillType = value; - if (this._type === SpriteType.FILLED && this._model) { - this._model.setFillType(value); + if (this._type === SpriteType.FILLED && this._renderData) { + this._renderData.vertDirty = true; } }, type: FillType, @@ -296,8 +289,8 @@ var Sprite = cc.Class({ }, set: function(value) { this._fillCenter = cc.v2(value); - if (this._type === SpriteType.FILLED && this._model) { - this._model.setFillCenter(this._fillCenter); + if (this._type === SpriteType.FILLED && this._renderData) { + this._renderData.vertDirty = true; } }, tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_center', @@ -320,8 +313,8 @@ var Sprite = cc.Class({ }, set: function(value) { this._fillStart = cc.clampf(value, -1, 1); - if (this._type === SpriteType.FILLED && this._model) { - this._model.setFillStart(this._fillStart); + if (this._type === SpriteType.FILLED && this._renderData) { + this._renderData.vertDirty = true; } }, tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_start' @@ -344,8 +337,8 @@ var Sprite = cc.Class({ }, set: function(value) { this._fillRange = cc.clampf(value, -1, 1); - if (this._type === SpriteType.FILLED && this._model) { - this._model.setFillRange(this._fillRange); + if (this._type === SpriteType.FILLED && this._renderData) { + this._renderData.vertDirty = true; } }, tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_range' @@ -365,8 +358,8 @@ var Sprite = cc.Class({ set: function (value) { if (this._isTrimmedMode !== value) { this._isTrimmedMode = value; - if (this._type === SpriteType.SIMPLE && this._model) { - this._model.trimmed = value; + if (this._type === SpriteType.SIMPLE && this._renderData) { + this._renderData.uvDirty = true; } } }, @@ -471,21 +464,22 @@ var Sprite = cc.Class({ }, onEnable: function () { - this._activateModel(); + this._activateMaterial(); }, onDisable: function () { - this._removeModel(); + RenderData.free(this._renderData); + }, + + _sizeChanged: function () { + if (this._renderData) { + this._renderData.vertDirty = true; + } }, - _activateModel: function () { - // model cannot be activated if already exists or component not enabled - // TODO: Should use enabledInHierarchy - if (!this.enabled) { - return; - } - // model cannot be activated if texture not loaded yet - else if (!this._spriteFrame.textureLoaded) { + _activateMaterial: function () { + // cannot be activated if texture not loaded yet + if (!this._spriteFrame.textureLoaded) { return; } @@ -501,61 +495,9 @@ var Sprite = cc.Class({ } } - if (!this._model) { - // Generate model - switch (this.type) { - case SpriteType.SIMPLE: - this._model = SpriteModel.alloc(); - this._model.trimmed = this._isTrimmedMode; - break; - case SpriteType.SLICED: - this._model = SlicedModel.alloc(); - break; - case SpriteType.TILED: - break; - case SpriteType.FILLED: - // sgNode.setFillType(this._fillType); - // sgNode.setFillCenter(this._fillCenter); - // sgNode.setFillStart(this._fillStart); - // sgNode.setFillRange(this._fillRange); - break; - } - this._model.setNode(this.node); - } - - this._model.spriteFrame = this._spriteFrame; - if (this.srcBlendFactor !== gfx.BLEND_SRC_ALPHA || this.dstBlendFactor !== gfx.BLEND_ONE_MINUS_SRC_ALPHA) { this._updateBlendFunc(); } - this._model.setEffect(this._material.effect); - - // Add to rendering scene - renderer.scene.addModel(this._model); - }, - - _removeModel: function () { - if (!this._model) { - return; - } - - // Remove from rendering scene - renderer.scene.removeModel(this._model); - - // Recycle model - switch (this.type) { - case SpriteType.SIMPLE: - SpriteModel.free(this._model); - break; - case SpriteType.SLICED: - SlicedModel.free(this._model); - break; - case SpriteType.TILED: - break; - case SpriteType.FILLED: - break; - } - this._model = null; }, _updateBlendFunc: function () { @@ -604,8 +546,14 @@ var Sprite = cc.Class({ if (!this.isValid) { return; } - // Reattach material to model - this._activateModel(); + // Mark render data dirty + if (this._renderData) { + this._renderData.uvDirty = true; + } + // Reactivate material + if (this.enabledInHierarchy) { + this._activateMaterial(); + } this._applySpriteSize(); }, diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index 233e4ff64b..b5c71970f2 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -27,7 +27,7 @@ require('./CCComponent'); require('./CCComponentEventHandler'); require('./missing-script'); -module.exports = [ +var components = [ require('./CCSprite'), require('./CCWidget'), require('./CCCanvas'), @@ -54,3 +54,8 @@ module.exports = [ require('./CCToggle'), require('./CCBlockInputEvents'), ]; + +// Delay require render components assemblers +require('../renderer/assemblers'); + +module.exports = components \ No newline at end of file diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index ecedc15121..078cf376dd 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -1867,7 +1867,7 @@ cc.macro = { * 最大可以被单次批处理渲染的顶点数量。 * @property {Number} BATCH_VERTEX_COUNT */ - BATCH_VERTEX_COUNT: 20000, + BATCH_VERTEX_COUNT: 2000, /** * !#en diff --git a/cocos2d/core/renderer/DirtyRegion.js b/cocos2d/core/renderer/DirtyRegion.js deleted file mode 100644 index b395d716d5..0000000000 --- a/cocos2d/core/renderer/DirtyRegion.js +++ /dev/null @@ -1,337 +0,0 @@ -//Region is used to label a rect which world axis aligned. -var Region = function () { - this._minX = 0; - this._minY = 0; - this._maxX = 0; - this._maxY = 0; - - this._width = 0; - this._height = 0; - this._area = 0; - //this.moved = false; -}; - -var regionProto = Region.prototype; - -var regionPool = []; - -function regionCreate() { - var region = regionPool.pop(); - if (!region) { - region = new Region(); - } - return region; -} - -function regionRelease(region) { - regionPool.push(region); -} - -regionProto.setTo = function (minX, minY, maxX, maxY) { - this._minX = minX; - this._minY = minY; - this._maxX = maxX; - this._maxY = maxY; - this.updateArea(); - return this; -}; - -//convert region to int values which is fast for clipping -regionProto.intValues = function () { - this._minX = Math.floor(this._minX); - this._minY = Math.floor(this._minY); - this._maxX = Math.ceil(this._maxX); - this._maxY = Math.ceil(this._maxY); - this.updateArea(); -}; - -//update the area of region -regionProto.updateArea = function () { - this._width = this._maxX - this._minX; - this._height = this._maxY - this._minY; - this._area = this._width * this._height; -}; - -//merge two region into one -regionProto.union = function (target) { - if(this.isEmpty()) { - this.setTo(target._minX, target._minY, target._maxX, target._maxY); - return; - } - if (this._minX > target._minX) { - this._minX = target._minX; - } - if (this._minY > target._minY) { - this._minY = target._minY; - } - if (this._maxX < target._maxX) { - this._maxX = target._maxX; - } - if (this._maxY < target._maxY) { - this._maxY = target._maxY; - } - this.updateArea(); -}; - -//regionProto.intersect = function (target) { -// if (this._minX < target._minX) { -// this._minX = target._minX; -// } -// if (this._maxX > target._maxX) { -// this._maxX = target._maxX; -// } -// if (this._minX >= this._maxX) { -// this.setEmpty(); -// return; -// } -// if (this._minY < target._minY) { -// this._minY = target._minY; -// } -// -// if (this._maxY > target._maxY) { -// this._maxY = target._maxY; -// } -// if (this._minY >= this._maxY) { -// this.setEmpty(); -// return; -// } -// this.updateArea(); -//}; - -//set region to empty -regionProto.setEmpty = function () { - this._minX = 0; - this._minY = 0; - this._maxX = 0; - this._maxY = 0; - this._width = 0; - this._height = 0; - this._area = 0; -}; - -regionProto.isEmpty = function () { - return this._width <= 0 || this._height <= 0; -}; - -//check whether two region is intersects or not -regionProto.intersects = function (target) { - if (this.isEmpty() || target.isEmpty()) { - return false; - } - var max = this._minX > target._minX ? this._minX : target._minX; - var min = this._maxX < target._maxX ? this._maxX : target._maxX; - if (max > min) { - return false; - } - - max = this._minY > target._minY ? this._minY : target._minY; - min = this._maxY < target._maxY ? this._maxY : target._maxY; - return max <= min; -}; - -//update region by a rotated bounds -regionProto.updateRegion = function (bounds, matrix) { - if (bounds.width === 0 || bounds.height === 0) { - this.setEmpty(); - return; - } - var m = matrix; - var a = m.a; - var b = m.b; - var c = m.c; - var d = m.d; - var tx = m.tx; - var ty = m.ty; - var x = bounds.x; - var y = bounds.y; - var xMax = x + bounds.width; - var yMax = y + bounds.height; - var minX, minY, maxX, maxY; - if (a === 1 && b === 0 && c === 0 && d === 1) { - minX = x + tx - 1; - minY = y + ty - 1; - maxX = xMax + tx + 1; - maxY = yMax + ty + 1; - } - else { - var x0 = a * x + c * y + tx; - var y0 = b * x + d * y + ty; - var x1 = a * xMax + c * y + tx; - var y1 = b * xMax + d * y + ty; - var x2 = a * xMax + c * yMax + tx; - var y2 = b * xMax + d * yMax + ty; - var x3 = a * x + c * yMax + tx; - var y3 = b * x + d * yMax + ty; - - var tmp = 0; - - if (x0 > x1) { - tmp = x0; - x0 = x1; - x1 = tmp; - } - if (x2 > x3) { - tmp = x2; - x2 = x3; - x3 = tmp; - } - - minX = (x0 < x2 ? x0 : x2) - 1; - maxX = (x1 > x3 ? x1 : x3) + 1; - - if (y0 > y1) { - tmp = y0; - y0 = y1; - y1 = tmp; - } - if (y2 > y3) { - tmp = y2; - y2 = y3; - y3 = tmp; - } - - minY = (y0 < y2 ? y0 : y2) - 1; - maxY = (y1 > y3 ? y1 : y3) + 1; - } - this._minX = minX; - this._minY = minY; - this._maxX = maxX; - this._maxY = maxY; - this._width = maxX - minX; - this._height = maxY - minY; - this._area = this._width * this._height; -}; - -//get the area of the unioned region of r1 and r2 -function unionArea(r1, r2) { - var minX = r1._minX < r2._minX ? r1._minX : r2._minX; - var minY = r1._minY < r2._minY ? r1._minY : r2._minY; - var maxX = r1._maxX > r2._maxX ? r1._maxX : r2._maxX; - var maxY = r1._maxY > r2._maxY ? r1._maxY : r2._maxY; - return (maxX - minX) * (maxY - minY); -} - -//DirtyRegion is used to collect the dirty area which need to be rerendered in canvas -//there may be many small regions which is dirty, the dirty region will merge it into several big one to optimise performance -var DirtyRegion = function() { - this.dirtyList = []; - this.hasClipRect = false; - this.clipWidth = 0; - this.clipHeight = 0; - this.clipArea = 0; - this.clipRectChanged = false; -}; -var dirtyRegionProto = DirtyRegion.prototype; - -//clip rect, regions will not be considered if it is outside -dirtyRegionProto.setClipRect = function(width, height) { - this.hasClipRect = true; - this.clipRectChanged = true; - this.clipWidth = Math.ceil(width); - this.clipHeight = Math.ceil(height); - this.clipArea = this.clipWidth * this.clipHeight; -}; - -//add a new region which is dirty (need to be rendered) -dirtyRegionProto.addRegion = function(target) { - var minX = target._minX, minY = target._minY, maxX = target._maxX, maxY = target._maxY; - - if (this.hasClipRect) { - if (minX < 0) { - minX = 0; - } - if (minY < 0) { - minY = 0; - } - if (maxX > this.clipWidth) { - maxX = this.clipWidth; - } - if (maxY > this.clipHeight) { - maxY = this.clipHeight; - } - } - if (minX >= maxX || minY >= maxY) { - return false; - } - if (this.clipRectChanged) { - return true; - } - var dirtyList = this.dirtyList; - var region = regionCreate(); - dirtyList.push(region.setTo(minX, minY, maxX, maxY)); - this.mergeDirtyList(dirtyList); - return true; -}; - -//clear all the dirty regions -dirtyRegionProto.clear = function() { - var dirtyList = this.dirtyList; - var length = dirtyList.length; - for (var i = 0; i < length; i++) { - regionRelease(dirtyList[i]); - } - dirtyList.length = 0; -}; - -//get the merged dirty regions -dirtyRegionProto.getDirtyRegions = function() { - var dirtyList = this.dirtyList; - if (this.clipRectChanged) { - this.clipRectChanged = false; - this.clear(); - var region = regionCreate(); - dirtyList.push(region.setTo(0, 0, this.clipWidth, this.clipHeight)); - } - else { - while (this.mergeDirtyList(dirtyList)) { - } - } - var numDirty = this.dirtyList.length; - if (numDirty > 0) { - for (var i = 0; i < numDirty; i++) { - this.dirtyList[i].intValues(); - } - } - return this.dirtyList; -}; - -//merge the small dirty regions into bigger region, to improve the performance of dirty regions -dirtyRegionProto.mergeDirtyList = function(dirtyList) { - var length = dirtyList.length; - if (length < 2) { - return false; - } - var hasClipRect = this.hasClipRect; - var bestDelta = length > 3 ? Number.POSITIVE_INFINITY : 0; - var mergeA = 0; - var mergeB = 0; - var totalArea = 0; - for (var i = 0; i < length - 1; i++) { - var regionA = dirtyList[i]; - hasClipRect && (totalArea += regionA.area); - for (var j = i + 1; j < length; j++) { - var regionB = dirtyList[j]; - var delta = unionArea(regionA, regionB) - regionA.area - regionB.area; - if (bestDelta > delta) { - mergeA = i; - mergeB = j; - bestDelta = delta; - } - } - } - //if the area of dirty region exceed 95% of the screen, skip the following dirty regions merge - if (hasClipRect && (totalArea / this.clipArea) > 0.95) { - this.clipRectChanged = true; - } - if (mergeA !== mergeB) { - var region = dirtyList[mergeB]; - dirtyList[mergeA].union(region); - regionRelease(region); - dirtyList.splice(mergeB, 1); - return true; - } - return false; -}; - -cc.Region = Region; -cc.DirtyRegion = DirtyRegion; diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js deleted file mode 100644 index 42a491a5ec..0000000000 --- a/cocos2d/core/renderer/RendererCanvas.js +++ /dev/null @@ -1,444 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Chukong Aipu reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -cc.rendererCanvas = { - childrenOrderDirty: true, - assignedZ: 0, - assignedZStep: 1/10000, - - _transformNodePool: [], //save nodes transform dirty - _renderCmds: [], //save renderer commands - - _isCacheToCanvasOn: false, //a switch that whether cache the rendererCmd to cacheToCanvasCmds - _cacheToCanvasCmds: {}, // an array saves the renderer commands need for cache to other canvas - _cacheInstanceIds: [], - _currentID: 0, - _clearColor: cc.color(), //background color,default BLACK - _clearFillStyle: "rgb(0, 0, 0)", - _dirtyRegion: null, - _allNeedDraw: true, - _enableDirtyRegion: false, - _debugDirtyRegion: false, - - //max dirty Region count, default is 10 - _dirtyRegionCountThreshold: 10, - init: function() { - if(cc.sys.browserType === cc.sys.BROWSER_TYPE_IE || cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { - this.enableDirtyRegion(false); - } - }, - - getRenderCmd: function (renderableObject) { - //TODO Add renderCmd pool here - return renderableObject._createRenderCmd(); - }, - - enableDirtyRegion : function (enabled) { - this._enableDirtyRegion = enabled; - }, - - isDirtyRegionEnabled: function () { - return this._enableDirtyRegion; - }, - - setDirtyRegionCountThreshold: function(threshold) { - this._dirtyRegionCountThreshold = threshold; - }, - - _collectDirtyRegion: function() { - //collect dirtyList - var locCmds = this._renderCmds, i, len; - var dirtyRegion = this._dirtyRegion; - var localStatus = _ccsg.Node.CanvasRenderCmd.RegionStatus; - var dirtryRegionCount = 0; - var result = true; - for (i = 0, len = locCmds.length; i < len; i++) { - var cmd = locCmds[i]; - var regionFlag = cmd._regionFlag; - var oldRegion = cmd._oldRegion; - var currentRegion = cmd._currentRegion; - if(regionFlag > localStatus.NotDirty) { - ++dirtryRegionCount; - if(dirtryRegionCount > this._dirtyRegionCountThreshold) - result = false; - //add - if(result) { - (!currentRegion.isEmpty()) && dirtyRegion.addRegion(currentRegion); - if(cmd._regionFlag > localStatus.Dirty) { - (!oldRegion.isEmpty()) && dirtyRegion.addRegion(oldRegion); - } - } - - cmd._regionFlag = localStatus.NotDirty; - } - - } - - return result; - }, - - _beginDrawDirtyRegion: function(ctxWrapper) { - var ctx = ctxWrapper.getContext(); - var dirtyList = this._dirtyRegion.getDirtyRegions(); - ctx.save(); - //add clip - ctxWrapper.setTransform({a:1, b:0, c:0, d:1, tx:0,ty:0}, 1, 1); - - ctx.beginPath(); - - var x = 0, y = 0, width = 0, height = 0, scaleX = ctxWrapper._scaleX, scaleY = ctxWrapper._scaleY; - for(var index = 0, count = dirtyList.length; index < count; ++index) { - // fix dirty rectangle black border for #fireball/issues/3819 - var region = dirtyList[index]; - x = (region._minX * scaleX | 0) - 1; - y = (-region._maxY * scaleX | 0) - 1; - width = (region._width * scaleX | 0) + 2; - height = (region._height * scaleY | 0) + 2; - ctx.rect(x, y, width, height); - } - - ctx.clip(); - //end add clip - }, - - _endDrawDirtyRegion: function(ctx) { - ctx.restore(); - }, - - _debugDrawDirtyRegion: function(ctxWrapper) { - if(!this._debugDirtyRegion) return; - var ctx = ctxWrapper.getContext(); - var dirtyList = this._dirtyRegion.getDirtyRegions(); - //add clip - ctxWrapper.setTransform({a:1, b:0, c:0, d:1, tx:0,ty:0}, 1, 1); - - ctx.beginPath(); - - var x = 0, y = 0, width = 0, height = 0, scaleX = ctxWrapper._scaleX, scaleY = ctxWrapper._scaleY; - for(var index = 0, count = dirtyList.length; index < count; ++index) { - var region = dirtyList[index]; - x = (region._minX * scaleX | 0) - 1; - y = (-region._maxY * scaleX | 0) - 1; - width = (region._width * scaleX | 0) + 2; - height = (region._height * scaleY | 0) + 2; - ctx.rect(x, y, width, height); - } - var oldstyle = ctx.fillStyle; - ctx.fillStyle = 'green'; - ctx.fill(); - ctx.fillStyle = oldstyle; - //end add clip - }, - /** - * drawing all renderer command to context (default is cc._renderContext) - * @param {cc.CanvasContextWrapper} [ctx=cc._renderContext] - */ - rendering: function (ctxWrapper) { - var dirtyRegion = this._dirtyRegion = this._dirtyRegion || new cc.DirtyRegion(); - var viewport = cc._canvas; - var wrapper = ctxWrapper || cc._renderContext; - var ctx = wrapper.getContext(); - - var scaleX = cc.view.getScaleX(), - scaleY = cc.view.getScaleY(); - wrapper.setViewScale(scaleX,scaleY); - wrapper.computeRealOffsetY(); - var dirtyList = this._dirtyRegion.getDirtyRegions(); - var locCmds = this._renderCmds, i, len; - var allNeedDraw = this._allNeedDraw || !this._enableDirtyRegion; - if(!allNeedDraw) { - allNeedDraw = allNeedDraw || !this._collectDirtyRegion(); - } - - if(!allNeedDraw) { - this._beginDrawDirtyRegion(wrapper); - } - - ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.clearRect(0, 0, viewport.width, viewport.height); - if (this._clearColor.r !== 0 || - this._clearColor.g !== 0 || - this._clearColor.b !== 0) { - wrapper.setFillStyle(this._clearFillStyle); - wrapper.setGlobalAlpha(this._clearColor.a); - ctx.fillRect(0, 0, viewport.width, viewport.height); - } - - for (i = 0, len = locCmds.length; i < len; i++) { - var cmd = locCmds[i]; - if (!cmd._needDraw) continue; - - var needRendering = false; - var cmdRegion = cmd._currentRegion; - if (!cmdRegion || allNeedDraw) { - needRendering = true; - } else { - for(var index = 0, count = dirtyList.length; index < count; ++index) { - if(dirtyList[index].intersects(cmdRegion)) { - needRendering = true; - break; - } - } - } - if (needRendering) { - cmd.rendering(wrapper, scaleX, scaleY); - } - } - - if (!allNeedDraw) { - //draw debug info for dirty region if it is needed - this._debugDrawDirtyRegion(wrapper); - this._endDrawDirtyRegion(ctx); - } - - dirtyRegion.clear(); - this._allNeedDraw = false; - }, - - /** - * drawing all renderer command to cache canvas' context - * @param {cc.CanvasContextWrapper} ctx - * @param {Number} [instanceID] - * @param {Number} [scaleX] - * @param {Number} [scaleY] - */ - _renderingToCacheCanvas: function (ctx, instanceID, scaleX, scaleY) { - if (!ctx) - cc.logID(7600); - scaleX = scaleX === undefined ? 1 : scaleX; - scaleY = scaleY === undefined ? 1 : scaleY; - instanceID = instanceID || this._currentID; - var locCmds = this._cacheToCanvasCmds[instanceID], i, len; - ctx.computeRealOffsetY(); - for (i = 0, len = locCmds.length; i < len; i++) { - locCmds[i].rendering(ctx, scaleX, scaleY); - } - this._removeCache(instanceID); - - var locIDs = this._cacheInstanceIds; - if (locIDs.length === 0) - this._isCacheToCanvasOn = false; - else - this._currentID = locIDs[locIDs.length - 1]; - }, - - _turnToCacheMode: function (renderTextureID) { - this._isCacheToCanvasOn = true; - renderTextureID = renderTextureID || 0; - this._cacheToCanvasCmds[renderTextureID] = []; - if(this._cacheInstanceIds.indexOf(renderTextureID) === -1) - this._cacheInstanceIds.push(renderTextureID); - this._currentID = renderTextureID; - }, - - _turnToNormalMode: function () { - this._isCacheToCanvasOn = false; - }, - - _removeCache: function (instanceID) { - instanceID = instanceID || this._currentID; - var cmds = this._cacheToCanvasCmds[instanceID]; - if (cmds) { - cmds.length = 0; - delete this._cacheToCanvasCmds[instanceID]; - } - - var locIDs = this._cacheInstanceIds; - cc.js.array.remove(locIDs, instanceID); - }, - - resetFlag: function () { - this.childrenOrderDirty = false; - this._transformNodePool.length = 0; - }, - - transform: function () { - var locPool = this._transformNodePool; - //sort the pool - locPool.sort(this._sortNodeByLevelAsc); - - //transform node - for (var i = 0, len = locPool.length; i < len; i++) { - locPool[i].updateStatus(); - } - locPool.length = 0; - }, - - transformDirty: function () { - return this._transformNodePool.length > 0; - }, - - _sortNodeByLevelAsc: function (n1, n2) { - return n1._curLevel - n2._curLevel; - }, - - pushDirtyNode: function (node) { - this._transformNodePool.push(node); - }, - - clear: function () { - }, - - clearRenderCommands: function () { - this._renderCmds.length = 0; - this._cacheInstanceIds.length = 0; - this._isCacheToCanvasOn = false; - this._allNeedDraw = true; - }, - - pushRenderCommand: function (cmd) { - if(!cmd.rendering) - return; - if (this._isCacheToCanvasOn) { - var currentId = this._currentID, locCmdBuffer = this._cacheToCanvasCmds; - var cmdList = locCmdBuffer[currentId]; - if (cmdList.indexOf(cmd) === -1) - cmdList.push(cmd); - } else { - if (this._renderCmds.indexOf(cmd) === -1) - this._renderCmds.push(cmd); - } - } -}; - -(function () { - cc.CanvasContextWrapper = function (context) { - this._context = context; - - this._saveCount = 0; - this._currentAlpha = context.globalAlpha; - this._currentCompositeOperation = context.globalCompositeOperation; - this._currentFillStyle = context.fillStyle; - this._currentStrokeStyle = context.strokeStyle; - - this._offsetX = 0; - this._offsetY = 0; - this._realOffsetY = this.height; - this._armatureMode = 0; - }; - - var proto = cc.CanvasContextWrapper.prototype; - - proto.resetCache = function(){ - var context = this._context; - //call it after resize cc._canvas, because context will reset. - this._currentAlpha = context.globalAlpha; - this._currentCompositeOperation = context.globalCompositeOperation; - this._currentFillStyle = context.fillStyle; - this._currentStrokeStyle = context.strokeStyle; - this._realOffsetY = this._context.canvas.height + this._offsetY; - }; - - proto.setOffset = function(x, y){ - this._offsetX = x; - this._offsetY = y; - this._realOffsetY = this._context.canvas.height + this._offsetY; - }; - - proto.computeRealOffsetY = function(){ - this._realOffsetY = this._context.canvas.height + this._offsetY; - }; - - proto.setViewScale = function(scaleX, scaleY){ - //call it at cc.renderCanvas.rendering - this._scaleX = scaleX; - this._scaleY = scaleY; - }; - - proto.getContext = function(){ - return this._context; - }; - - proto.save = function () { - this._context.save(); - this._saveCount++; - }; - - proto.restore = function () { - this._context.restore(); - this._currentAlpha = this._context.globalAlpha; - this._saveCount--; - }; - - proto.setGlobalAlpha = function (alpha) { - if (this._saveCount > 0) { - this._context.globalAlpha = alpha; - } else { - if (this._currentAlpha !== alpha) { - this._currentAlpha = alpha; - this._context.globalAlpha = alpha; - } - } - }; - - proto.setCompositeOperation = function(compositionOperation){ - if (this._saveCount > 0) { - this._context.globalCompositeOperation = compositionOperation; - } else { - if (this._currentCompositeOperation !== compositionOperation) { - this._currentCompositeOperation = compositionOperation; - this._context.globalCompositeOperation = compositionOperation; - } - } - }; - - proto.setFillStyle = function(fillStyle){ - this._context.fillStyle = fillStyle; - }; - - proto.setStrokeStyle = function(strokeStyle){ - if (this._saveCount > 0) { - this._context.strokeStyle = strokeStyle; - } else { - if (this._currentStrokeStyle !== strokeStyle) { - this._currentStrokeStyle = strokeStyle; - this._context.strokeStyle = strokeStyle; - } - } - }; - - proto.setTransform = function(t, scaleX, scaleY){ - if (this._armatureMode > 0) { - //ugly for armature - this.restore(); - this.save(); - this._context.transform(t.a, -t.b, -t.c, t.d, t.tx * scaleX, -(t.ty * scaleY)); - } else { - this._context.setTransform(t.a * scaleX, -t.b * scaleY, -t.c * scaleX, t.d * scaleY, this._offsetX + t.tx * scaleX, this._realOffsetY - (t.ty * scaleY)); - } - }; - - proto._switchToArmatureMode = function(enable, t, scaleX, scaleY){ - if(enable){ - this._armatureMode++; - this._context.setTransform(t.a, t.c, t.b, t.d, this._offsetX + t.tx * scaleX, this._realOffsetY - (t.ty * scaleY)); - this.save(); - }else{ - this._armatureMode--; - this.restore(); - } - }; -})(); - diff --git a/cocos2d/core/renderer/assemblers/index.js b/cocos2d/core/renderer/assemblers/index.js new file mode 100644 index 0000000000..056d8793e3 --- /dev/null +++ b/cocos2d/core/renderer/assemblers/index.js @@ -0,0 +1 @@ +require('./sprite-assembler'); \ No newline at end of file diff --git a/cocos2d/core/renderer/assemblers/sprite-assembler.js b/cocos2d/core/renderer/assemblers/sprite-assembler.js new file mode 100644 index 0000000000..e8ce74bd08 --- /dev/null +++ b/cocos2d/core/renderer/assemblers/sprite-assembler.js @@ -0,0 +1,374 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const Sprite = require('../../components/CCSprite'); +const renderEngine = require('../render-engine'); +const SpriteType = Sprite.Type; +const RenderData = renderEngine.RenderData; +const math = renderEngine.math; + +var _matrix = math.mat4.create(); + +var simpleRenderData = { + createData (sprite) { + let renderData = RenderData.alloc(); + renderData.xysLength = 4; + renderData.uvsLength = 4; + renderData.vertexCount = 4; + renderData.indexCount = 6; + return renderData; + }, + + updateUVs (sprite) { + let effect = sprite.getEffect(); + let data = sprite._renderData; + if (effect && data) { + let texture = effect.getValue('texture'); + let texw = texture._width, + texh = texture._height; + let frame = sprite.spriteFrame; + let rect = frame._rect; + let l, b, r, t; + + if (sprite.trim) { + l = rect.x; + t = rect.y; + r = rect.x + rect.width; + b = rect.y + rect.height; + } else { + let originalSize = frame._originalSize; + let offset = frame._offset; + let ow = originalSize.width, + oh = originalSize.height, + rw = rect.width, + rh = rect.height; + let ox = rect.x + (rw - ow) / 2 - offset.x; + let oy = rect.y + (rh - oh) / 2 - offset.y; + + l = ox; + t = oy; + r = ox + ow; + b = oy + oh; + } + + l = texw === 0 ? 0 : l / texw; + r = texw === 0 ? 0 : r / texw; + b = texh === 0 ? 0 : b / texh; + t = texh === 0 ? 0 : t / texh; + + let uvs = data._uvs; + uvs.u[0] = l; + uvs.u[1] = r; + uvs.u[2] = l; + uvs.u[3] = r; + uvs.v[0] = b; + uvs.v[1] = b; + uvs.v[2] = t; + uvs.v[3] = t; + + data.uvDirty = false; + } + }, + + updateVerts (sprite) { + let data = sprite._renderData, + frame = sprite.spriteFrame, + width, height; + if (sprite.trim) { + width = frame._rect.width; + height = frame._rect.height; + } + else { + width = frame._originalSize.width; + height = frame._originalSize.height; + } + + let appx = data._pivotX * width, + appy = data._pivotY * height; + + var verts = data._verts; + verts.x[0] = -appx; + verts.x[1] = width - appx; + verts.x[2] = -appx; + verts.x[3] = width - appx; + verts.y[0] = -appy; + verts.y[1] = -appy; + verts.y[2] = height - appy; + verts.y[3] = height - appy; + + data.vertDirty = false; + }, + + fillVertexBuffer (sprite, index, vbuf, uintbuf) { + let texture = sprite.getEffect().getValue('texture'); + + let off = index * sprite._vertexFormat._bytes / 4; + let node = sprite.node; + let data = sprite._renderData; + let x = data._verts.x, + y = data._verts.y, + u = data._uvs.u, + v = data._uvs.v, + z = node.z; + + let color = node._color._val; + let uintColor = ((color&0xff<<24) >>> 0) + ((color&0xff00)<<8) + ((color&0xff0000)>>8) + (color>>>24); + + node.getWorldMatrix(_matrix); + let a = _matrix.m00, + b = _matrix.m01, + c = _matrix.m04, + d = _matrix.m05, + tx = _matrix.m12, + ty = _matrix.m13; + + for (let i = 0; i < 4; i++) { + vbuf[off++] = x[i] * a + y[i] * c + tx; + vbuf[off++] = x[i] * b + y[i] * d + ty; + vbuf[off++] = z; + uintbuf[off++] = color; + vbuf[off++] = u[i]; + vbuf[off++] = v[i]; + } + }, + + fillIndexBuffer (comp, offset, vertexId, ibuf) { + ibuf[offset + 0] = vertexId; + ibuf[offset + 1] = vertexId + 1; + ibuf[offset + 2] = vertexId + 2; + ibuf[offset + 3] = vertexId + 1; + ibuf[offset + 4] = vertexId + 3; + ibuf[offset + 5] = vertexId + 2; + } +}; + +var slicedRenderData = { + createData (sprite) { + let renderData = RenderData.alloc(); + renderData.xysLength = 4; + renderData.uvsLength = 4; + renderData.vertexCount = 36; + renderData.indexCount = 54; + return renderData; + }, + + updateUVs (sprite) { + let effect = sprite.getEffect(); + let data = sprite._renderData; + if (effect) { + let texture = effect.getValue('texture'); + let frame = sprite.spriteFrame; + let rect = frame._rect; + let atlasWidth = texture._width; + let atlasHeight = texture._height; + + // caculate texture coordinate + let leftWidth = frame.insetLeft; + let rightWidth = frame.insetRight; + let centerWidth = rect.width - leftWidth - rightWidth; + let topHeight = frame.insetTop; + let bottomHeight = frame.insetBottom; + let centerHeight = rect.height - topHeight - bottomHeight; + + // uv computation should take spritesheet into account. + let u = data._uvs.u; + let v = data._uvs.v; + if (frame._rotated) { + u[0] = (rect.x) / atlasWidth; + u[1] = (bottomHeight + rect.x) / atlasWidth; + u[2] = (bottomHeight + centerHeight + rect.x) / atlasWidth; + u[3] = (rect.x + rect.height) / atlasWidth; + + v[0] = (rect.y) / atlasHeight; + v[1] = (leftWidth + rect.y) / atlasHeight; + v[2] = (leftWidth + centerWidth + rect.y) / atlasHeight; + v[3] = (rect.y + rect.width) / atlasHeight; + } + else { + u[0] = (rect.x) / atlasWidth; + u[1] = (leftWidth + rect.x) / atlasWidth; + u[2] = (leftWidth + centerWidth + rect.x) / atlasWidth; + u[3] = (rect.x + rect.width) / atlasWidth; + + v[3] = (rect.y) / atlasHeight; + v[2] = (topHeight + rect.y) / atlasHeight; + v[1] = (topHeight + centerHeight + rect.y) / atlasHeight; + v[0] = (rect.y + rect.height) / atlasHeight; + } + data.uvDirty = false; + } + }, + + updateVerts (sprite) { + let data = sprite._renderData, + width = data._width, + height = data._height, + appx = data._pivotX * width, + appy = data._pivotY * height; + + let frame = sprite.spriteFrame; + let rect = frame._rect; + let leftWidth = frame.insetLeft; + let rightWidth = frame.insetRight; + let topHeight = frame.insetTop; + let bottomHeight = frame.insetBottom; + + let sizableWidth = width - leftWidth - rightWidth; + let sizableHeight = height - topHeight - bottomHeight; + let xScale = width / (leftWidth + rightWidth); + let yScale = height / (topHeight + bottomHeight); + xScale = (isNaN(xScale) || xScale > 1) ? 1 : xScale; + yScale = (isNaN(yScale) || yScale > 1) ? 1 : yScale; + sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; + sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; + let x = data._verts.x; + let y = data._verts.y; + x[0] = -appx; + x[1] = leftWidth * xScale - appx; + x[2] = x[1] + sizableWidth - appx; + x[3] = width - appx; + y[0] = -appy; + y[1] = bottomHeight * yScale - appy; + y[2] = y[1] + sizableHeight - appy; + y[3] = height - appy; + + data.vertDirty = false; + }, + + fillVertexBuffer (sprite, index, vbuf, uintbuf) { + let texture = sprite.getEffect().getValue('texture'); + + let offset = index * sprite._vertexFormat._bytes / 4; + let node = sprite.node; + let data = sprite._renderData; + let x = data._verts.x, + y = data._verts.y, + u = data._uvs.u, + v = data._uvs.v, + z = node.z; + + let color = node._color; + let uintColor = ((color.a<<24) >>> 0) + (color.b<<16) + (color.g<<8) + color.r; + + node.getWorldMatrix(_matrix); + let a = _matrix.m00, + b = _matrix.m01, + c = _matrix.m04, + d = _matrix.m05, + tx = _matrix.m12, + ty = _matrix.m13; + + for (let r = 0; r < 3; ++r) { + for (let c = 0; c < 3; ++c) { + // lb + vbuf[offset] = x[r][c]; + vbuf[offset + 1] = y[r][c]; + vbuf[offset + 2] = z; + uintbuf[offset + 3] = color; + vbuf[offset + 4] = u[c]; + vbuf[offset + 5] = v[r]; + offset += 6; + // rb + vbuf[offset] = x[r][c+1]; + vbuf[offset + 1] = y[r][c+1]; + vbuf[offset + 2] = z; + uintbuf[offset + 3] = color; + vbuf[offset + 4] = u[c+1]; + vbuf[offset + 5] = v[r]; + offset += 6; + // lt + vbuf[offset] = x[r+1][c]; + vbuf[offset + 1] = y[r+1][c]; + vbuf[offset + 2] = z; + uintbuf[offset + 3] = color; + vbuf[offset + 4] = u[c]; + vbuf[offset + 5] = v[r+1]; + offset += 6; + // rt + vbuf[offset] = x[r+1][c+1]; + vbuf[offset + 1] = y[r+1][c+1]; + vbuf[offset + 2] = z; + uintbuf[offset + 3] = color; + vbuf[offset + 4] = u[c+1]; + vbuf[offset + 5] = v[r+1]; + offset += 6; + } + } + }, + + fillIndexBuffer (sprite, offset, vertexId, ibuf) { + for (let r = 0; r < 3; ++r) { + for (let c = 0; c < 3; ++c) { + ibuf[offset++] = vertexId; + ibuf[offset++] = vertexId + 1; + ibuf[offset++] = vertexId + 2; + ibuf[offset++] = vertexId + 1; + ibuf[offset++] = vertexId + 3; + ibuf[offset++] = vertexId + 2; + vertexId += 4; + } + } + } +} + +var dataUpdater = {}; +dataUpdater[SpriteType.SIMPLE] = simpleRenderData; +dataUpdater[SpriteType.SLICED] = slicedRenderData; + +var spriteAssembler = { + updateRenderData (sprite) { + let updater = dataUpdater[sprite.type]; + // Create render data if needed + if (!sprite._renderData) { + sprite._renderData = updater.createData(sprite); + } + + let renderData = sprite._renderData; + let size = sprite.node._contentSize; + let anchor = sprite.node._anchorPoint; + renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); + + if (renderData.uvDirty) { + updater.updateUVs(sprite); + } + if (renderData.vertDirty) { + updater.updateVerts(sprite); + } + }, + + fillVertexBuffer (sprite, index, vbuf, uintbuf) { + let updater = dataUpdater[sprite.type]; + updater.fillVertexBuffer(sprite, index, vbuf, uintbuf); + }, + + fillIndexBuffer (sprite, offset, vertexId, ibuf) { + let updater = dataUpdater[sprite.type]; + updater.fillIndexBuffer(sprite, offset, vertexId, ibuf); + } +} + +Sprite._assembler = spriteAssembler; + +module.exports = spriteAssembler; \ No newline at end of file diff --git a/cocos2d/core/renderer/index.js b/cocos2d/core/renderer/index.js index 8ddec31610..9b0428c07e 100644 --- a/cocos2d/core/renderer/index.js +++ b/cocos2d/core/renderer/index.js @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2013-2017 Chukong Technologies Inc. http://www.cocos.com @@ -24,6 +24,7 @@ ****************************************************************************/ const renderEngine = require('./render-engine'); +const RenderComponentWalker = require('./render-component-walker'); require('./RendererWebGL'); function _initBuiltins(device) { @@ -61,6 +62,7 @@ module.exports = { device: null, scene: null, materialUtil: null, + _walker: null, _cameraNode: null, _camera: null, _forward: null, @@ -71,6 +73,8 @@ module.exports = { this.scene = new renderEngine.Scene(); this.materialUtil = new renderEngine.MaterialUtil(); + this._walker = new RenderComponentWalker(this.device, this.scene); + this._cameraNode = new cc.Node(); this._camera = new renderEngine.Camera({ x: 0, y: 0, w: canvas.width, h: canvas.height @@ -85,6 +89,8 @@ module.exports = { }, updateCameraViewport () { + var scene = cc.director.getScene(); + scene.scaleX = scene.scaleY = 1; this._cameraNode.scaleX = 1 / cc.view.getScaleX(); this._cameraNode.scaleY = 1 / cc.view.getScaleY(); this._camera._rect.w = this.canvas.width; @@ -94,6 +100,10 @@ module.exports = { }, render () { - this._forward.render(this.scene); + var scene = cc.director.getScene(); + if (scene) { + this._walker.visit(scene); + this._forward.render(this.scene); + } } }; \ No newline at end of file diff --git a/cocos2d/core/renderer/render-component-walker.js b/cocos2d/core/renderer/render-component-walker.js new file mode 100644 index 0000000000..1c2d662842 --- /dev/null +++ b/cocos2d/core/renderer/render-component-walker.js @@ -0,0 +1,258 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const RenderComponent = require('../components/CCRenderComponent'); +const renderer = require('./index'); +const renderEngine = require('./render-engine'); +const SharedArrayBuffer = require('./shared-array-buffer'); +const gfx = renderEngine.gfx; +const RecyclePool = renderEngine.RecyclePool; +const InputAssembler = renderEngine.InputAssembler; + +const PER_INDEX_BYTE = 2; +// 500 Quad + 750 Index +const MIN_SHARED_BUFFER_SIZE = 54000; +// 2000 Quad + 3000 Index +const MAX_SHARED_BUFFER_SIZE = 216000; +var _buffers = []; +var _newBuffer = { + buffer: null, + offset: -1 +}; +var _queue = []; + +function _createNewBuffer (bytes) { + // Allocate buffer + let buffer = null, offset = -1; + for (let i = 0, l = _buffers.length; i < l; i++) { + buffer = _buffers[i]; + offset = buffer.request(bytes); + if (offset !== -1) { + break; + } + } + if (offset === -1) { + let bufferSize = 0; + if (bytes > MAX_SHARED_BUFFER_SIZE) { + bufferSize = bytes; + } + else { + bufferSize = Math.max(bytes * 2, MIN_SHARED_BUFFER_SIZE); + } + buffer = new SharedArrayBuffer(bufferSize); + _buffers.push(buffer); + offset = buffer.request(bytes); + } + _newBuffer.buffer = buffer.data; + _newBuffer.offset = offset; + return _newBuffer; +} + +var RenderComponentWalker = function (device, renderScene) { + this._renderScene = renderScene; + this._device = device; + + let defaultFormat = new gfx.VertexFormat([]); + this._vbPool = new RecyclePool(function () { + return new gfx.VertexBuffer( + device, + defaultFormat, + gfx.USAGE_STATIC, + null, + 0 + ); + }, 16); + this._ibPool = new RecyclePool(function () { + return new gfx.IndexBuffer( + device, + gfx.INDEX_FMT_UINT16, + gfx.USAGE_STATIC, + null, + 0 + ); + }, 16); + this._iaPool = new RecyclePool(function () { + return new InputAssembler(); + }, 16); + + this._modelPool = new RecyclePool(() => { + return new renderEngine.Model(); + }, 16); + + this._batchedModels = []; + this._dummyNode = new cc.Node(); + this._sortKey = 0; +}; + +RenderComponentWalker.prototype = { + constructor: RenderComponentWalker, + + reset() { + for (let i = 0; i < _buffers.length; i++) { + _buffers[i].reset(); + } + this._iaPool.reset(); + this._vbPool.reset(); + this._ibPool.reset(); + let scene = this._renderScene; + let models = this._batchedModels; + for (let i = 0; i < models.length; ++i) { + // remove from scene + models[i].clearInputAssemblers(); + models[i].clearEffects(); + scene.removeModel(models[i]); + } + this._modelPool.reset(); + models.length = 0; + _queue.length = 0; + this._sortKey = 0; + }, + + _handleRender (node) { + if (node instanceof cc.Scene) { + return; + } + let comp = node.getComponent(RenderComponent); + if (comp) { + _queue.push(comp); + } + }, + + _postHandleRender (node) { + + }, + + _genModel (vertexCount, vertexFormat, indexCount, comps, start, end) { + let vertexBytes = vertexCount * vertexFormat._bytes; + let buf = _createNewBuffer(vertexBytes); + let vbuf = new Float32Array(buf.buffer, buf.offset, vertexBytes / 4); + buf = _createNewBuffer(indexCount * PER_INDEX_BYTE); + let ibuf = new Uint16Array(buf.buffer, buf.offset, indexCount); + let model = this._batch(comps, start, end, vbuf, ibuf); + this._renderScene.addModel(model); + }, + + _batch (comps, start, end, vbuf, ibuf) { + let uintbuf = new Uint32Array(vbuf.buffer, vbuf.byteOffset, vbuf.length); + let vertexFormat = comps[start]._vertexFormat; + let effect = comps[start].getEffect(); + + let numIndices = 0; + let numVertices = 0; + let comp, assembler, data, vertexId; + for (let i = start; i < end; i++) { + comp = comps[i]; + assembler = comp.constructor._assembler; + data = comp._renderData; + vertexId = numVertices; + assembler.fillVertexBuffer(comp, vertexId, vbuf, uintbuf); + assembler.fillIndexBuffer(comp, numIndices, vertexId, ibuf); + numVertices += data.vertexCount; + numIndices += data.indexCount; + } + + let count = end - start; + + let device = this._device; + let vb = this._vbPool.add(); + device._stats.vb -= vb._bytes; + vb._format = vertexFormat; + vb._numVertices = numVertices; + vb._bytes = vertexFormat._bytes * numVertices; + vb.update(0, vbuf); + device._stats.vb += vb._bytes; + + let ib = this._ibPool.add(); + device._stats.ib -= ib._bytes; + ib._numIndices = numIndices; + ib._bytes = 2 * numIndices; + ib.update(0, ibuf); + device._stats.ib += ib._bytes; + + let ia = this._iaPool.add(); + ia._vertexBuffer = vb; + ia._indexBuffer = ib; + ia._start = 0; + ia._count = numIndices; + + let model = this._modelPool.add(); + this._batchedModels.push(model); + model.sortKey = this._sortKey++; + model._viewID = -1; + model.setNode(this._dummyNode); + model.addEffect(effect); + model.addInputAssembler(ia); + + return model; + }, + + visit (scene) { + this.reset(); + + // Store all render components to _queue + scene.walk(this._handleRender); + + let comp, effect, assembler, data; + let currEffect = null; + let vertexFormat = null; + let vertexCount = 0; + let indexCount = 0; + let start = 0; + + for (let i = 0, len = _queue.length; i < len; i++) { + comp = _queue[i]; + effect = comp.getEffect(); + assembler = comp.constructor._assembler; + if (!assembler || !effect) { + continue; + } + + // Update render data + assembler.updateRenderData(comp); + data = comp._renderData; + + if (currEffect != effect) { + vertexFormat = comp._vertexFormat; + // breaking batch + if (vertexCount > 0 && indexCount > 0) { + this._genModel(vertexCount, vertexFormat, indexCount, _queue, start, i); + } + start = i; + currEffect = effect; + } + + vertexCount += data.vertexCount; + indexCount += data.indexCount; + } + + // last batch + if (vertexCount > 0 && indexCount > 0) { + vertexFormat = _queue[start]._vertexFormat; + this._genModel(vertexCount, vertexFormat, indexCount, _queue, start, _queue.length); + } + } +} + +module.exports = RenderComponentWalker; \ No newline at end of file diff --git a/cocos2d/core/renderer/render-engine.js b/cocos2d/core/renderer/render-engine.js index 63e0a9eddb..a2f01aa06c 100644 --- a/cocos2d/core/renderer/render-engine.js +++ b/cocos2d/core/renderer/render-engine.js @@ -7774,9 +7774,9 @@ module.exports = (function () { return; } - let gl = this._device._gl; + let gl = this.device.gl; gl.deleteBuffer(this._glID); - this._device._stats.ib -= this.bytes; + this.device._stats.ib -= this.bytes; this._glID = -1; } @@ -7853,9 +7853,9 @@ module.exports = (function () { return; } - let gl = this._device._gl; + let gl = this.device.gl; gl.deleteBuffer(this._glID); - this._device._stats.vb -= this.bytes; + this.device._stats.vb -= this.bytes; this._glID = -1; } @@ -8107,10 +8107,10 @@ module.exports = (function () { return; } - let gl = this._device._gl; + let gl = this.device.gl; gl.deleteTexture(this._glID); - this._device._stats.tex -= this.bytes; + this.device._stats.tex -= this.bytes; this._glID = -1; } } @@ -10994,7 +10994,7 @@ module.exports = (function () { } } - class Model { + class Model$1 { constructor() { this._poolID = -1; this._node = null; @@ -13762,7 +13762,7 @@ module.exports = (function () { Light, Camera, - Model, + Model: Model$1, Scene: Scene$1, Base, @@ -13770,79 +13770,6 @@ module.exports = (function () { }; Object.assign(renderer, enums); - class SharedArrayBuffer { - - constructor (byteLength) { - this.byteLength = byteLength; - this.data = new ArrayBuffer(this.byteLength); - this._spaces = { - 0: this.byteLength - }; - } - - _alloc (offset, size) { - var space = this._spaces[offset]; - if (space && space >= size) { - // Remove the space - delete this._spaces[offset]; - if (space > size) { - var newOffset = offset + size; - this._spaces[newOffset] = space - size; - } - return true; - } - else { - return false; - } - } - - request (size) { - var key, offset, available; - for (key in this._spaces) { - offset = parseInt(key); - available = this._spaces[key]; - if (available >= size && this._alloc(offset, size)) { - return offset; - } - } - return -1; - } - - free (offset, size) { - var spaces = this._spaces; - var i, key, end; - // Merge with previous space - for (key in spaces) { - i = parseInt(key); - if (i > offset) { - break; - } - if (i + spaces[key] >= offset) { - size = size + offset - i; - offset = i; - break; - } - } - - end = offset + size; - // Merge with next space - if (this._spaces[end]) { - size += this._spaces[end]; - delete this._spaces[end]; - } - - this._spaces[offset] = size; - } - - reset () { - this._spaces = { - 0: this.byteLength - }; - } - } - - let InputAssembler = renderer.InputAssembler; - let _camPos = vec3.create(); let _camFwd = vec3.create(); let _v3_tmp1 = vec3.create(); @@ -13851,101 +13778,17 @@ module.exports = (function () { let _a16_proj = new Float32Array(16); let _a16_viewProj = new Float32Array(16); - const PER_INDEX_BYTE = 2; - // 500 Quad + 750 Index - const MIN_SHARED_BUFFER_SIZE = 54000; - // 2000 Quad + 3000 Index - const MAX_SHARED_BUFFER_SIZE = 216000; - var _buffers = []; - var _newBuffer = { - buffer: null, - offset: -1 - }; - // Add stage to renderer renderer.addStage('transparent'); - function _createNewBuffer (bytes) { - // Allocate buffer - let buffer = null, offset = -1; - for (let i = 0, l = _buffers.length; i < l; i++) { - buffer = _buffers[i]; - offset = buffer.request(bytes); - if (offset !== -1) { - break; - } - } - if (offset === -1) { - let bufferSize = 0; - if (bytes > MAX_SHARED_BUFFER_SIZE) { - bufferSize = bytes; - } - else { - bufferSize = Math.max(bytes * 2, MIN_SHARED_BUFFER_SIZE); - } - buffer = new SharedArrayBuffer(bufferSize); - _buffers.push(buffer); - offset = buffer.request(bytes); - } - _newBuffer.buffer = buffer.data; - _newBuffer.offset = offset; - return _newBuffer; - } - class ForwardRenderer$1 extends renderer.Base { constructor (device, builtin) { super(device, builtin); - - let defaultFormat = new gfx.VertexFormat([]); - this._vbPool = new RecyclePool(function () { - return new gfx.VertexBuffer( - device, - defaultFormat, - gfx.USAGE_DYNAMIC, - null, - 0 - ); - }, 16); - this._ibPool = new RecyclePool(function () { - return new gfx.IndexBuffer( - device, - gfx.INDEX_FMT_UINT16, - gfx.USAGE_STATIC, - null, - 0 - ); - }, 16); - this._iaPool = new RecyclePool(function () { - return new InputAssembler(); - }, 16); - - this._batchedItems = null; - this._registerStage('transparent', this._transparentStage.bind(this)); } - reset () { - // Reset intermediate datas - for (let i = 0; i < _buffers.length; i++) { - _buffers[i].reset(); - } - this._vbPool.reset(); - this._ibPool.reset(); - this._iaPool.reset(); - this._batchedItems = null; - // Reset renderer internal datas - this._reset(); - } - render (scene) { - this.reset(); - - // visit logic node tree to get zorders - // scene.visit(); - - // batched stage items, will be released every frame by _reset function - this._batchedItems = this._stageItemsPools.add(); - this._batchedItems.reset(); + this._reset(); for (let i = 0; i < scene._cameras.length; ++i) { let view = scene._cameras.data[i].getView(); @@ -13953,99 +13796,15 @@ module.exports = (function () { } } - batchItem (items, start, end, vbuf, ibuf) { - let uintbuf = new Uint32Array(vbuf.buffer, vbuf.byteOffset, vbuf.length); - let stageItem = this._batchedItems.add(); - let item0 = items.data[start]; - let vformat = item0.model.vertexFormat; - stageItem.model = null; - stageItem.node = item0.node; - stageItem.effect = item0.effect; - stageItem.options = item0.options; - stageItem.technique = item0.technique; - stageItem.sortKey = -1; - - let numIndices = 0; - let numVertices = 0; - for (let i = start; i < end; i++) { - let item = items.data[i]; - let vertexId = numVertices; - numVertices += item.model.fillVertexBuffer(vertexId, vbuf, uintbuf); - numIndices += item.model.fillIndexBuffer(numIndices, vertexId, ibuf); - } - - let count = end - start; - - let device = this._device; - let vb = this._vbPool.add(); - device._stats.vb -= vb._bytes; - vb._format = item0.model.vertexFormat; - vb._numVertices = numVertices; - vb._bytes = vformat._bytes * numVertices; - vb.update(0, vbuf); - device._stats.vb += vb._bytes; - - let ib = this._ibPool.add(); - device._stats.ib -= ib._bytes; - ib._numIndices = numIndices; - ib._bytes = 2 * numIndices; - ib.update(0, ibuf); - device._stats.ib += ib._bytes; - - let ia = this._iaPool.add(); - ia._vertexBuffer = vb; - ia._indexBuffer = ib; - stageItem.ia = ia; - return stageItem; - } - _transparentStage (view, items) { // update uniforms this._device.setUniform('view', mat4.array(_a16_view, view._matView)); this._device.setUniform('proj', mat4.array(_a16_proj, view._matProj)); this._device.setUniform('viewProj', mat4.array(_a16_viewProj, view._matViewProj)); - // Culling and batch stage items - let currEffect = null; - let vertexFormat = null; - let vertexCount = 0; - let indexCount = 0; - let start = 0; - for (let i = 0, l = items.length; i < l; ++i) { - let item = items.data[i]; - if (currEffect != item.effect) { - // breaking batch - if (vertexCount > 0 && indexCount > 0) { - let vertexBytes = vertexCount * vertexFormat._bytes; - let buf = _createNewBuffer(vertexBytes); - let vbuf = new Float32Array(buf.buffer, buf.offset, vertexBytes / 4); - buf = _createNewBuffer(indexCount * PER_INDEX_BYTE); - let ibuf = new Uint16Array(buf.buffer, buf.offset, indexCount); - this.batchItem(items, start, i, vbuf, ibuf); - vertexCount = 0; - indexCount = 0; - } - start = i; - currEffect = item.effect; - vertexFormat = item.model.vertexFormat; - } - - vertexCount += item.model.vertexCount; - indexCount += item.model.indexCount; - } - - if (vertexCount > 0 && indexCount > 0) { - let vertexBytes = vertexCount * vertexFormat._bytes; - let buf = _createNewBuffer(vertexBytes); - let vbuf = new Float32Array(buf.buffer, buf.offset, vertexBytes / 4); - buf = _createNewBuffer(indexCount * PER_INDEX_BYTE); - let ibuf = new Uint16Array(buf.buffer, buf.offset, indexCount); - this.batchItem(items, start, items.length, vbuf, ibuf); - } - // draw it - for (let i = 0; i < this._batchedItems.length; ++i) { - let item = this._batchedItems.data[i]; + for (let i = 0; i < items.length; ++i) { + let item = items.data[i]; this._draw(item); } } @@ -14396,7 +14155,7 @@ module.exports = (function () { this._color = color4.new(0, 0, 0, 1); this._depth = 1; this._stencil = 1; - this._clearFlags = gfx.CLEAR_COLOR | gfx.CLEAR_DEPTH; + this._clearFlags = renderer.CLEAR_COLOR | renderer.CLEAR_DEPTH; // projection properties this._near = 0.1; @@ -14498,541 +14257,81 @@ module.exports = (function () { ORTHO: 1 }; - var _vertexFormat = new gfx.VertexFormat([ - { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, - { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true }, - { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 } - ]); - - var _matrix = mat4.create(); - var _pool; - class SpriteModel { + class RenderData { constructor () { - this._node = null; - this._viewID = -1; - this._poolID = -1; - this._frame = null; - this._effect = null; - this._option = null; - this._texture = null; - this._trimmed = true; - this._uv = { - l: 0, - r: 1, - b: 0, - t: 1 + this._verts = { + x: [], + y: [] }; + this._uvs = { + u: [], + v: [] + }; + + this._pivotX = 0; + this._pivotY = 0; + this._width = 0; + this._height = 0; + + this.vertexCount = 0; + this.indexCount = 0; + + this.uvDirty = true; + this.vertDirty = true; + } + + get xysLength () { + return this._verts.x.length; + } + + set xysLength (length) { + this._verts.x.length = length; + this._verts.y.length = length; } - _updateUV () { - let frame = this._frame; - if (this._effect) { - let texture = this._effect.getValue('texture'); - let texw = texture._width, - texh = texture._height; - let rect = frame._rect; - let l, b, r, t; - - if (this._trimmed) { - l = rect.x; - t = rect.y; - r = rect.x + rect.width; - b = rect.y + rect.height; - } else { - let originalSize = frame._originalSize; - let offset = frame._offset; - let ow = originalSize.width, - oh = originalSize.height, - rw = rect.width, - rh = rect.height; - let ox = rect.x + (rw - ow) / 2 - offset.x; - let oy = rect.y + (rh - oh) / 2 - offset.y; - - l = ox; - t = oy; - r = ox + ow; - b = oy + oh; - } - - this._uv.l = texw === 0 ? 0 : l / texw; - this._uv.r = texw === 0 ? 0 : r / texw; - this._uv.b = texh === 0 ? 0 : b / texh; - this._uv.t = texh === 0 ? 0 : t / texh; - } + get uvsLength () { + return this._uvs.u.length; } - setNode (node) { - this._node = node; + set uvsLength (length) { + this._uvs.u.length = length; + this._uvs.v.length = length; } - setEffect (effect) { - this._effect = effect; - if (effect) { - let opt = Object.create(null); - effect.extractOptions(opt); - this._option = opt; - } - else { - this._option = null; + updateSizeNPivot (width, height, pivotX, pivotY) { + if (width !== this._width || + height !== this._height || + pivotX !== this._pivotX || + pivotY !== this._pivotY) + { + this._width = width; + this._height = height; + this._pivotX = pivotX; + this._pivotY = pivotY; + this.vertDirty = true; } } - get spriteFrame () { - return this._frame; - } - - set spriteFrame (frame) { - this._frame = frame; - this._updateUV(); - } - - get trimmed () { - return this._trimmed; - } - - set trimmed (trimmed) { - this._trimmed = !!trimmed; - this._updateUV(); - } - - get drawItemCount () { - return 1; - } - - get vertexFormat () { - return _vertexFormat; - } - - get vertexCount () { - return 4; - } - - get indexCount () { - return 6; - } - - extractDrawItem (out, index) { - out.model = this; - out.node = this._node; - out.ia = null; - out.effect = this._effect; - out.options = out.effect.extractOptions(this._option); - } - - fillVertexBuffer (index, vbuf, uintbuf) { - let texture = this._effect.getValue('texture'); - if (texture !== this._texture) { - this._updateUV(); - this._texture = texture; - } - - let off = index * _vertexFormat._bytes / 4; - let node = this._node; - let uv = this._uv; - // for position - node.getWorldMatrix(_matrix); - let a = _matrix.m00, - b = _matrix.m01, - c = _matrix.m04, - d = _matrix.m05, - tx = _matrix.m12, - ty = _matrix.m13; - - // for color - let color = ((255<<24) >>> 0) + (255<<16) + (255<<8) + 255; - - // Assign vertex data - let frame = this._frame, - width, height; - if (this._trimmed) { - width = frame._rect.width; - height = frame._rect.height; - } - else { - width = frame._originalSize.width; - height = frame._originalSize.height; - } - - let appx = node._anchorPoint.x*width, appy = node._anchorPoint.y*height; - if (appx || appy) { - tx -= a * appx + c * appy; - ty -= b * appx + d * appy; - } - - let top = height, - right = width, - bottom = 0, - left = 0; - let z = node.lpos === undefined ? node.z : node.lpos.z; - // bl - vbuf[off++] = left * a + bottom * c + tx; - vbuf[off++] = left * b + bottom * d + ty; - vbuf[off++] = z; - uintbuf[off++] = color; - vbuf[off++] = uv.l; - vbuf[off++] = uv.b; - // br - vbuf[off++] = right * a + bottom * c + tx; - vbuf[off++] = right * b + bottom * d + ty; - vbuf[off++] = z; - uintbuf[off++] = color; - vbuf[off++] = uv.r; - vbuf[off++] = uv.b; - // tl - vbuf[off++] = left * a + top * c + tx; - vbuf[off++] = left * b + top * d + ty; - vbuf[off++] = z; - uintbuf[off++] = color; - vbuf[off++] = uv.l; - vbuf[off++] = uv.t; - // tr - vbuf[off++] = right * a + top * c + tx; - vbuf[off++] = right * b + top * d + ty; - vbuf[off++] = z; - uintbuf[off++] = color; - vbuf[off++] = uv.r; - vbuf[off++] = uv.t; - - return 4; - } - - fillIndexBuffer (offset, vertexId, ibuf) { - ibuf[offset + 0] = vertexId; - ibuf[offset + 1] = vertexId + 1; - ibuf[offset + 2] = vertexId + 2; - ibuf[offset + 3] = vertexId + 1; - ibuf[offset + 4] = vertexId + 3; - ibuf[offset + 5] = vertexId + 2; - return 6; - } - - // Canvas draw - draw (ctx) { - let texture = this._effect.getValue('texture'); - if (texture !== this._texture) { - this._texture = texture; - } - - this._node.getWorldMatrix(_matrix); - let a = _matrix.m00, - b = _matrix.m01, - c = _matrix.m04, - d = _matrix.m05, - tx = _matrix.m12, - ty = _matrix.m13; - - ctx.transform(a, b, c, d, tx, ty); - - let frame = this._frame; - let dx = -frame.width/2, - dy = -frame.height/2, - dw = frame.width, - dh = frame.height, - sx = frame.x, - sy = frame.y, - sw = frame.width, - sh = frame.height; - ctx.drawImage(texture._image, sx, sy, sw, sh, dx, dy, dw, dh); - } - static alloc () { return _pool.alloc(); } - static free (model) { - if (model instanceof SpriteModel) { - model._node = null; - model._frame = null; - model._effect = null; - model._texture = null; - model._trimmed = true; + static free (data) { + if (data instanceof RenderData) { + data._verts.x.length = 0; + data._verts.y.length = 0; + data._uvs.u.length = 0; + data._uvs.v.length = 0; _pool.free(model); } } } _pool = new Pool(() => { - return new SpriteModel(); - }, 8); - - var _matrix$1 = mat4.create(); - var _x = [0, 0, 0, 0]; - var _y = [0, 0, 0, 0]; - var _vertex = { - x: [ - [0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0] - ], - y: [ - [0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0], - [0, 0, 0, 0] - ] - }; - - var _pool$1; - - class SlicedModel { - constructor() { - this._node = null; - this._viewID = -1; - this._poolID = -1; - this._frame = null; - this._effect = null; - this._option = null; - this._texture = null; - this._uv = { - u: [0, 0, 0, 0], - v: [0, 0, 0, 0] - }; - } - - _updateUV () { - let frame = this._frame; - if (this._effect) { - let texture = this._effect.getValue('texture'); - let rect = frame._rect; - let atlasWidth = texture._width; - let atlasHeight = texture._height; - - // caculate texture coordinate - let leftWidth = frame.insetLeft; - let rightWidth = frame.insetRight; - let centerWidth = rect.width - leftWidth - rightWidth; - let topHeight = frame.insetTop; - let bottomHeight = frame.insetBottom; - let centerHeight = rect.height - topHeight - bottomHeight; - - // uv computation should take spritesheet into account. - let u = this._uv.u; - let v = this._uv.v; - if (frame._rotated) { - u[0] = (rect.x) / atlasWidth; - u[1] = (bottomHeight + rect.x) / atlasWidth; - u[2] = (bottomHeight + centerHeight + rect.x) / atlasWidth; - u[3] = (rect.x + rect.height) / atlasWidth; - - v[0] = (rect.y) / atlasHeight; - v[1] = (leftWidth + rect.y) / atlasHeight; - v[2] = (leftWidth + centerWidth + rect.y) / atlasHeight; - v[3] = (rect.y + rect.width) / atlasHeight; - } - else { - u[0] = (rect.x) / atlasWidth; - u[1] = (leftWidth + rect.x) / atlasWidth; - u[2] = (leftWidth + centerWidth + rect.x) / atlasWidth; - u[3] = (rect.x + rect.width) / atlasWidth; - - v[3] = (rect.y) / atlasHeight; - v[2] = (topHeight + rect.y) / atlasHeight; - v[1] = (topHeight + centerHeight + rect.y) / atlasHeight; - v[0] = (rect.y + rect.height) / atlasHeight; - } - } - } - - setNode(node) { - this._node = node; - } - - setEffect(effect) { - this._effect = effect; - if (effect) { - let opt = Object.create(null); - effect.extractOptions(opt); - this._option = opt; - } - else { - this._option = null; - } - } - - get spriteFrame () { - return this._frame; - } - - set spriteFrame (frame) { - this._frame = frame; - this._updateUV(); - } - - get drawItemCount() { - return 1; - } - - get vertexFormat () { - return _vertexFormat; - } - - get vertexCount () { - return 36; - } - - get indexCount () { - return 54; - } - - extractDrawItem(out, index) { - out.model = this; - out.node = this._node; - out.ia = null; - out.effect = this._effect; - out.options = out.effect.extractOptions(this._option); - } - - _updateVertex (node) { - node.getWorldMatrix(_matrix$1); - let a = _matrix$1.m00, - b = _matrix$1.m01, - c = _matrix$1.m04, - d = _matrix$1.m05, - tx = _matrix$1.m12, - ty = _matrix$1.m13; - - let appx = node._anchorPoint.x * node.width, appy = node._anchorPoint.y * node.height; - if (appx || appy) { - tx -= a * appx + c * appy; - ty -= b * appx + d * appy; - } - - let frame = this._frame; - let rect = frame._rect; - let leftWidth = frame.insetLeft; - let rightWidth = frame.insetRight; - let topHeight = frame.insetTop; - let bottomHeight = frame.insetBottom; - - let sizableWidth = node.width - leftWidth - rightWidth; - let sizableHeight = node.height - topHeight - bottomHeight; - let xScale = node.width / (leftWidth + rightWidth); - let yScale = node.height / (topHeight + bottomHeight); - xScale = (isNaN(xScale) || xScale > 1) ? 1 : xScale; - yScale = (isNaN(yScale) || yScale > 1) ? 1 : yScale; - sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; - sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; - let x = _x; - let y = _y; - x[0] = 0; - x[1] = leftWidth * xScale; - x[2] = x[1] + sizableWidth; - x[3] = node.width; - y[0] = 0; - y[1] = bottomHeight * yScale; - y[2] = y[1] + sizableHeight; - y[3] = node.height; - - let vx = _vertex.x; - let vy = _vertex.y; - for (let row = 0; row < 4; row++) { - for (let col = 0; col < 4; col++) { - vx[row][col] = x[col] * a + y[row] * c + tx; - vy[row][col] = x[col] * b + y[row] * d + ty; - } - } - } - - fillVertexBuffer (index, vbuf, uintbuf) { - let texture = this._effect.getValue('texture'); - if (texture !== this._texture) { - this._updateUV(); - this._texture = texture; - } - - let offset = index * _vertexFormat._bytes / 4; - let node = this._node; - let frame = this._frame; - - // for color - let color = ((255<<24) >>> 0) + (255<<16) + (255<<8) + 255; - - // Assign vertex data - this._updateVertex(node); - let x = _vertex.x; - let y = _vertex.y; - let z = node.lpos === undefined ? node.z : node.lpos.z; - let u = this._uv.u; - let v = this._uv.v; - for (let r = 0; r < 3; ++r) { - for (let c = 0; c < 3; ++c) { - // lb - vbuf[offset] = x[r][c]; - vbuf[offset + 1] = y[r][c]; - vbuf[offset + 2] = z; - uintbuf[offset + 3] = color; - vbuf[offset + 4] = u[c]; - vbuf[offset + 5] = v[r]; - offset += 6; - // rb - vbuf[offset] = x[r][c+1]; - vbuf[offset + 1] = y[r][c+1]; - vbuf[offset + 2] = z; - uintbuf[offset + 3] = color; - vbuf[offset + 4] = u[c+1]; - vbuf[offset + 5] = v[r]; - offset += 6; - // lt - vbuf[offset] = x[r+1][c]; - vbuf[offset + 1] = y[r+1][c]; - vbuf[offset + 2] = z; - uintbuf[offset + 3] = color; - vbuf[offset + 4] = u[c]; - vbuf[offset + 5] = v[r+1]; - offset += 6; - // rt - vbuf[offset] = x[r+1][c+1]; - vbuf[offset + 1] = y[r+1][c+1]; - vbuf[offset + 2] = z; - uintbuf[offset + 3] = color; - vbuf[offset + 4] = u[c+1]; - vbuf[offset + 5] = v[r+1]; - offset += 6; - } - } - return 36; - } - - fillIndexBuffer (offset, vertexId, ibuf) { - for (let r = 0; r < 3; ++r) { - for (let c = 0; c < 3; ++c) { - ibuf[offset++] = vertexId; - ibuf[offset++] = vertexId + 1; - ibuf[offset++] = vertexId + 2; - ibuf[offset++] = vertexId + 1; - ibuf[offset++] = vertexId + 3; - ibuf[offset++] = vertexId + 2; - vertexId += 4; - } - } - return 54; - } - - draw () { - - } - - static alloc () { - return _pool$1.alloc(); - } - - static free (model) { - if (model instanceof SlicedModel) { - model._node = null; - model._frame = null; - model._effect = null; - model._texture = null; - _pool$1.free(model); - } - } - } - - _pool$1 = new Pool(() => { - return new SlicedModel(); - }, 8); + return new RenderData(); + }, 32); class Asset { constructor(persist = true) { @@ -15062,7 +14361,7 @@ module.exports = (function () { super(false); var pass = new renderer.Pass('sprite'); - pass.setDepth(true, false); + pass.setDepth(false, false); pass.setCullMode(gfx.CULL_NONE); pass.setBlend( gfx.BLEND_FUNC_ADD, @@ -15162,6 +14461,8 @@ module.exports = (function () { const ForwardRenderer = renderMode.supportWebGL ? ForwardRenderer$1 : ForwardRenderer$2; const Texture2D = renderMode.supportWebGL ? gfx.Texture2D : canvas.Texture2D; const Device = renderMode.supportWebGL ? gfx.Device : canvas.Device; + const Model = renderer.Model; + const InputAssembler = renderer.InputAssembler; let renderEngine = { // core classes @@ -15172,10 +14473,9 @@ module.exports = (function () { // render scene Scene, Camera: Camera$1, - - // models - SpriteModel, - SlicedModel, + Model, + RenderData, + InputAssembler, // assets Asset, @@ -15188,10 +14488,12 @@ module.exports = (function () { shaders, // utils - SharedArrayBuffer, renderMode, MaterialUtil, + // memop + RecyclePool, + // modules math, renderer, diff --git a/cocos2d/core/renderer/shared-array-buffer.js b/cocos2d/core/renderer/shared-array-buffer.js new file mode 100644 index 0000000000..69b3278a55 --- /dev/null +++ b/cocos2d/core/renderer/shared-array-buffer.js @@ -0,0 +1,73 @@ +function SharedArrayBuffer (byteLength) { + this.byteLength = byteLength; + this.data = new ArrayBuffer(this.byteLength); + this._spaces = { + 0: this.byteLength + }; +} + +SharedArrayBuffer.prototype = { + constructor: SharedArrayBuffer, + + _alloc (offset, size) { + var space = this._spaces[offset]; + if (space && space >= size) { + // Remove the space + delete this._spaces[offset]; + if (space > size) { + var newOffset = offset + size; + this._spaces[newOffset] = space - size; + } + return true; + } + else { + return false; + } + }, + + request (size) { + var key, offset, available; + for (key in this._spaces) { + offset = parseInt(key); + available = this._spaces[key]; + if (available >= size && this._alloc(offset, size)) { + return offset; + } + } + return -1; + }, + + free (offset, size) { + var spaces = this._spaces; + var i, key, end; + // Merge with previous space + for (key in spaces) { + i = parseInt(key); + if (i > offset) { + break; + } + if (i + spaces[key] >= offset) { + size = size + offset - i; + offset = i; + break; + } + } + + end = offset + size; + // Merge with next space + if (this._spaces[end]) { + size += this._spaces[end]; + delete this._spaces[end]; + } + + this._spaces[offset] = size; + }, + + reset () { + this._spaces = { + 0: this.byteLength + }; + } +}; + +module.exports = SharedArrayBuffer; \ No newline at end of file diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 1fc6288faf..2dcbc3add9 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -120,11 +120,11 @@ function _walk (root, prefunc, postfunc) { } if (afterChildren) { // post call - postfunc(curr); + postfunc && postfunc(curr); } else { // pre call - prefunc(curr); + prefunc && prefunc(curr); } // Avoid memory leak @@ -667,7 +667,7 @@ var BaseNode = cc.Class({ * @param {Function} prefunc The callback to process node when reach the node for the first time * @param {_BaseNode} prefunc.target The current visiting node * @param {Function} postfunc The callback to process node when re-visit the node after walked all children in its sub tree - * @param {_BaseNode} prefunc.target The current visiting node + * @param {_BaseNode} postfunc.target The current visiting node * @example * node.walk(function (target) { * console.log('Walked through node ' + target.name + ' for the first time');