diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 92354855af..ab2deef17f 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -30,6 +30,7 @@ const AutoReleaseUtils = require('./load-pipeline/auto-release-utils'); const ComponentScheduler = require('./component-scheduler'); const NodeActivator = require('./node-activator'); const EventListeners = require('./event/event-listeners'); +const Obj = require('./platform/CCObject'); const renderer = require('./renderer'); const eventManager = require('./event-manager'); @@ -120,7 +121,7 @@ cc.Director = function () { // FPS this._totalFrames = 0; - this._lastUpdate = Date.now(); + this._lastUpdate = performance.now(); this._deltaTime = 0.0; // Scheduler for user registration update @@ -134,7 +135,7 @@ cc.Director = function () { var self = this; cc.game.on(cc.game.EVENT_SHOW, function () { - self._lastUpdate = Date.now(); + self._lastUpdate = performance.now(); }); }; @@ -142,7 +143,7 @@ cc.Director.prototype = { constructor: cc.Director, init: function () { this._totalFrames = 0; - this._lastUpdate = Date.now(); + this._lastUpdate = performance.now(); this._paused = false; this._purgeDirectorInNextLoop = false; this._winSizeInPoints = cc.size(0, 0); @@ -211,7 +212,7 @@ cc.Director.prototype = { * calculates delta time since last time it was called */ calculateDeltaTime: function () { - var now = Date.now(); + var now = performance.now(); this._deltaTime = (now - this._lastUpdate) / 1000; if ((cc.game.config[cc.game.CONFIG_KEY.debugMode] > 0) && (this._deltaTime > 1)) @@ -440,7 +441,7 @@ cc.Director.prototype = { this._scene = null; // purge destroyed nodes belongs to old scene - cc.Object._deferredDestroy(); + Obj._deferredDestroy(); CC_BUILD && CC_DEBUG && console.timeEnd('Destroy'); if (onBeforeLoadScene) { @@ -673,7 +674,7 @@ cc.Director.prototype = { return; } - this._lastUpdate = Date.now(); + this._lastUpdate = performance.now(); if (!this._lastUpdate) { cc.logID(1200); } @@ -899,7 +900,7 @@ cc.Director.prototype = { */ startAnimation: function () { this.invalid = false; - this._lastUpdate = Date.now(); + this._lastUpdate = performance.now(); }, /* @@ -913,6 +914,7 @@ cc.Director.prototype = { * Run main loop of director */ mainLoop: CC_EDITOR ? function (deltaTime, updateAnimate) { + // Update if (!this._paused) { this.emit(cc.Director.EVENT_BEFORE_UPDATE); @@ -928,12 +930,15 @@ cc.Director.prototype = { this.emit(cc.Director.EVENT_AFTER_UPDATE); } - this.emit(cc.Director.EVENT_BEFORE_DRAW); // Render + this.emit(cc.Director.EVENT_BEFORE_DRAW); renderer.render(this._scene); - this._totalFrames++; + + // After draw this.emit(cc.Director.EVENT_AFTER_DRAW); + this._totalFrames++; + } : function () { if (this._purgeDirectorInNextLoop) { this._purgeDirectorInNextLoop = false; @@ -943,6 +948,7 @@ cc.Director.prototype = { // calculate "global" dt this.calculateDeltaTime(); + // Update if (!this._paused) { this.emit(cc.Director.EVENT_BEFORE_UPDATE); // Call start for new added components @@ -956,15 +962,18 @@ cc.Director.prototype = { // User can use this event to do things after update this.emit(cc.Director.EVENT_AFTER_UPDATE); // Destroy entities that have been removed recently - cc.Object._deferredDestroy(); + Obj._deferredDestroy(); } - this.emit(cc.Director.EVENT_BEFORE_DRAW); + // Render + this.emit(cc.Director.EVENT_BEFORE_DRAW); renderer.render(this._scene); - this._totalFrames++; + + // After draw this.emit(cc.Director.EVENT_AFTER_DRAW); - + eventManager.frameUpdateListeners(); + this._totalFrames++; } }, diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index b94b5dc7ab..76c27c3382 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -43,7 +43,6 @@ const POSITION_CHANGED = 'position-changed'; const SIZE_CHANGED = 'size-changed'; const ANCHOR_CHANGED = 'anchor-changed'; const ROTATION_CHANGED = 'rotation-changed'; -const WORLD_MATRIX_CHANGED = 'world-matrix-changed'; const SCALE_CHANGED = 'scale-changed'; const CHILD_REORDER = 'child-reorder'; @@ -55,8 +54,17 @@ var emptyFunc = function () {}; var _mat4_temp = math.mat4.create(); var _vec3_temp = math.vec3.create(); var _quat_temp = math.quat.create(); +var _parents = []; var _globalOrderOfArrival = 1; +const POSITION_DIRTY_FLAG = 1 << 0; +const SCALE_DIRTY_FLAG = 1 << 1; +const ROTATION_DIRTY_FLAG = 1 << 2; +const SKEW_DIRTY_FLAG = 1 << 3; +// rotation transform dirty +const RT_DIRTY_FLAG = SCALE_DIRTY_FLAG | ROTATION_DIRTY_FLAG | SKEW_DIRTY_FLAG; +const ALL_DIRTY_FLAG = 0xffff; + /** * !#en The event type supported by Node * !#zh Node 支持的事件类型 @@ -308,6 +316,16 @@ function _checkListeners (node, events) { return true; } +function _syncWorldDirty (children) { + for (let i = 0, l = children.length; i < l; i++) { + let child = children[i]; + child._worldMatDirty = true; + if (child._children.length > 0) { + _syncWorldDirty(child._children); + } + } +} + /** * !#en * Class of all entities in Cocos Creator scenes.
@@ -421,7 +439,7 @@ var Node = cc.Class({ } localPosition.x = value; - this._localMatDirty = true; + this.setLocalDirty(POSITION_DIRTY_FLAG); // fast check event var cache = this._hasListenerCache; @@ -464,7 +482,7 @@ var Node = cc.Class({ } localPosition.y = value; - this._localMatDirty = true; + this.setLocalDirty(POSITION_DIRTY_FLAG); // fast check event var cache = this._hasListenerCache; @@ -494,7 +512,7 @@ var Node = cc.Class({ if (value !== localPosition.z) { if (!CC_EDITOR || isFinite(value)) { localPosition.z = value; - this._localMatDirty = true; + this.setLocalDirty(POSITION_DIRTY_FLAG); } else { cc.error(ERR_INVALID_NUMBER, 'new z'); @@ -524,7 +542,7 @@ var Node = cc.Class({ this._rotationX = this._rotationY = value; // Update quaternion from rotation math.quat.fromEuler(this._quat, 0, 0, -value); - this._localMatDirty = true; + this.setLocalDirty(ROTATION_DIRTY_FLAG); var cache = this._hasListenerCache; if (cache && cache[ROTATION_CHANGED]) { @@ -557,7 +575,7 @@ var Node = cc.Class({ else { math.quat.fromEuler(this._quat, value, this._rotationY, 0); } - this._localMatDirty = true; + this.setLocalDirty(ROTATION_DIRTY_FLAG); var cache = this._hasListenerCache; if (cache && cache[ROTATION_CHANGED]) { @@ -590,7 +608,7 @@ var Node = cc.Class({ else { math.quat.fromEuler(this._quat, this._rotationX, value, 0); } - this._localMatDirty = true; + this.setLocalDirty(ROTATION_DIRTY_FLAG); var cache = this._hasListenerCache; if (cache && cache[ROTATION_CHANGED]) { @@ -625,7 +643,7 @@ var Node = cc.Class({ set (value) { if (this._scale.x !== value) { this._scale.x = value; - this._localMatDirty = true; + this.setLocalDirty(SCALE_DIRTY_FLAG); var cache = this._hasListenerCache; if (cache && cache[SCALE_CHANGED]) { @@ -651,7 +669,7 @@ var Node = cc.Class({ set (value) { if (this._scale.y !== value) { this._scale.y = value; - this._localMatDirty = true; + this.setLocalDirty(SCALE_DIRTY_FLAG); var cache = this._hasListenerCache; if (cache && cache[SCALE_CHANGED]) { @@ -676,7 +694,7 @@ var Node = cc.Class({ }, set (value) { this._skewX = value; - this._localMatDirty = true; + this.setLocalDirty(SKEW_DIRTY_FLAG); } }, @@ -695,7 +713,7 @@ var Node = cc.Class({ }, set (value) { this._skewY = value; - this._localMatDirty = true; + this.setLocalDirty(SKEW_DIRTY_FLAG); } }, @@ -908,8 +926,9 @@ var Node = cc.Class({ this._matrix = mathPools.mat4.get(); this._worldMatrix = mathPools.mat4.get(); - this._localMatDirty = true; - this._worldMatDirty = true; + this._localMatDirty = 0; + this._worldMatDirty = false; + this.setLocalDirty(ALL_DIRTY_FLAG); this._cullingMask = 1 << this.groupIndex; }, @@ -983,6 +1002,7 @@ var Node = cc.Class({ var actionManager = ActionManagerExist ? cc.director.getActionManager() : null; if (active) { // activate + // ActionManager & EventManager actionManager && actionManager.resumeTarget(this); eventManager.resumeTarget(this); if (this._touchListener) { @@ -1506,7 +1526,7 @@ var Node = cc.Class({ */ setPosition (newPosOrX, y) { var x; - if (typeof y === 'undefined') { + if (y === undefined) { x = newPosOrX.x; y = newPosOrX.y; } @@ -1535,7 +1555,7 @@ var Node = cc.Class({ else { return cc.error(ERR_INVALID_NUMBER, 'y of new position'); } - this._localMatDirty = true; + this.setLocalDirty(POSITION_DIRTY_FLAG); // fast check event var cache = this._hasListenerCache; @@ -1577,7 +1597,7 @@ var Node = cc.Class({ * node.setScale(1, 1); */ setScale (scaleX, scaleY) { - if (typeof scaleX === 'object') { + if (scaleX && typeof scaleX !== 'number') { scaleY = scaleX.y; scaleX = scaleX.x; } @@ -1587,7 +1607,7 @@ var Node = cc.Class({ if (this._scale.x !== scaleX || this._scale.y !== scaleY) { this._scale.x = scaleX; this._scale.y = scaleY; - this._localMatDirty = true; + this.setLocalDirty(SCALE_DIRTY_FLAG); var cache = this._hasListenerCache; if (cache && cache[SCALE_CHANGED]) { @@ -1725,7 +1745,7 @@ var Node = cc.Class({ locAnchorPoint.x = point; locAnchorPoint.y = y; } - this._localMatDirty = true; + this.setLocalDirty(POSITION_DIRTY_FLAG); this.emit(ANCHOR_CHANGED); }, @@ -1792,8 +1812,7 @@ var Node = cc.Class({ else { math.vec3.copy(this._position, pos); } - - this._localMatDirty = true; + this.setLocalDirty(POSITION_DIRTY_FLAG); // fast check event var cache = this._hasListenerCache; @@ -1880,29 +1899,70 @@ var Node = cc.Class({ }, _updateLocalMatrix () { - if (this._localMatDirty) { - // Update transform - let t = this._matrix; - math.mat4.fromRTS(t, this._quat, this._position, this._scale); + let dirtyFlag = this._localMatDirty; + if (!dirtyFlag) return; - // skew - if (this._skewX || this._skewY) { - let a = t.m00, b = t.m01, c = t.m04, d = t.m05; - let skx = Math.tan(this._skewX * ONE_DEGREE); - let sky = Math.tan(this._skewY * ONE_DEGREE); - if (skx === Infinity) - skx = 99999999; - if (sky === Infinity) - sky = 99999999; - t.m00 = a + c * sky; - t.m01 = b + d * sky; - t.m04 = c + a * skx; - t.m05 = d + b * skx; + // Update transform + let t = this._matrix; + //math.mat4.fromRTS(t, this._quat, this._position, this._scale); + + if (dirtyFlag & RT_DIRTY_FLAG) { + let hasRotation = this._rotationX || this._rotationY; + let hasSkew = this._skewX || this._skewY; + let sx = this._scale.x, sy = this._scale.y; + + if (hasRotation || hasSkew) { + let a = 1, b = 0, c = 0, d = 1; + // rotation + if (hasRotation) { + let rotationRadiansX = this._rotationX * ONE_DEGREE; + c = Math.sin(rotationRadiansX); + d = Math.cos(rotationRadiansX); + if (this._rotationY === this._rotationX) { + a = d; + b = -c; + } + else { + let rotationRadiansY = this._rotationY * ONE_DEGREE; + a = Math.cos(rotationRadiansY); + b = -Math.sin(rotationRadiansY); + } + } + // scale + t.m00 = a *= sx; + t.m01 = b *= sx; + t.m04 = c *= sy; + t.m05 = d *= sy; + // skew + if (hasSkew) { + let a = t.m00, b = t.m01, c = t.m04, d = t.m05; + let skx = Math.tan(this._skewX * ONE_DEGREE); + let sky = Math.tan(this._skewY * ONE_DEGREE); + if (skx === Infinity) + skx = 99999999; + if (sky === Infinity) + sky = 99999999; + t.m00 = a + c * sky; + t.m01 = b + d * sky; + t.m04 = c + a * skx; + t.m05 = d + b * skx; + } + } + else { + t.m00 = sx; + t.m01 = 0; + t.m04 = 0; + t.m05 = sy; } - this._localMatDirty = false; - // Register dirty status of world matrix so that it can be recalculated - this._worldMatDirty = true; } + + // position + t.m12 = this._position.x; + t.m13 = this._position.y; + + this._localMatDirty = 0; + // Register dirty status of world matrix so that it can be recalculated + this._worldMatDirty = true; }, _calculWorldMatrix () { @@ -1912,34 +1972,64 @@ var Node = cc.Class({ } // Assume parent world matrix is correct - if (this._parent) { - let parentMat = this._parent._worldMatrix; - math.mat4.mul(this._worldMatrix, parentMat, this._matrix); + let parent = this._parent; + if (parent) { + let pt = parent._worldMatrix; + let t = this._matrix; + let wt = this._worldMatrix; + let aa=t.m00, ab=t.m01, ac=t.m04, ad=t.m05, atx=t.m12, aty=t.m13; + let ba=pt.m00, bb=pt.m01, bc=pt.m04, bd=pt.m05, btx=pt.m12, bty=pt.m13; + if (bb !== 0 || bc !== 0) { + wt.m00 = aa * ba + ab * bc; + wt.m01 = aa * bb + ab * bd; + wt.m04 = ac * ba + ad * bc; + wt.m05 = ac * bb + ad * bd; + wt.m12 = ba * atx + bc * aty + btx; + wt.m13 = bb * atx + bd * aty + bty; + } + else { + wt.m00 = aa * ba; + wt.m01 = ab * bd; + wt.m04 = ac * ba; + wt.m05 = ad * bd; + wt.m12 = ba * atx + btx; + wt.m13 = bd * aty + bty; + } } else { math.mat4.copy(this._worldMatrix, this._matrix); } this._worldMatDirty = false; - - this.emit(WORLD_MATRIX_CHANGED); - - for (let i = 0, len = this._children.length; i < len; ++i) { - let child = this._children[i]; - child._calculWorldMatrix(); - } }, _updateWorldMatrix () { - let curr = this; - let changedRoot = null; - while (curr) { - if (curr._localMatDirty || curr._worldMatDirty) { - changedRoot = curr; - } - curr = curr._parent; + let n = -1; + // Find root of world matrix changing + for (let node = this; node && node._worldMatDirty; node = node._parent) { + n++; + _parents[n] = node; } - if (changedRoot) { - changedRoot._calculWorldMatrix(); + // Update world matrix of all changed parents + for (let i = n; i >= 0; i--) { + _parents[i]._calculWorldMatrix(); + _parents[i] = null; + } + }, + + setLocalDirty (flag) { + if (!this._localMatDirty) { + this.setWorldDirty(); + } + this._localMatDirty = this._localMatDirty | flag; + }, + + setWorldDirty () { + if (!this._worldMatDirty) { + this._worldMatDirty = true; + // Sync world mat dirty to sub tree + if (this._children.length > 0) { + _syncWorldDirty(this._children); + } } }, @@ -2400,9 +2490,6 @@ var Node = cc.Class({ }, onRestore: CC_EDITOR && function () { - this._localMatDirty = true; - this._worldMatDirty = true; - this._onRestoreBase(); var actionManager = cc.director.getActionManager(); diff --git a/cocos2d/core/assets/CCRenderTexture.js b/cocos2d/core/assets/CCRenderTexture.js index 0d623bcba4..28e444b955 100644 --- a/cocos2d/core/assets/CCRenderTexture.js +++ b/cocos2d/core/assets/CCRenderTexture.js @@ -56,6 +56,26 @@ let RenderTexture = cc.Class({ this.emit("load"); }, + /** + * !#en Draw a texture to the specified position + * !#zh 将指定的图片渲染到指定的位置上 + * @param {Texture2D} texture + * @param {Number} x + * @param {Number} y + */ + drawTextureAt (texture, x, y) { + if (!texture._image) return; + + this._texture.updateSubImage({ + x, y, + image: texture._image, + width: texture.width, + height: texture.height, + level: 0, + flipY: false + }) + }, + /** * !#en * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array. diff --git a/cocos2d/core/assets/CCSpriteFrame.js b/cocos2d/core/assets/CCSpriteFrame.js index 55d44c41cb..259f329e5b 100644 --- a/cocos2d/core/assets/CCSpriteFrame.js +++ b/cocos2d/core/assets/CCSpriteFrame.js @@ -158,6 +158,9 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._texture = null; this._textureFilename = ''; + // store original info before packed to dynamic atlas + this._original = null; + if (CC_EDITOR) { // Atlas asset uuid this._atlasUuid = ''; diff --git a/cocos2d/core/assets/CCTexture2D.js b/cocos2d/core/assets/CCTexture2D.js index f4473126df..921772c44a 100644 --- a/cocos2d/core/assets/CCTexture2D.js +++ b/cocos2d/core/assets/CCTexture2D.js @@ -367,9 +367,6 @@ var Texture2D = cc.Class({ this._image = options.images[0]; } else if (options.image !== undefined) { - // Release previous gl texture if existed - this._texture.destroy(); - this._image = options.image; if (!options.images) { _images.length = 0; diff --git a/cocos2d/core/camera/CCCamera.js b/cocos2d/core/camera/CCCamera.js index e1498b9f2a..d9eb84ff3e 100644 --- a/cocos2d/core/camera/CCCamera.js +++ b/cocos2d/core/camera/CCCamera.js @@ -291,9 +291,8 @@ let Camera = cc.Class({ }, onEnable () { - this.node.on('world-matrix-changed', this._onMatrixDirty, this); this._matrixDirty = true; - + cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); if (game.renderType === game.RENDER_TYPE_WEBGL) { renderer.scene.addCamera(this._camera); } @@ -301,8 +300,7 @@ let Camera = cc.Class({ }, onDisable () { - this.node.off('world-matrix-changed', this._onMatrixDirty, this); - + cc.director.off(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); if (game.renderType === game.RENDER_TYPE_WEBGL) { renderer.scene.removeCamera(this._camera); } @@ -432,17 +430,19 @@ let Camera = cc.Class({ root = root || cc.director.getScene(); if (!root) return null; - this.lateUpdate(); + // force update node world matrix + this.node.getWorldMatrix(_mat4_temp_1); + this.beforeDraw(); renderer._walker.visit(root); renderer._forward.renderCamera(this._camera, renderer.scene); }, - lateUpdate: !CC_EDITOR && function () { + beforeDraw: !CC_EDITOR && function () { let node = this.node; - node.getWorldMatrix(_mat4_temp_1); - - if (!this._matrixDirty) return; + if (!this._matrixDirty && !node._worldMatDirty) + return; + let camera = this._camera; let fov = Math.atan(Math.tan(this._fov/2) / this.zoomRatio)*2; camera.setFov(fov); @@ -454,8 +454,9 @@ let Camera = cc.Class({ height = targetTexture.height; } - _vec3_temp_1.x = _mat4_temp_1.m12; - _vec3_temp_1.y = _mat4_temp_1.m13; + node._updateWorldMatrix(); + _vec3_temp_1.x = node._worldMatrix.m12; + _vec3_temp_1.y = node._worldMatrix.m13; _vec3_temp_1.z = 0; node.z = height / 1.1566; diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 7eab4f46c9..0e05779867 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -504,7 +504,6 @@ var Label = cc.Class({ if (!this._renderData) { this._renderData = this._assembler.createData(this); - this._renderData.worldMatDirty = true; } }, diff --git a/cocos2d/core/components/CCRenderComponent.js b/cocos2d/core/components/CCRenderComponent.js index 5ed1bd5cd3..699776fc45 100644 --- a/cocos2d/core/components/CCRenderComponent.js +++ b/cocos2d/core/components/CCRenderComponent.js @@ -51,6 +51,12 @@ var RenderComponent = cc.Class({ this.__allocedDatas = []; this._vertexFormat = defaultVertexFormat; this._toPostHandle = false; + // Render component chain entries + this._chain = { + comp: this, + next: null + }; + this._postChain = null; }, onEnable () { diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 0b97ae1be5..38d76565e9 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -464,9 +464,9 @@ var Sprite = cc.Class({ * @param state {Sprite.State} NORMAL or GRAY State. */ setState: function (state) { + if (this._state === state) return; this._state = state; this._material = null; - this._activateMaterial(); }, /** @@ -483,11 +483,8 @@ var Sprite = cc.Class({ this._updateAssembler(); - this._activateMaterial(); - this.node.on('size-changed', this._onNodeSizeDirty, this); this.node.on('anchor-changed', this._onNodeSizeDirty, this); - this.node.on('world-matrix-changed', this._onNodeMatrixDirty, this); }, onDisable: function () { @@ -495,7 +492,6 @@ var Sprite = cc.Class({ this.node.off('size-changed', this._onNodeSizeDirty, this); this.node.off('anchor-changed', this._onNodeSizeDirty, this); - this.node.off('world-matrix-changed', this._onNodeMatrixDirty, this); }, _onNodeSizeDirty () { @@ -504,12 +500,6 @@ var Sprite = cc.Class({ } }, - _onNodeMatrixDirty () { - if (this._renderData) { - this._renderData.worldMatDirty = true; - } - }, - _updateAssembler: function () { let assembler = Sprite._assembler.getAssembler(this); @@ -520,46 +510,50 @@ var Sprite = cc.Class({ if (!this._renderData) { this._renderData = this._assembler.createData(this); - this._renderData.worldMatDirty = true; this._renderData.material = this._material; } }, _activateMaterial: function () { + if (this._material) return; + + let spriteFrame = this._spriteFrame; // cannot be activated if texture not loaded yet - if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { + if (!spriteFrame || !spriteFrame.textureLoaded()) { return; } // Get material - if (!this._material) { - let texture = this._spriteFrame.getTexture(); - let url = texture.url; - let key = url; - if (this._state === State.GRAY) { - key = url + ':gray'; - } - if (this._state === State.GRAY) { - this._material = new GraySpriteMaterial(); - } - else { - this._material = new SpriteMaterial(); - } - // TODO: old texture in material have been released by loader - this._material.texture = texture; + let texture = spriteFrame.getTexture(); + let url = texture.url; + let key = url; + if (this._state === State.GRAY) { + key = url + ':gray'; } + let material; + if (this._state === State.GRAY) { + material = new GraySpriteMaterial(); + } + else { + material = new SpriteMaterial(); + } + // TODO: old texture in material have been released by loader + material.texture = texture; + if (this.srcBlendFactor !== gfx.BLEND_SRC_ALPHA || this.dstBlendFactor !== gfx.BLEND_ONE_MINUS_SRC_ALPHA) { // Update hash inside this._updateBlendFunc(); } else { - this._material.updateHash(); + material.updateHash(); } if (this._renderData) { - this._renderData.material = this._material; + this._renderData.material = material; } + + this._material = material; }, _updateBlendFunc: function () { @@ -641,10 +635,7 @@ var Sprite = cc.Class({ if (!this.isValid) { return; } - // Reactivate material - if (this.enabledInHierarchy) { - this._activateMaterial(); - } + this._applySpriteSize(); }, diff --git a/cocos2d/core/node-activator.js b/cocos2d/core/node-activator.js index 9f6cc82c48..b91a806fe8 100644 --- a/cocos2d/core/node-activator.js +++ b/cocos2d/core/node-activator.js @@ -250,7 +250,7 @@ var NodeActivator = cc.Class({ if (cc.engine._isPlaying || comp.constructor._executeInEditMode) { if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; - if (typeof comp.__preload === 'function') { + if (comp.__preload) { if (preloadInvoker) { preloadInvoker.add(comp); } @@ -285,7 +285,7 @@ var NodeActivator = cc.Class({ } : function (comp, preloadInvoker, onLoadInvoker, onEnableInvoker) { if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; - if (typeof comp.__preload === 'function') { + if (comp.__preload) { if (preloadInvoker) { preloadInvoker.add(comp); } @@ -337,7 +337,7 @@ var NodeActivator = cc.Class({ }, resetComp: CC_EDITOR && function (comp) { - if (typeof comp.resetInEditor === 'function') { + if (comp.resetInEditor) { callResetInTryCatch(comp); } } diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index 3c415bf637..6e566ca9f5 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -232,7 +232,7 @@ var inputManager = { var docElem = document.documentElement; var leftOffset = window.pageXOffset - docElem.clientLeft; var topOffset = window.pageYOffset - docElem.clientTop; - if (typeof element.getBoundingClientRect === 'function') { + if (element.getBoundingClientRect) { var box = element.getBoundingClientRect(); return { left: box.left + leftOffset, diff --git a/cocos2d/core/platform/CCScreen.js b/cocos2d/core/platform/CCScreen.js index 0a440f4d88..c6121bc5a9 100644 --- a/cocos2d/core/platform/CCScreen.js +++ b/cocos2d/core/platform/CCScreen.js @@ -92,7 +92,7 @@ cc.screen = /** @lends cc.screen# */{ } } - this._supportsFullScreen = (typeof this._fn.requestFullscreen !== 'undefined'); + this._supportsFullScreen = (this._fn.requestFullscreen !== undefined); this._touchEvent = ('ontouchstart' in window) ? 'touchstart' : 'mousedown'; }, diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index ecceabc55f..4959be674e 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -296,7 +296,7 @@ var _Deserializer = (function () { // 和 _deserializeObject 不同的地方在于会判断 id 和 uuid prototype._deserializeObjField = function (obj, jsonObj, propName, target, _stillUseUrl) { var id = jsonObj.__id__; - if (typeof id === 'undefined') { + if (id === undefined) { var uuid = jsonObj.__uuid__; if (uuid) { //if (ENABLE_TARGET) { @@ -413,7 +413,7 @@ var _Deserializer = (function () { for (var i = 0; i < fastDefinedProps.length; i++) { var propName = fastDefinedProps[i]; var prop = serialized[propName]; - if (typeof prop !== 'undefined' && serialized.hasOwnProperty(propName)) { + if (prop !== undefined && serialized.hasOwnProperty(propName)) { if (typeof prop !== 'object') { instance[propName] = prop; } @@ -612,7 +612,7 @@ var _Deserializer = (function () { prop = d[propNameToRead]; - if (typeof prop !== 'undefined') { + if (prop !== undefined) { var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; // function undefined object(null) string boolean number var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index 2862913ec7..1eb448b5a6 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -269,7 +269,7 @@ var tmpGetSetDesc = { * @param {Object} obj * @param {String} prop * @param {Function} getter - * @param {Function} setter + * @param {Function} [setter=null] * @param {Boolean} [enumerable=false] */ js.getset = function (obj, prop, getter, setter, enumerable) { @@ -897,7 +897,7 @@ js.array = { * constructor(size: number) */ function Pool (cleanupFunc, size) { - if (typeof cleanupFunc === 'number') { + if (size === undefined) { size = cleanupFunc; cleanupFunc = null; } diff --git a/cocos2d/core/renderer/assemblers/graphics/index.js b/cocos2d/core/renderer/assemblers/graphics/index.js index 752cba56e8..88af67d93a 100644 --- a/cocos2d/core/renderer/assemblers/graphics/index.js +++ b/cocos2d/core/renderer/assemblers/graphics/index.js @@ -49,7 +49,6 @@ const sin = Math.sin; const atan2 = Math.atan2; const abs = Math.abs; -let _matrix = math.mat4.create(); let _renderData = null; let _impl = null; let _curColor = 0; @@ -95,9 +94,9 @@ let graphicsAssembler = js.addon({ z = node._position.z; // vertex buffer - node.getWorldMatrix(_matrix); - let a = _matrix.m00, b = _matrix.m01, c = _matrix.m04, d = _matrix.m05, - tx = _matrix.m12, ty = _matrix.m13; + let matrix = node._worldMatrix; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; let nodeColor = node.color, nodeR = nodeColor.r / 255, diff --git a/cocos2d/core/renderer/assemblers/label/bmfont.js b/cocos2d/core/renderer/assemblers/label/bmfont.js index 862023629e..b223b07810 100644 --- a/cocos2d/core/renderer/assemblers/label/bmfont.js +++ b/cocos2d/core/renderer/assemblers/label/bmfont.js @@ -28,20 +28,26 @@ const renderEngine = require('../../render-engine'); const js = require('../../../platform/js'); const bmfontUtls = require('../../utils/label/bmfont'); +const assembler = require('../assembler'); +const ttfAssembler = require('./ttf'); module.exports = js.addon({ createData (comp) { return comp.requestRenderData(); }, - fillVertexBuffer (comp, off, vbuf, uintbuf) { + updateRenderData: ttfAssembler.updateRenderData, + + fillBuffers (comp, batchData, vertexId, vbuf, uintbuf, ibuf) { + let vertexOffset = batchData.byteOffset / 4, + indiceOffset = batchData.indiceOffset; + let node = comp.node; let renderData = comp._renderData; let data = renderData._data; let z = node._position.z; let color = node.color._val; - node._updateWorldMatrix(); let matrix = node._worldMatrix; let a = matrix.m00, b = matrix.m01, @@ -54,26 +60,22 @@ module.exports = js.addon({ let length = renderData.dataLength; for (let i = 0; i < length; i++) { vert = data[i]; - vbuf[off + 0] = vert.x * a + vert.y * c + tx; - vbuf[off + 1] = vert.x * b + vert.y * d + ty; - vbuf[off + 2] = z; - vbuf[off + 4] = vert.u; - vbuf[off + 5] = vert.v; - uintbuf[off + 3] = color; - off += 6; + vbuf[vertexOffset + 0] = vert.x * a + vert.y * c + tx; + vbuf[vertexOffset + 1] = vert.x * b + vert.y * d + ty; + vbuf[vertexOffset + 2] = z; + vbuf[vertexOffset + 4] = vert.u; + vbuf[vertexOffset + 5] = vert.v; + uintbuf[vertexOffset + 3] = color; + vertexOffset += 6; } - }, - - fillIndexBuffer (comp, offset, vertexId, ibuf) { - let renderData = comp._renderData; - let length = renderData.indiceCount; + length = renderData.indiceCount; for (let i = 0; i < length; i+=6) { - ibuf[offset++] = vertexId; - ibuf[offset++] = vertexId+1; - ibuf[offset++] = vertexId+2; - ibuf[offset++] = vertexId+1; - ibuf[offset++] = vertexId+3; - ibuf[offset++] = vertexId+2; + ibuf[indiceOffset++] = vertexId; + ibuf[indiceOffset++] = vertexId+1; + ibuf[indiceOffset++] = vertexId+2; + ibuf[indiceOffset++] = vertexId+1; + ibuf[indiceOffset++] = vertexId+3; + ibuf[indiceOffset++] = vertexId+2; vertexId += 4; } }, @@ -132,4 +134,4 @@ module.exports = js.addon({ data[dataOffset+3].x = x + rectWidth * scale; data[dataOffset+3].y = y; }, -}, bmfontUtls); +}, bmfontUtls, assembler); diff --git a/cocos2d/core/renderer/assemblers/label/index.js b/cocos2d/core/renderer/assemblers/label/index.js index 00639c4e26..00e5720047 100644 --- a/cocos2d/core/renderer/assemblers/label/index.js +++ b/cocos2d/core/renderer/assemblers/label/index.js @@ -23,14 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -const js = require('../../../platform/js'); -const assembler = require('../assembler'); const Label = require('../../../components/CCLabel'); const ttfAssembler = require('./ttf'); const bmfontAssembler = require('./bmfont'); -var labelAssembler = js.addon({ - +var labelAssembler = { getAssembler (comp) { let assembler = ttfAssembler; @@ -41,40 +38,11 @@ var labelAssembler = js.addon({ return assembler; }, - updateRenderData (comp) { - this.datas.length = 0; - - if (comp.string === undefined || - comp.string === null || - comp.string === "" || - !comp._assembler) { - return this.datas; - } - - let renderData = comp._renderData; - - // let size = comp.node._contentSize; - // let anchor = comp.node._anchorPoint; - // renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y); - - comp._assembler.update(comp); - - renderData.material = comp.getMaterial(); - this.datas.push(renderData); - return this.datas; - }, - - fillBuffers (comp, batchData, vertexId, vbuf, uintbuf, ibuf) { - let assembler = comp._assembler; - if (!assembler) return; - - let vertexOffset = batchData.byteOffset / 4, - indiceOffset = batchData.indiceOffset; - - assembler.fillVertexBuffer(comp, vertexOffset, vbuf, uintbuf); - assembler.fillIndexBuffer(comp, indiceOffset, vertexId, ibuf); + // Skip invalid labels (without own _assembler) + updateRenderData (label) { + return label.__allocedDatas; } -}, assembler); +}; Label._assembler = labelAssembler; diff --git a/cocos2d/core/renderer/assemblers/label/ttf.js b/cocos2d/core/renderer/assemblers/label/ttf.js index c458aebdc6..e682294565 100644 --- a/cocos2d/core/renderer/assemblers/label/ttf.js +++ b/cocos2d/core/renderer/assemblers/label/ttf.js @@ -28,6 +28,7 @@ const renderEngine = require('../../render-engine'); const js = require('../../../platform/js'); const ttfUtls = require('../../utils/label/ttf'); +const assembler = require('../assembler'); module.exports = js.addon({ createData (comp) { @@ -49,14 +50,32 @@ module.exports = js.addon({ return renderData; }, - fillVertexBuffer (comp, off, vbuf, uintbuf) { + updateRenderData (comp) { + let datas = this.datas; + datas.length = 0; + + if (!comp.string) { + return datas; + } + + let renderData = comp._renderData; + this.update(comp); + + renderData.material = comp.getMaterial(); + datas.push(renderData); + return datas; + }, + + fillBuffers (comp, batchData, vertexId, vbuf, uintbuf, ibuf) { + let vertexOffset = batchData.byteOffset / 4, + indiceOffset = batchData.indiceOffset; + let node = comp.node; let renderData = comp._renderData; let data = renderData._data; let z = node._position.z; let color = cc.Color.WHITE._val; - node._updateWorldMatrix(); let matrix = node._worldMatrix; let a = matrix.m00, b = matrix.m01, @@ -69,23 +88,21 @@ module.exports = js.addon({ let length = renderData.dataLength; for (let i = 0; i < length; i++) { vert = data[i]; - vbuf[off + 0] = vert.x * a + vert.y * c + tx; - vbuf[off + 1] = vert.x * b + vert.y * d + ty; - vbuf[off + 2] = z; - vbuf[off + 4] = vert.u; - vbuf[off + 5] = vert.v; - uintbuf[off + 3] = color; - off += 6; + vbuf[vertexOffset + 0] = vert.x * a + vert.y * c + tx; + vbuf[vertexOffset + 1] = vert.x * b + vert.y * d + ty; + vbuf[vertexOffset + 2] = z; + vbuf[vertexOffset + 4] = vert.u; + vbuf[vertexOffset + 5] = vert.v; + uintbuf[vertexOffset + 3] = color; + vertexOffset += 6; } - }, - - 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; + + ibuf[indiceOffset + 0] = vertexId; + ibuf[indiceOffset + 1] = vertexId + 1; + ibuf[indiceOffset + 2] = vertexId + 2; + ibuf[indiceOffset + 3] = vertexId + 1; + ibuf[indiceOffset + 4] = vertexId + 3; + ibuf[indiceOffset + 5] = vertexId + 2; }, _updateVerts (comp) { @@ -107,4 +124,4 @@ module.exports = js.addon({ data[3].x = width - appx; data[3].y = height - appy; } -}, ttfUtls); +}, ttfUtls, assembler); diff --git a/cocos2d/core/renderer/assemblers/mask-assembler.js b/cocos2d/core/renderer/assemblers/mask-assembler.js index e2584a0544..e12a6ac9e2 100644 --- a/cocos2d/core/renderer/assemblers/mask-assembler.js +++ b/cocos2d/core/renderer/assemblers/mask-assembler.js @@ -94,7 +94,7 @@ let maskFrontAssembler = js.addon({ if (mask.spriteFrame) { datas = mask._renderDatas; datas.length = 0; - renderData.dataLength = 8; + renderData.dataLength = 4; spriteAssembler.update(mask); renderData.material = mask.getMaterial(); datas.push(renderData); diff --git a/cocos2d/core/renderer/assemblers/motion-streak.js b/cocos2d/core/renderer/assemblers/motion-streak.js index 3bbbf903ce..d5f5b9da6d 100644 --- a/cocos2d/core/renderer/assemblers/motion-streak.js +++ b/cocos2d/core/renderer/assemblers/motion-streak.js @@ -104,7 +104,6 @@ var motionStreakAssembler = js.addon({ let stroke = comp._stroke / 2; let node = comp.node; - node._updateWorldMatrix(); let matrix = node._worldMatrix; let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; diff --git a/cocos2d/core/renderer/assemblers/sprite/bar-filled.js b/cocos2d/core/renderer/assemblers/sprite/bar-filled.js index bd3f2ead10..b7d63a3116 100644 --- a/cocos2d/core/renderer/assemblers/sprite/bar-filled.js +++ b/cocos2d/core/renderer/assemblers/sprite/bar-filled.js @@ -26,46 +26,62 @@ const Sprite = require('../../../components/CCSprite'); const FillType = Sprite.FillType; -const simpleRenderUtil = require('./simple'); +const dynamicAtlasManager = require('../../utils/dynamic-atlas/manager'); module.exports = { - update (sprite) { - let renderData = sprite._renderData; - let uvDirty = renderData.uvDirty, - vertDirty = renderData.vertDirty; - - if (!uvDirty && !vertDirty) return; - - let fillStart = sprite._fillStart; - let fillRange = sprite._fillRange; - - if (fillRange < 0) { - fillStart += fillRange; - fillRange = -fillRange; - } - - fillRange = fillStart + fillRange; - - fillStart = fillStart > 1.0 ? 1.0 : fillStart; - fillStart = fillStart < 0.0 ? 0.0 : fillStart; - - fillRange = fillRange > 1.0 ? 1.0 : fillRange; - fillRange = fillRange < 0.0 ? 0.0 : fillRange; - fillRange = fillRange - fillStart; - fillRange = fillRange < 0 ? 0 : fillRange; + useModel: false, + updateRenderData (sprite) { + let frame = sprite.spriteFrame; - let fillEnd = fillStart + fillRange; - fillEnd = fillEnd > 1 ? 1 : fillEnd; + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + if (!sprite._material && frame) { + // Avoid as much function call as possible + if (!frame._original) { + dynamicAtlasManager.insertSpriteFrame(frame); + } + sprite._activateMaterial(); + } - if (uvDirty) { - this.updateUVs(sprite, fillStart, fillEnd); - } - if (vertDirty) { - this.updateVerts(sprite, fillStart, fillEnd); - } - if (vertDirty || renderData.worldMatDirty) { - this.updateWorldVerts(sprite); + let renderData = sprite._renderData; + if (renderData && frame) { + let uvDirty = renderData.uvDirty, + vertDirty = renderData.vertDirty; + + if (!uvDirty && !vertDirty) return; + + let fillStart = sprite._fillStart; + let fillRange = sprite._fillRange; + + if (fillRange < 0) { + fillStart += fillRange; + fillRange = -fillRange; + } + + fillRange = fillStart + fillRange; + + fillStart = fillStart > 1.0 ? 1.0 : fillStart; + fillStart = fillStart < 0.0 ? 0.0 : fillStart; + + fillRange = fillRange > 1.0 ? 1.0 : fillRange; + fillRange = fillRange < 0.0 ? 0.0 : fillRange; + fillRange = fillRange - fillStart; + fillRange = fillRange < 0 ? 0 : fillRange; + + let fillEnd = fillStart + fillRange; + fillEnd = fillEnd > 1 ? 1 : fillEnd; + + if (uvDirty) { + this.updateUVs(sprite, fillStart, fillEnd); + } + if (vertDirty) { + this.updateVerts(sprite, fillStart, fillEnd); + } + if (vertDirty || batchData.worldMatUpdated) { + this.updateWorldVerts(sprite); + } } + return sprite.__allocedDatas; }, updateUVs (sprite, fillStart, fillEnd) { @@ -175,7 +191,56 @@ module.exports = { renderData.vertDirty = false; }, - updateWorldVerts: simpleRenderUtil.updateWorldVerts, - createData: simpleRenderUtil.createData, - fillBuffers: simpleRenderUtil.fillBuffers + createData (sprite) { + let renderData = sprite.requestRenderData(); + // 0-4 for world verts + // 5-8 for local verts + renderData.dataLength = 8; + renderData.vertexCount = 4; + renderData.indiceCount = 6; + return renderData; + }, + + updateWorldVerts (sprite) { + let node = sprite.node, + data = sprite._renderData._data; + + let matrix = node._worldMatrix, + 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++) { + let local = data[i+4]; + let world = data[i]; + world.x = local.x * a + local.y * c + tx; + world.y = local.x * b + local.y * d + ty; + } + }, + + fillBuffers (sprite, batchData, vertexId, vbuf, uintbuf, ibuf) { + let vertexOffset = batchData.byteOffset / 4, + indiceOffset = batchData.indiceOffset; + + let data = sprite._renderData._data; + let node = sprite.node; + let z = node._position.z; + let color = node._color._val; + + for (let i = 0; i < 4; i++) { + let vert = data[i]; + vbuf[vertexOffset ++] = vert.x; + vbuf[vertexOffset ++] = vert.y; + vbuf[vertexOffset ++] = z; + uintbuf[vertexOffset ++] = color; + vbuf[vertexOffset ++] = vert.u; + vbuf[vertexOffset ++] = vert.v; + } + + ibuf[indiceOffset ++] = vertexId; + ibuf[indiceOffset ++] = vertexId + 1; + ibuf[indiceOffset ++] = vertexId + 2; + ibuf[indiceOffset ++] = vertexId + 1; + ibuf[indiceOffset ++] = vertexId + 3; + ibuf[indiceOffset ++] = vertexId + 2; + } }; diff --git a/cocos2d/core/renderer/assemblers/sprite/index.js b/cocos2d/core/renderer/assemblers/sprite/index.js index 97aaafbe87..454c399a3f 100644 --- a/cocos2d/core/renderer/assemblers/sprite/index.js +++ b/cocos2d/core/renderer/assemblers/sprite/index.js @@ -23,10 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -const js = require('../../../platform/js'); -const assembler = require('../assembler'); const Sprite = require('../../../components/CCSprite'); -const renderEngine = require('../../render-engine'); +const dynamicAtlasManager = require('../../utils/dynamic-atlas/manager'); + const SpriteType = Sprite.Type; const FillType = Sprite.FillType; @@ -38,9 +37,8 @@ const barFilledRenderUtil = require('./bar-filled'); const meshRenderUtil = require('./mesh'); // Inline all type switch to avoid jit deoptimization during inlined function change -let spriteAssembler = js.addon({ - useModel: false, +let spriteAssembler = { getAssembler (sprite) { let util = simpleRenderUtil; @@ -67,21 +65,11 @@ let spriteAssembler = js.addon({ return util; }, + // Skip invalid sprites (without own _assembler) updateRenderData (sprite) { - let datas = sprite.__allocedDatas; - if (!sprite.spriteFrame || !sprite.getMaterial() || !sprite._renderData) { - return datas; - } - - sprite._assembler.update(sprite); - - return datas; - }, - - fillBuffers (sprite, batchData, vertexId, vbuf, uintbuf, ibuf) { - sprite._assembler.fillBuffers(sprite, batchData, vertexId, vbuf, uintbuf, ibuf); + return sprite.__allocedDatas; } -}, assembler); +}; Sprite._assembler = spriteAssembler; diff --git a/cocos2d/core/renderer/assemblers/sprite/mesh.js b/cocos2d/core/renderer/assemblers/sprite/mesh.js index 799da554a3..c85f31e0a0 100644 --- a/cocos2d/core/renderer/assemblers/sprite/mesh.js +++ b/cocos2d/core/renderer/assemblers/sprite/mesh.js @@ -23,38 +23,55 @@ THE SOFTWARE. ****************************************************************************/ -module.exports = { +const dynamicAtlasManager = require('../../utils/dynamic-atlas/manager'); + + module.exports = { + useModel: false, + createData (sprite) { return sprite.requestRenderData(); }, - update (sprite) { - let renderData = sprite._renderData; + updateRenderData (sprite) { let frame = sprite.spriteFrame; - - let vertices = frame.vertices; - if (!vertices) return; - - if (renderData.vertexCount !== vertices.x.length) { - renderData.vertexCount = vertices.x.length; - renderData.indiceCount = vertices.triangles.length; - - // 1 for world vertices, 2 for local vertices - renderData.dataLength = renderData.vertexCount * 2; - - renderData.uvDirty = renderData.vertDirty = true; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + if (!sprite._material && frame) { + // Avoid as much function call as possible + if (!frame._original) { + dynamicAtlasManager.insertSpriteFrame(frame); + } + sprite._activateMaterial(); } - if (renderData.uvDirty) { - this.updateUVs(sprite); - } - let vertDirty = renderData.vertDirty; - if (vertDirty) { - this.updateVerts(sprite); - } - if (vertDirty || renderData.worldMatDirty) { - this.updateWorldVerts(sprite); + let renderData = sprite._renderData; + if (renderData && frame) { + let vertices = frame.vertices; + if (vertices) { + if (renderData.vertexCount !== vertices.x.length) { + renderData.vertexCount = vertices.x.length; + renderData.indiceCount = vertices.triangles.length; + + // 1 for world vertices, 2 for local vertices + renderData.dataLength = renderData.vertexCount * 2; + + renderData.uvDirty = renderData.vertDirty = true; + } + + if (renderData.uvDirty) { + this.updateUVs(sprite); + } + let vertDirty = renderData.vertDirty; + if (vertDirty) { + this.updateVerts(sprite); + } + if (vertDirty || batchData.worldMatUpdated) { + this.updateWorldVerts(sprite); + } + } } + return sprite.__allocedDatas; }, updateUVs (sprite) { @@ -125,8 +142,8 @@ module.exports = { updateWorldVerts (sprite) { let node = sprite.node, renderData = sprite._renderData, - data = renderData._data, - matrix = node._worldMatrix; + data = renderData._data; + let matrix = node._worldMatrix; let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; @@ -136,8 +153,6 @@ module.exports = { world.x = local.x * a + local.y * c + tx; world.y = local.x * b + local.y * d + ty; } - - renderData.worldMatDirty = false; }, fillBuffers (sprite, batchData, vertexId, vbuf, uintbuf, ibuf) { @@ -166,5 +181,5 @@ module.exports = { for (let i = 0, l = triangles.length; i < l; i++) { ibuf[indiceOffset++] = vertexId + triangles[i]; } - } + }, }; \ No newline at end of file diff --git a/cocos2d/core/renderer/assemblers/sprite/radial-filled.js b/cocos2d/core/renderer/assemblers/sprite/radial-filled.js index d0dcfb74bd..3c112f2ebf 100644 --- a/cocos2d/core/renderer/assemblers/sprite/radial-filled.js +++ b/cocos2d/core/renderer/assemblers/sprite/radial-filled.js @@ -23,11 +23,13 @@ THE SOFTWARE. ****************************************************************************/ -const simpleRenderUtil = require('./simple'); +const dynamicAtlasManager = require('../../utils/dynamic-atlas/manager'); const PI_2 = Math.PI * 2; module.exports = { + useModel: false, + _vertPos: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)], _vertices: [0, 0, 0, 0], _uvs: [0, 0, 0, 0, 0, 0, 0, 0], @@ -40,100 +42,114 @@ module.exports = { return sprite.requestRenderData(); }, - update (sprite) { - let renderData = sprite._renderData; - if (!renderData.vertDirty && !renderData.uvDirty) return; - - let data = renderData._data; - let spriteFrame = sprite._spriteFrame; - - let fillStart = sprite._fillStart; - let fillRange = sprite._fillRange; - if (fillRange < 0) { - fillStart += fillRange; - fillRange = -fillRange; + updateRenderData (sprite) { + let frame = sprite.spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + if (!sprite._material && frame) { + // Avoid as much function call as possible + if (!frame._original) { + dynamicAtlasManager.insertSpriteFrame(frame); + } + sprite._activateMaterial(); } - //do round fill start [0,1), include 0, exclude 1 - while (fillStart >= 1.0) fillStart -= 1.0; - while (fillStart < 0.0) fillStart += 1.0; + let renderData = sprite._renderData; + if (renderData && frame) { + if (renderData.vertDirty || renderData.uvDirty) { + let data = renderData._data; - fillStart *= PI_2; - fillRange *= PI_2; - let fillEnd = fillStart + fillRange; + let fillStart = sprite._fillStart; + let fillRange = sprite._fillRange; + if (fillRange < 0) { + fillStart += fillRange; + fillRange = -fillRange; + } - //build vertices - this._calculateVertices(sprite); - //build uvs - this._calculateUVs(spriteFrame); + //do round fill start [0,1), include 0, exclude 1 + while (fillStart >= 1.0) fillStart -= 1.0; + while (fillStart < 0.0) fillStart += 1.0; - let center = this._center; + fillStart *= PI_2; + fillRange *= PI_2; + let fillEnd = fillStart + fillRange; - let vertPos = this._vertPos, - vertices = this._vertices; + //build vertices + this._calculateVertices(sprite); + //build uvs + this._calculateUVs(frame); - let triangles = this._triangles; + let center = this._center; - this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart, this._intersectPoint_1); - this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart + fillRange, this._intersectPoint_2); + let vertPos = this._vertPos, + vertices = this._vertices; - let offset = 0; - for (let triangleIndex = 0; triangleIndex < 4; ++triangleIndex) { - let triangle = triangles[triangleIndex]; - if (!triangle) { - continue; - } - //all in - if (fillRange >= PI_2) { - renderData.dataLength = offset + 3; - this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); - offset += 3; - continue; - } - //test against - let startAngle = this._getVertAngle(center, vertPos[triangle[0]]); - let endAngle = this._getVertAngle(center, vertPos[triangle[1]]); - if(endAngle < startAngle) endAngle += PI_2; - startAngle -= PI_2; - endAngle -= PI_2; - //testing - for(let testIndex = 0; testIndex < 3; ++testIndex) { - if(startAngle >= fillEnd) { - //all out - } else if (startAngle >= fillStart) { - renderData.dataLength = offset + 3; - if(endAngle >= fillEnd) { - //startAngle to fillEnd - this._generateTriangle(data, offset, center, vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]); - } else { - //startAngle to endAngle - this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); + let triangles = this._triangles; + + this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart, this._intersectPoint_1); + this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart + fillRange, this._intersectPoint_2); + + let offset = 0; + for (let triangleIndex = 0; triangleIndex < 4; ++triangleIndex) { + let triangle = triangles[triangleIndex]; + if (!triangle) { + continue; } - offset += 3; - } else { - //startAngle < fillStart - if(endAngle <= fillStart) { - //all out - } else if(endAngle <= fillEnd) { + //all in + if (fillRange >= PI_2) { renderData.dataLength = offset + 3; - //fillStart to endAngle - this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], vertPos[triangle[1]]); - offset += 3; - } else { - renderData.dataLength = offset + 3; - //fillStart to fillEnd - this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]); + this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); offset += 3; + continue; + } + //test against + let startAngle = this._getVertAngle(center, vertPos[triangle[0]]); + let endAngle = this._getVertAngle(center, vertPos[triangle[1]]); + if(endAngle < startAngle) endAngle += PI_2; + startAngle -= PI_2; + endAngle -= PI_2; + //testing + for(let testIndex = 0; testIndex < 3; ++testIndex) { + if(startAngle >= fillEnd) { + //all out + } else if (startAngle >= fillStart) { + renderData.dataLength = offset + 3; + if(endAngle >= fillEnd) { + //startAngle to fillEnd + this._generateTriangle(data, offset, center, vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]); + } else { + //startAngle to endAngle + this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]); + } + offset += 3; + } else { + //startAngle < fillStart + if(endAngle <= fillStart) { + //all out + } else if(endAngle <= fillEnd) { + renderData.dataLength = offset + 3; + //fillStart to endAngle + this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], vertPos[triangle[1]]); + offset += 3; + } else { + renderData.dataLength = offset + 3; + //fillStart to fillEnd + this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]); + offset += 3; + } + } + //add 2 * PI + startAngle += PI_2; + endAngle += PI_2; } } - //add 2 * PI - startAngle += PI_2; - endAngle += PI_2; + + renderData.indiceCount = renderData.vertexCount = offset; + renderData.vertDirty = renderData.uvDirty = false; } } - - renderData.indiceCount = renderData.vertexCount = offset; - renderData.vertDirty = renderData.uvDirty = false; + return sprite.__allocedDatas; }, _getVertAngle: function(start, end) { @@ -339,5 +355,5 @@ module.exports = { for (let i = 0; i < count; i++) { ibuf[indiceOffset+i] = vertexId+i; } - } + }, }; diff --git a/cocos2d/core/renderer/assemblers/sprite/simple.js b/cocos2d/core/renderer/assemblers/sprite/simple.js index 71f2da53cd..ee126f1cea 100644 --- a/cocos2d/core/renderer/assemblers/sprite/simple.js +++ b/cocos2d/core/renderer/assemblers/sprite/simple.js @@ -24,25 +24,35 @@ ****************************************************************************/ const js = require('../../../platform/js'); -const assembler = require('../assembler'); +const dynamicAtlasManager = require('../../utils/dynamic-atlas/manager'); -module.exports = js.addon({ +module.exports = { useModel: false, - - update (sprite) { - let renderData = sprite._renderData; + + updateRenderData (sprite) { + let frame = sprite._spriteFrame; - if (renderData.uvDirty) { - this.updateUVs(sprite); + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + if (!sprite._material && frame) { + // Avoid as much function call as possible + if (!frame._original) { + dynamicAtlasManager.insertSpriteFrame(frame); + } + sprite._activateMaterial(); } - let vertDirty = renderData.vertDirty; - if (vertDirty) { - this.updateVerts(sprite); - } - if (vertDirty || renderData.worldMatDirty) { - this.updateWorldVerts(sprite); + let renderData = sprite._renderData; + if (renderData && frame) { + if (renderData.uvDirty) { + this.updateUVs(sprite); + } + + if (renderData.vertDirty) { + this.updateVerts(sprite); + } } + return sprite.__allocedDatas; }, fillBuffers (sprite, batchData, vertexId, vbuf, uintbuf, ibuf) { @@ -53,11 +63,14 @@ module.exports = js.addon({ let node = sprite.node; let z = node._position.z; let color = node._color._val; + let matrix = node._worldMatrix; + 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++) { let vert = data[i]; - vbuf[vertexOffset ++] = vert.x; - vbuf[vertexOffset ++] = vert.y; + vbuf[vertexOffset ++] = vert.x * a + vert.y * c + tx; + vbuf[vertexOffset ++] = vert.x * b + vert.y * d + ty; vbuf[vertexOffset ++] = z; uintbuf[vertexOffset ++] = color; vbuf[vertexOffset ++] = vert.u; @@ -74,9 +87,7 @@ module.exports = js.addon({ createData (sprite) { let renderData = sprite.requestRenderData(); - // 0-4 for world verts - // 5-8 for local verts - renderData.dataLength = 8; + renderData.dataLength = 4; renderData.vertexCount = 4; renderData.indiceCount = 6; return renderData; @@ -124,24 +135,6 @@ module.exports = js.addon({ renderData.uvDirty = false; }, - updateWorldVerts (sprite) { - let node = sprite.node, - renderData = sprite._renderData, - data = renderData._data, - matrix = node._worldMatrix; - 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++) { - let local = data[i+4]; - let world = data[i]; - world.x = local.x * a + local.y * c + tx; - world.y = local.x * b + local.y * d + ty; - } - - renderData.worldMatDirty = false; - }, - updateVerts (sprite) { let renderData = sprite._renderData, node = sprite.node, @@ -171,15 +164,15 @@ module.exports = js.addon({ t = ch + trimTop * scaleY - appy; } - data[4].x = l; - data[4].y = b; - data[5].x = r; - data[5].y = b; - data[6].x = l; - data[6].y = t; - data[7].x = r; - data[7].y = t; + data[0].x = l; + data[0].y = b; + data[1].x = r; + data[1].y = b; + data[2].x = l; + data[2].y = t; + data[3].x = r; + data[3].y = t; renderData.vertDirty = false; } -}, assembler); +}; diff --git a/cocos2d/core/renderer/assemblers/sprite/sliced.js b/cocos2d/core/renderer/assemblers/sprite/sliced.js index 68d21b7478..6b804fbcf7 100644 --- a/cocos2d/core/renderer/assemblers/sprite/sliced.js +++ b/cocos2d/core/renderer/assemblers/sprite/sliced.js @@ -24,11 +24,12 @@ ****************************************************************************/ const Sprite = require('../../../components/CCSprite'); +const dynamicAtlasManager = require('../../utils/dynamic-atlas/manager'); const FillType = Sprite.FillType; -const simpleRenderUtil = require('./simple'); - module.exports = { + useModel: false, + createData (sprite) { let renderData = sprite.requestRenderData(); // 0-4 for local verts @@ -39,6 +40,36 @@ module.exports = { renderData.indiceCount = 54; return renderData; }, + + updateRenderData (sprite, batchData) { + let frame = sprite.spriteFrame; + + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + if (!sprite._material && frame) { + // Avoid as much function call as possible + if (!frame._original) { + dynamicAtlasManager.insertSpriteFrame(frame); + } + sprite._activateMaterial(); + } + + let renderData = sprite._renderData; + if (renderData && frame) { + if (renderData.uvDirty) { + this.updateUVs(sprite); + } + + let vertDirty = renderData.vertDirty; + if (vertDirty) { + this.updateVerts(sprite); + } + if (vertDirty || batchData.worldMatUpdated) { + this.updateWorldVerts(sprite); + } + } + return sprite.__allocedDatas; + }, updateUVs (sprite) { let material = sprite.getMaterial(); @@ -79,6 +110,17 @@ module.exports = { data[1].v = (topHeight + centerHeight + rect.y) / atlasHeight; data[0].v = (rect.y + rect.height) / atlasHeight; } + + for (let row = 0; row < 4; ++row) { + let rowD = data[row]; + for (let col = 0; col < 4; ++col) { + let colD = data[col]; + let world = data[4 + row*4 + col]; + world.u = colD.u; + world.v = rowD.v; + } + } + renderData.uvDirty = false; }, @@ -137,7 +179,7 @@ module.exports = { uintbuf[vertexOffset + 3] = color; vertexOffset += 6; } - + for (let r = 0; r < 3; ++r) { for (let c = 0; c < 3; ++c) { let start = vertexId + r*4 + c; @@ -153,10 +195,10 @@ module.exports = { updateWorldVerts (sprite) { let node = sprite.node, - renderData = sprite._renderData, - data = renderData._data, - matrix = node._worldMatrix; - let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + data = sprite._renderData._data; + + let matrix = node._worldMatrix, + a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, tx = matrix.m12, ty = matrix.m13; for (let row = 0; row < 4; ++row) { @@ -166,13 +208,7 @@ module.exports = { let world = data[4 + row*4 + col]; world.x = colD.x*a + rowD.y*c + tx; world.y = colD.x*b + rowD.y*d + ty; - world.u = colD.u; - world.v = rowD.v; } } - - renderData.worldMatDirty = false; }, - - update: simpleRenderUtil.update }; diff --git a/cocos2d/core/renderer/assemblers/sprite/tiled.js b/cocos2d/core/renderer/assemblers/sprite/tiled.js index a6ef006f17..0b7fd5c1e1 100644 --- a/cocos2d/core/renderer/assemblers/sprite/tiled.js +++ b/cocos2d/core/renderer/assemblers/sprite/tiled.js @@ -23,101 +23,117 @@ THE SOFTWARE. ****************************************************************************/ +const dynamicAtlasManager = require('../../utils/dynamic-atlas/manager'); + module.exports = { + useModel: false, + createData (sprite) { return sprite.requestRenderData(); }, - update (sprite) { - let renderData = sprite._renderData; - if (!renderData.uvDirty && !renderData.vertDirty) return; - - let material = sprite.getMaterial(); - - let texture = material.effect.getProperty('texture'); - let texw = texture._width, - texh = texture._height; + updateRenderData (sprite) { let frame = sprite.spriteFrame; - let rect = frame._rect; - - let node = sprite.node, - contentWidth = Math.abs(node.width), - contentHeight = Math.abs(node.height), - appx = node.anchorX * contentWidth, - appy = node.anchorY * contentHeight; - - let rectWidth = rect.width; - let rectHeight = rect.height; - let hRepeat = contentWidth / rectWidth; - let vRepeat = contentHeight / rectHeight; - let row = Math.ceil(vRepeat), - col = Math.ceil(hRepeat); - - let data = renderData._data; - renderData.dataLength = Math.max(8, row+1, col+1); - - let l, b, r, t; - if (!frame._rotated) { - l = (rect.x) / texw; - r = (rect.x + rectWidth) / texw; - b = (rect.y + rectHeight) / texh; - t = (rect.y) / texh; - - data[0].u = l; - data[0].v = b; - data[1].u = r; - data[1].v = b; - data[2].u = l; - data[2].v = t; - data[3].u = r; - data[3].v = t; - - data[4].u = l; - data[4].v = b; - data[5].u = l + (r-l) * Math.min(1, hRepeat - col + 1); - data[5].v = b; - data[6].u = l; - data[6].v = b + (t-b) * Math.min(1, vRepeat - row + 1); - data[7].u = data[5].u; - data[7].v = data[6].v; - } else { - l = (rect.x) / texw; - r = (rect.x + rectHeight) / texw; - b = (rect.y + rectWidth) / texh; - t = (rect.y) / texh; - - data[0].u = l; - data[0].v = t; - data[1].u = l; - data[1].v = b; - data[2].u = r; - data[2].v = t; - data[3].u = r; - data[3].v = b; - - data[4].u = l; - data[4].v = t; - data[5].u = l; - data[5].v = t + (b - t) * Math.min(1, vRepeat - col + 1); - data[6].u = l + (r - l) * Math.min(1, hRepeat - row + 1); - data[6].v = t; - data[7].u = data[5].u; - data[7].v = data[6].v; - } - - for (let i = 0; i <= col; ++i) { - data[i].x = Math.min(rectWidth * i, contentWidth) - appx; - } - - for (let i = 0; i <= row; ++i) { - data[i].y = Math.min(rectHeight * i, contentHeight) - appy; - } - // update data property - renderData.vertexCount = row * col * 4; - renderData.indiceCount = row * col * 6; - renderData.uvDirty = false; - renderData.vertDirty = false; + // TODO: Material API design and export from editor could affect the material activation process + // need to update the logic here + if (!sprite._material && frame) { + // Avoid as much function call as possible + if (!frame._original) { + dynamicAtlasManager.insertSpriteFrame(frame); + } + sprite._activateMaterial(); + } + + let renderData = sprite._renderData; + if (renderData && frame) { + if (renderData.uvDirty || renderData.vertDirty) { + let texture = frame._texture; + let texw = texture._width, + texh = texture._height; + let rect = frame._rect; + + let node = sprite.node, + contentWidth = Math.abs(node.width), + contentHeight = Math.abs(node.height), + appx = node.anchorX * contentWidth, + appy = node.anchorY * contentHeight; + + let rectWidth = rect.width; + let rectHeight = rect.height; + let hRepeat = contentWidth / rectWidth; + let vRepeat = contentHeight / rectHeight; + let row = Math.ceil(vRepeat), + col = Math.ceil(hRepeat); + + let data = renderData._data; + renderData.dataLength = Math.max(8, row+1, col+1); + + let l, b, r, t; + if (!frame._rotated) { + l = (rect.x) / texw; + r = (rect.x + rectWidth) / texw; + b = (rect.y + rectHeight) / texh; + t = (rect.y) / texh; + + data[0].u = l; + data[0].v = b; + data[1].u = r; + data[1].v = b; + data[2].u = l; + data[2].v = t; + data[3].u = r; + data[3].v = t; + + data[4].u = l; + data[4].v = b; + data[5].u = l + (r-l) * Math.min(1, hRepeat - col + 1); + data[5].v = b; + data[6].u = l; + data[6].v = b + (t-b) * Math.min(1, vRepeat - row + 1); + data[7].u = data[5].u; + data[7].v = data[6].v; + } else { + l = (rect.x) / texw; + r = (rect.x + rectHeight) / texw; + b = (rect.y + rectWidth) / texh; + t = (rect.y) / texh; + + data[0].u = l; + data[0].v = t; + data[1].u = l; + data[1].v = b; + data[2].u = r; + data[2].v = t; + data[3].u = r; + data[3].v = b; + + data[4].u = l; + data[4].v = t; + data[5].u = l; + data[5].v = t + (b - t) * Math.min(1, vRepeat - col + 1); + data[6].u = l + (r - l) * Math.min(1, hRepeat - row + 1); + data[6].v = t; + data[7].u = data[5].u; + data[7].v = data[6].v; + } + + for (let i = 0; i <= col; ++i) { + data[i].x = Math.min(rectWidth * i, contentWidth) - appx; + } + + for (let i = 0; i <= row; ++i) { + data[i].y = Math.min(rectHeight * i, contentHeight) - appy; + } + + // update data property + renderData.vertexCount = row * col * 4; + renderData.indiceCount = row * col * 6; + renderData.uvDirty = false; + renderData.vertDirty = false; + } + } + return sprite.__allocedDatas; }, fillBuffers (sprite, batchData, vertexId, vbuf, uintbuf, ibuf) { @@ -139,14 +155,9 @@ module.exports = { let row = Math.ceil(vRepeat), col = Math.ceil(hRepeat); - node._updateWorldMatrix(); let matrix = node._worldMatrix; - let a = matrix.m00, - b = matrix.m01, - c = matrix.m04, - d = matrix.m05, - tx = matrix.m12, - ty = matrix.m13; + let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05, + tx = matrix.m12, ty = matrix.m13; let x, x1, y, y1, lastx, lasty; for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) { @@ -203,5 +214,5 @@ module.exports = { ibuf[indiceOffset++] = vertexId+2; vertexId += 4; } - } + }, }; \ No newline at end of file diff --git a/cocos2d/core/renderer/canvas/canvas-render-walker.js b/cocos2d/core/renderer/canvas/canvas-render-walker.js index 135e949da0..21e02144cd 100644 --- a/cocos2d/core/renderer/canvas/canvas-render-walker.js +++ b/cocos2d/core/renderer/canvas/canvas-render-walker.js @@ -42,10 +42,6 @@ RenderComponentWalker.prototype = { reset() {}, _handleRender (node) { - if (node._localMatDirty) { - node._calculWorldMatrix(); - } - let comp = node._renderComponent; let opacity = node.opacity; let assembler = comp && comp.constructor._assembler; @@ -67,6 +63,10 @@ RenderComponentWalker.prototype = { let ctx = this._device._ctx; let cam = this._camera; ctx.setTransform(cam.a, cam.b, cam.c, cam.d, cam.tx, cam.ty); + let node = comp.node; + if (node._worldMatDirty) { + node._updateWorldMatrix(); + } let drawCall = renderer.draw(ctx, comp); this._device._stats.drawcalls += drawCall; }, diff --git a/cocos2d/core/renderer/index.js b/cocos2d/core/renderer/index.js index 0252800d8d..da436ae34d 100644 --- a/cocos2d/core/renderer/index.js +++ b/cocos2d/core/renderer/index.js @@ -66,7 +66,7 @@ module.exports = { this.Texture2D = renderEngine.Texture2D; this.canvas = canvas; - if (CC_JSB) { + if (CC_JSB && CC_NATIVERENDERER) { // native codes will create an instance of Device, so just use the global instance. this.device = window.device; } diff --git a/cocos2d/core/renderer/render-component-walker.js b/cocos2d/core/renderer/render-component-walker.js index 45916a6c69..5f26833511 100644 --- a/cocos2d/core/renderer/render-component-walker.js +++ b/cocos2d/core/renderer/render-component-walker.js @@ -27,6 +27,8 @@ const macro = require('../platform/CCMacro'); const renderEngine = require('./render-engine'); const defaultVertexFormat = require('./vertex-format'); const StencilManager = require('./stencil-manager'); +const atlasManager = require('./utils/dynamic-atlas/manager'); + const gfx = renderEngine.gfx; const RecyclePool = renderEngine.RecyclePool; const InputAssembler = renderEngine.InputAssembler; @@ -40,50 +42,28 @@ const MAX_VERTEX_BYTES = MAX_VERTEX * defaultVertexFormat._bytes; const MAX_INDICE = MAX_VERTEX * BYTE_PER_INDEX; const MAX_INDICE_BYTES = MAX_INDICE * 2; -var _batchData = { - node: null, - vfmt: null, - material: null, - data: null, - vertexOffset: 0, - byteOffset: 0, - indiceOffset: 0, - cullingMask: 1, - MAX_VERTEX: MAX_VERTEX, - MAX_INDICE: MAX_INDICE -}; - var RenderComponentWalker = function (device, renderScene) { this._renderScene = renderScene; this._device = device; this._stencilMgr = StencilManager.sharedManager; - // Buffers - this._vData = new Float32Array(MAX_VERTEX * FLOATS_PER_VERT); - this._uintVData = new Uint32Array(this._vData.buffer); - this._iData = new Uint16Array(MAX_INDICE); - + this._batchData = { + node: null, + worldMatUpdated: false, + vfmt: null, + material: null, + data: null, + vertexOffset: 0, + byteStart: 0, + byteOffset: 0, + indiceStart: 0, + indiceOffset: 0, + cullingMask: 1, + MAX_VERTEX: MAX_VERTEX, + MAX_INDICE: MAX_INDICE + }; + let defaultFormat = new gfx.VertexFormat([]); - this._vbPool = new RecyclePool(function () { - let vb = new gfx.VertexBuffer( - device, - defaultFormat, - gfx.USAGE_DYNAMIC, - null, - 0 - ); - return vb; - }, 16); - this._ibPool = new RecyclePool(function () { - var ib = new gfx.IndexBuffer( - device, - gfx.INDEX_FMT_UINT16, - gfx.USAGE_STATIC, - null, - 0 - ); - return ib; - }, 16); this._iaPool = new RecyclePool(function () { return new InputAssembler(); }, 16); @@ -91,15 +71,21 @@ var RenderComponentWalker = function (device, renderScene) { this._modelPool = new RecyclePool(() => { return new renderEngine.Model(); }, 16); - + + // buffers + this._vb = null; + this._ib = null; + this._buffersToDestroy = []; + + this._maxVertexCount = MAX_VERTEX; + this._maxIndiceCount = MAX_INDICE; + this._reallocBuffer(this._maxVertexCount, this._maxIndiceCount); + this._batchedModels = []; this._dummyNode = new cc.Node(); this._sortKey = 0; this._curCameraNode = null; - - this._handleRender = this._handleRender.bind(this); - this._postHandleRender = this._postHandleRender.bind(this); }; RenderComponentWalker.prototype = { @@ -108,8 +94,6 @@ RenderComponentWalker.prototype = { reset() { // Reset pools this._iaPool.reset(); - this._vbPool.reset(); - this._ibPool.reset(); // Reset scene let scene = this._renderScene; @@ -124,92 +108,98 @@ RenderComponentWalker.prototype = { models.length = 0; this._sortKey = 0; + // Reset useless buffers + if (this._buffersToDestroy.length !== 0) { + for (let i = 0, l = this._buffersToDestroy.length; i < l; i++) { + this._buffersToDestroy[i].destroy(); + } + this._buffersToDestroy.length = 0; + } + // reset caches for handle render components - _batchData.node = null; - _batchData.vfmt = null; - _batchData.material = null; - _batchData.data = null; - _batchData.vertexOffset = 0; - _batchData.byteOffset = 0; - _batchData.indiceOffset = 0; - _batchData.cullingMask = 1; + let batchData = this._batchData; + batchData.node = null; + batchData.worldMatUpdated = false; + batchData.vfmt = null; + batchData.material = null; + batchData.data = null; + batchData.vertexOffset = 0; + batchData.byteStart = 0; + batchData.byteOffset = 0; + batchData.indiceStart = 0; + batchData.indiceOffset = 0; + batchData.cullingMask = 1; // reset stencil manager's cache this._stencilMgr.reset(); }, - _handleRender (node) { - if (node._localMatDirty) { - node._calculWorldMatrix(); - } + _uploadData () { + // update vertext data + let vertexsData = new Float32Array(this._vData.buffer, 0, this._batchData.byteOffset / 4); + let indicesData = new Uint16Array(this._iData.buffer, 0, this._batchData.indiceOffset); - if (node.groupIndex !== 0) { - this._curCameraNode = node; - } + let gl = this._device._gl; + let vb = this._vb; + vb.update(0, vertexsData); - let group = this._curCameraNode ? this._curCameraNode.groupIndex : node.groupIndex; - node._cullingMask = 1 << group; - - let comp = node._renderComponent; - if (comp) { - this.renderComp(comp, comp.constructor._assembler); - } + let ib = this._ib; + ib.update(0, indicesData); }, - _postHandleRender (node) { - let comp = node._renderComponent; - if (comp && comp.constructor._postAssembler) { - this.renderComp(comp, comp.constructor._postAssembler); + _reallocBuffer (vertexCount, indiceCount) { + let batchData = this._batchData; + batchData.vertexOffset = 0; + batchData.byteStart = 0; + batchData.byteOffset = 0; + batchData.indiceStart = 0; + batchData.indiceOffset = 0; + + if (this._vb) { + this._buffersToDestroy.push(this._vb); + } + if (this._ib) { + this._buffersToDestroy.push(this._ib); } - if (this._curCameraNode === node) { - this._curCameraNode = null; - } + this._vData = new Float32Array(vertexCount * FLOATS_PER_VERT); + this._uintVData = new Uint32Array(this._vData.buffer); + this._iData = new Uint16Array(indiceCount); + + this._vb = new gfx.VertexBuffer( + this._device, + defaultVertexFormat, + gfx.USAGE_DYNAMIC, + this._vData.buffer, + vertexCount + ); + + this._ib = new gfx.IndexBuffer( + this._device, + gfx.INDEX_FMT_UINT16, + gfx.USAGE_STATIC, + this._iData.buffer, + indiceCount + ); }, - _flush (batchData) { - let vfmt = batchData.vfmt, + _flush () { + let batchData = this._batchData, material = batchData.material, - vertexByte = batchData.byteOffset, - cullingMask = batchData.cullingMask, - vertexCount = batchData.vertexOffset, - indiceCount = batchData.indiceOffset, - vDataSize = Math.min(bits.nextPow2(vertexByte), MAX_VERTEX_BYTES), - vertexsData = null, - indicesData = null; - - // Prepare data view for vb ib - if (material && vertexCount > 0 && indiceCount > 0) { - vertexsData = new Float32Array(this._vData.buffer, 0, vDataSize / 4); - indicesData = new Uint16Array(this._iData.buffer, 0, indiceCount); - } - else { + indiceStart = batchData.indiceStart, + indiceOffset = batchData.indiceOffset, + indiceCount = indiceOffset - indiceStart; + if (!material || indiceCount <= 0) { return; } let effect = material.effect; - // Generate vb, ib, ia - let device = this._device; - let vb = this._vbPool.add(); - device._stats.vb -= vb._bytes; - vb._format = vfmt; - vb._numVertices = vertexCount; - vb._bytes = vDataSize; - vb.update(0, vertexsData); - device._stats.vb += vb._bytes; - - let ib = this._ibPool.add(); - device._stats.ib -= ib._bytes; - ib._numIndices = indiceCount; - ib._bytes = BYTE_PER_INDEX * indiceCount; - ib.update(0, indicesData); - device._stats.ib += ib._bytes; - + // Generate ia let ia = this._iaPool.add(); - ia._vertexBuffer = vb; - ia._indexBuffer = ib; - ia._start = 0; + ia._vertexBuffer = this._vb; + ia._indexBuffer = this._ib; + ia._start = indiceStart; ia._count = indiceCount; // Check stencil state and modify pass @@ -219,16 +209,20 @@ RenderComponentWalker.prototype = { let model = this._modelPool.add(); this._batchedModels.push(model); model.sortKey = this._sortKey++; - model._cullingMask = CC_EDITOR ? 1 : cullingMask; + model._cullingMask = CC_EDITOR ? 1 : batchData.cullingMask; model.setNode(batchData.node); model.addEffect(effect); model.addInputAssembler(ia); this._renderScene.addModel(model); + + batchData.byteStart = batchData.byteOffset; + batchData.indiceStart = batchData.indiceOffset; }, - _flushIA (batchData) { - let material = batchData.material, + _flushIA () { + let batchData = this._batchData, + material = batchData.material, cullingMask = batchData.cullingMask, iaRenderData = batchData.data; @@ -251,22 +245,16 @@ RenderComponentWalker.prototype = { this._renderScene.addModel(model); }, - renderComp (comp, assembler) { - if (!assembler) { - return; - } - - let material = null, + _commitComp (comp, assembler, cullingMask) { + let batchData = this._batchData, + material = null, datas = null, data = null, - cullingMask = 1, broken = false, iaData = false; // Update render data - datas = assembler.updateRenderData(comp, _batchData); - - cullingMask = comp.node._cullingMask; + datas = assembler.updateRenderData(comp, batchData); for (let id = 0; id < datas.length; id ++) { data = datas[id]; @@ -276,46 +264,118 @@ RenderComponentWalker.prototype = { continue; } + // need to realloc buffers + if ((batchData.vertexOffset + data.vertexCount) > this._maxVertexCount || + (batchData.indiceOffset + data.indiceCount) > this._maxIndiceCount) { + this._uploadData(); + + this._maxVertexCount *= 2; + this._maxIndiceCount *= 2; + this._reallocBuffer(this._maxVertexCount, this._maxIndiceCount); + } + // Check ia data, each ia data should be packed into a separated model iaData = data.type === IARenderData.type; // breaking batch broken = iaData || - !_batchData.material || _batchData.material._hash != material._hash || - _batchData.cullingMask !== cullingMask || - (_batchData.vertexOffset + data.vertexCount > MAX_VERTEX) || - (_batchData.indiceOffset + data.indiceCount > MAX_INDICE); + !batchData.material || batchData.material._hash != material._hash || + batchData.cullingMask !== cullingMask; if (broken) { - this._flush(_batchData); - _batchData.node = assembler.useModel ? comp.node : this._dummyNode; - _batchData.material = material; - _batchData.vfmt = comp._vertexFormat; - _batchData.vertexOffset = 0; - _batchData.byteOffset = 0; - _batchData.indiceOffset = 0; - _batchData.cullingMask = cullingMask; + this._flush(batchData); + + batchData.node = assembler.useModel ? comp.node : this._dummyNode; + batchData.material = material; + batchData.vfmt = comp._vertexFormat; + batchData.cullingMask = cullingMask; } - _batchData.data = data; + batchData.data = data; if (iaData) { - this._flushIA(_batchData); + this._flushIA(); } else { - assembler.fillBuffers(comp, _batchData, _batchData.vertexOffset, this._vData, this._uintVData, this._iData); - _batchData.vertexOffset += data.vertexCount; - _batchData.byteOffset += data.vertexCount * comp._vertexFormat._bytes; - _batchData.indiceOffset += data.indiceCount; + assembler.fillBuffers(comp, batchData, batchData.vertexOffset, this._vData, this._uintVData, this._iData); + batchData.byteOffset += data.vertexCount * comp._vertexFormat._bytes; + batchData.indiceOffset += data.indiceCount; + batchData.vertexOffset += data.vertexCount; } } }, + _findEntry (node) { + if (node._renderComponent) { + return node._renderComponent._chain; + } + + let children = node._children; + let first; + for (let i = 0; i < children.length; i++) { + let child = children[i]; + first = this._findEntry(child); + if (first) { + return first; + } + } + return null; + }, + + _visitNode (node) { + if (!node._activeInHierarchy) { + return; + } + + let batchData = this._batchData; + // Transform + if (node._worldMatDirty) { + node._updateWorldMatrix(); + batchData.worldMatUpdated = true; + } + + // Culling mask + if (node.groupIndex !== 0) { + this._curCameraNode = node; + } + let group = this._curCameraNode ? this._curCameraNode.groupIndex : node.groupIndex; + let cullingMask = node._cullingMask = 1 << group; + + // Render self + let comp = node._renderComponent; + let needDraw = !!(comp && comp._enabled); + if (needDraw) { + let assembler = comp._assembler || comp.constructor._assembler; + this._commitComp(comp, assembler, cullingMask); + } + // Reset worldMatUpdated + batchData.worldMatUpdated = false; + + // Render children + let children = node._children; + for (let i = 0, l = children.length; i < l; i++) { + this._visitNode(children[i]); + } + + // Post render + if (needDraw && comp.constructor._postAssembler) { + this._commitComp(comp, comp.constructor._postAssembler, cullingMask); + } + + // Reset current camera node + if (this._curCameraNode === node) { + this._curCameraNode = null; + } + }, + visit (scene) { this.reset(); - // Store all render components to _queue - scene.walk(this._handleRender, this._postHandleRender); + for (let i = 0, l = scene._children.length; i < l; i++) { + this._visitNode(scene._children[i]); + } - this._flush(_batchData); + atlasManager.update(); + this._flush(); + this._uploadData(); } } diff --git a/cocos2d/core/renderer/render-engine.js b/cocos2d/core/renderer/render-engine.js index bb9888eeab..65f5b7585e 100644 --- a/cocos2d/core/renderer/render-engine.js +++ b/cocos2d/core/renderer/render-engine.js @@ -15056,7 +15056,13 @@ var Model$2 = renderer.Model; var InputAssembler$2 = renderer.InputAssembler; // Add stage to renderer -renderer.addStage('transparent'); +if (renderer.config) { + // JSB adaptation + renderer.config.addStage('transparent'); +} +else { + renderer.addStage('transparent'); +} var renderEngine = { // core classes diff --git a/cocos2d/core/renderer/render-engine.jsb.js b/cocos2d/core/renderer/render-engine.jsb.js index cb499b03fe..c9607022ec 100644 --- a/cocos2d/core/renderer/render-engine.jsb.js +++ b/cocos2d/core/renderer/render-engine.jsb.js @@ -10045,7 +10045,13 @@ var Model = renderer.Model; var InputAssembler = renderer.InputAssembler; // Add stage to renderer -renderer.addStage('transparent'); +if (renderer.config) { + // JSB adaptation + renderer.config.addStage('transparent'); +} +else { + renderer.addStage('transparent'); +} var renderEngine = { // core classes diff --git a/cocos2d/core/renderer/utils/dynamic-atlas/atlas.js b/cocos2d/core/renderer/utils/dynamic-atlas/atlas.js new file mode 100644 index 0000000000..e2bf17eae4 --- /dev/null +++ b/cocos2d/core/renderer/utils/dynamic-atlas/atlas.js @@ -0,0 +1,111 @@ +const space = 1; + +class Atlas { + constructor (width, height) { + let texture = new cc.RenderTexture(); + texture.initWithSize(width, height); + texture.update(); + + this._texture = texture; + + this._x = space; + this._y = space; + this._nexty = space; + + this._width = width; + this._height = height; + + this._innerTextureInfos = {}; + this._innerSpriteFrames = []; + } + + insertSpriteFrame (spriteFrame) { + let rect = spriteFrame._rect, + texture = spriteFrame._texture, + info = this._innerTextureInfos[texture.__instanceId]; + + let sx = rect.x, sy = rect.y; + + if (info) { + rect.x += info.x; + rect.y += info.y; + } + else { + let width = texture.width, height = texture.height; + + if ((this._x + width) > this._width) { + this._x = space; + this._y = this._nexty; + } + + if ((this._y + height) > this._nexty) { + this._nexty = this._y + height; + } + + if (this._nexty > this._height) { + return false; + } + + this._texture.drawTextureAt(texture, this._x, this._y); + + this._innerTextureInfos[texture.__instanceId] = { + x: this._x, + y: this._y, + texture: texture + }; + + rect.x += this._x; + rect.y += this._y; + + this._x += width; + + this._dirty = true; + } + + spriteFrame._original = { + x: sx, + y: sy, + texture: spriteFrame._texture + } + + spriteFrame._texture = this._texture; + + this._innerSpriteFrames.push(spriteFrame); + + return true; + } + + update () { + if (!this._dirty) return; + this._texture.update(); + this._dirty = false; + } + + reset () { + this._x = space; + this._y = space; + this._nexty = space; + + let frames = this._innerSpriteFrames; + for (let i = 0, l = frames.length; i < l; i++) { + let frame = frames[i]; + if (!frame.isValid) { + continue; + } + let oriInfo = frame._original; + frame._rect.x = oriInfo.x; + frame._rect.y = oriInfo.y; + frame._texture = oriInfo.texture; + frame._original = null; + } + this._innerSpriteFrames.length = 0; + this._innerTextureInfos = {}; + } + + destroy () { + this.reset(); + this._texture.destroy(); + } +} + +module.exports = Atlas; diff --git a/cocos2d/core/renderer/utils/dynamic-atlas/manager.js b/cocos2d/core/renderer/utils/dynamic-atlas/manager.js new file mode 100644 index 0000000000..a2a3fc7158 --- /dev/null +++ b/cocos2d/core/renderer/utils/dynamic-atlas/manager.js @@ -0,0 +1,214 @@ +const Atlas = require('./atlas'); + +let _atlases = []; +let _atlasIndex = -1; + +let _maxAtlasCount = 5; +let _textureSize = 2048; +let _maxFrameSize = 512; + +let _enabled = true; + +let _debugNode = null; + +function newAtlas () { + let atlas = new Atlas(_textureSize, _textureSize); + _atlases.push(atlas); + _atlasIndex++; + return atlas; +} + + +/** + * !#en Manager the dynamic atlas. + * !#zh 管理动态图集。 + * @class DynamicAtlasManager + */ +let dynamicAtlasManager = { + + /** + * !#en Enabled or Disabled dynamic atlas. + * !#zh 开启或者关闭动态图集。 + * @property enabled + * @type {Boolean} + */ + get enabled () { + return _enabled; + }, + set enabled (value) { + if (_enabled === value) return; + + if (value) { + this.reset(); + } + _enabled = value; + }, + + /** + * !#en The maximum number of atlas that can be created. + * !#zh 可以创建的最大图集数量。 + * @property maxAtlasCount + * @type {Number} + */ + get maxAtlasCount () { + return _maxAtlasCount; + }, + set maxAtlasCount (value) { + _maxAtlasCount = value; + }, + + /** + * !#en The size of the atlas that was created + * !#zh 创建的图集的宽高 + * @property textureSize + * @type {Number} + */ + get textureSize () { + return _textureSize; + }, + set textureSize (value) { + _textureSize = value; + }, + + /** + * !#en The maximum size of the picture that can be added to the atlas. + * !#zh 可以添加进图集的图片的最大尺寸。 + * @property maxFrameSize + * @type {Number} + */ + get maxFrameSize () { + return _maxFrameSize; + }, + set maxFrameSize (value) { + _maxFrameSize = value; + }, + + /** + * !#en Append a sprite frame into the dynamic atlas. + * !#zh 添加碎图进入动态图集。 + * @method insertSpriteFrame + * @param {SpriteFrame} spriteFrame + */ + insertSpriteFrame (spriteFrame) { + if (CC_EDITOR) return; + if (!_enabled || _atlasIndex === _maxAtlasCount || + !spriteFrame || spriteFrame._original) return; + + let texture = spriteFrame._texture; + if (texture.width > _maxFrameSize || texture.height > _maxFrameSize) { + return; + } + + let atlas = _atlases[_atlasIndex]; + if (!atlas) { + atlas = newAtlas(); + } + + if (!atlas.insertSpriteFrame(spriteFrame) && _atlasIndex !== _maxAtlasCount) { + atlas = newAtlas(); + atlas.insertSpriteFrame(spriteFrame); + } + }, + + /** + * !#en Resets all dynamic atlas, and the existing ones are not destroyed, but are reused. + * !#zh 重置所有动态图集,已有的动态图集并不会被销毁,而是会被复用。 + * @method reset + */ + reset () { + for (let i = 0; i <= _atlasIndex; i++) { + _atlases[i].reset(); + } + _atlasIndex = -1; + }, + + /** + * !#en Releases all dynamic atlas, which are destroyed. + * !#zh 释放所有动态图集,这些图集会被销毁掉。 + * @method releaseAll + */ + releaseAll () { + for (let i = 0, l = _atlases.length; i < l; i++) { + _atlases[i].destroy(); + } + _atlases.length = 0; + _atlasIndex = -1; + }, + + /** + * !#en Displays all the dynamic atlas in the current scene, which you can use to view the current atlas state. + * !#zh 在当前场景中显示所有动态图集,可以用来查看当前的合图状态。 + * @method showDebug + * @param {Boolean} show + */ + showDebug: CC_DEV && function (show) { + if (show) { + if (!_debugNode) { + let width = cc.visibleRect.width; + let height = cc.visibleRect.height; + + _debugNode = new cc.Node('DYNAMIC_ATLAS_DEBUG_NODE'); + _debugNode.width = width; + _debugNode.height = height; + _debugNode.x = width/2; + _debugNode.y = height/2; + _debugNode._zIndex = cc.macro.MAX_ZINDEX; + _debugNode.parent = cc.director.getScene(); + + let scroll = _debugNode.addComponent(cc.ScrollView); + + let content = new cc.Node('CONTENT'); + let layout = content.addComponent(cc.Layout); + layout.type = cc.Layout.Type.VERTICAL; + layout.resizeMode = cc.Layout.ResizeMode.CONTAINER; + content.parent = _debugNode; + content.width = _textureSize; + content.anchorY = 1; + content.x = _textureSize; + + scroll.content = content; + + for (let i = 0; i <= _atlasIndex; i++) { + let node = new cc.Node('ATLAS'); + + let texture = _atlases[i]._texture; + let spriteFrame = new cc.SpriteFrame(); + spriteFrame.setTexture(_atlases[i]._texture); + + let sprite = node.addComponent(cc.Sprite) + sprite.spriteFrame = spriteFrame; + // sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM; + + // node.width = height; + // node.height = height; + + node.parent = content; + } + } + } + else { + if (_debugNode) { + _debugNode.parent = null; + _debugNode = null; + } + } + }, + + update () { + if (!this.enabled) return; + + for (let i = 0; i <= _atlasIndex; i++) { + _atlases[i].update(); + } + }, +}; + +/** + * @module cc + */ + +/** + * @property dynamicAtlasManager + * @type DynamicAtlasManager + */ +module.exports = cc.dynamicAtlasManager = dynamicAtlasManager; \ No newline at end of file diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 38b4618d1c..bf4934136f 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -24,20 +24,19 @@ THE SOFTWARE. ****************************************************************************/ -var PrefabHelper = require('./prefab-helper'); -var Flags = require('../platform/CCObject').Flags; -var misc = require('./misc'); -var js = require('../platform/js'); -var IdGenerater = require('../platform/id-generater'); -var eventManager = require('../event-manager'); +const PrefabHelper = require('./prefab-helper'); +const Flags = require('../platform/CCObject').Flags; +const misc = require('./misc'); +const js = require('../platform/js'); +const IdGenerater = require('../platform/id-generater'); +const eventManager = require('../event-manager'); -var Destroying = Flags.Destroying; -var DontDestroy = Flags.DontDestroy; -var Deactivating = Flags.Deactivating; - -var CHILD_ADDED = 'child-added'; -var CHILD_REMOVED = 'child-removed'; +const Destroying = Flags.Destroying; +const DontDestroy = Flags.DontDestroy; +const Deactivating = Flags.Deactivating; +const CHILD_ADDED = 'child-added'; +const CHILD_REMOVED = 'child-removed'; var idGenerater = new IdGenerater('Node'); @@ -148,6 +147,14 @@ var BaseNode = cc.Class({ _active: true, + /** + * @property _level + * @type {Number} + * @default 0 + * @private + */ + _level: 0, + /** * @property _components * @type {Component[]} @@ -323,7 +330,7 @@ var BaseNode = cc.Class({ * @param {String} [name] */ ctor (name) { - this._name = typeof name !== 'undefined' ? name : 'New Node'; + this._name = name !== undefined ? name : 'New Node'; this._activeInHierarchy = false; // Support for ActionManager and EventManager @@ -373,6 +380,7 @@ var BaseNode = cc.Class({ if (CC_DEBUG && (value._objFlags & Deactivating)) { cc.errorID(3821); } + this._level = value._level + 1; eventManager._setDirtyForNode(this); value._children.push(this); value.emit(CHILD_ADDED, this); diff --git a/cocos2d/core/utils/profiler/CCProfiler.js b/cocos2d/core/utils/profiler/CCProfiler.js index 88487ea843..df367e65bb 100644 --- a/cocos2d/core/utils/profiler/CCProfiler.js +++ b/cocos2d/core/utils/profiler/CCProfiler.js @@ -121,8 +121,9 @@ function generateStats () { mode: { desc: cc.game.renderType === cc.game.RENDER_TYPE_WEBGL ? 'WebGL' : 'Canvas', min: 1 } }; + let now = performance.now(); for (let id in _stats) { - _stats[id]._counter = new PerfCounter(id, _stats[id]); + _stats[id]._counter = new PerfCounter(id, _stats[id], now); } } @@ -163,18 +164,20 @@ function generateNode () { function beforeUpdate () { generateNode(); - _stats['frame']._counter.start(); - _stats['logic']._counter.start(); + let now = cc.director._lastUpdate; + _stats['frame']._counter.start(now); + _stats['logic']._counter.start(now); } function afterUpdate () { + let now = performance.now(); if (cc.director.isPaused()) { - _stats['frame']._counter.start(); + _stats['frame']._counter.start(now); } else { - _stats['logic']._counter.end(); + _stats['logic']._counter.end(now); } - _stats['render']._counter.start(); + _stats['render']._counter.start(now); } function updateLabel (stat) { @@ -185,16 +188,17 @@ function updateLabel (stat) { } function afterDraw () { - _stats['render']._counter.end(); + let now = performance.now(); + _stats['render']._counter.end(now); _stats['draws']._counter.value = cc.renderer.drawCalls; - _stats['frame']._counter.end(); - _stats['fps']._counter.frame(); + _stats['frame']._counter.end(now); + _stats['fps']._counter.frame(now); let left = ''; let right = ''; for (let id in _stats) { let stat = _stats[id]; - stat._counter.sample(); + stat._counter.sample(now); left += stat.desc + '\n'; right += stat._counter.human() + '\n'; diff --git a/cocos2d/core/utils/profiler/counter.js b/cocos2d/core/utils/profiler/counter.js index 681e91c900..551619947f 100644 --- a/cocos2d/core/utils/profiler/counter.js +++ b/cocos2d/core/utils/profiler/counter.js @@ -1,5 +1,5 @@ class Counter { - constructor(id, opts) { + constructor(id, opts, now) { this._id = id; this._opts = opts || {}; @@ -8,15 +8,15 @@ class Counter { this._averageValue = 0; this._accumValue = 0; this._accumSamples = 0; - this._accumStart = window.performance.now(); + this._accumStart = now; } - _average(v) { + _average(v, now) { if (this._opts.average) { this._accumValue += v; ++this._accumSamples; - let t = performance.now(); + let t = now; if (t - this._accumStart >= this._opts.average) { this._averageValue = this._accumValue / this._accumSamples; this._accumValue = 0; @@ -31,8 +31,8 @@ class Counter { this._value = v; } - sample() { - this._average(this._value); + sample(now) { + this._average(this._value, now); } human() { diff --git a/cocos2d/core/utils/profiler/perf-counter.js b/cocos2d/core/utils/profiler/perf-counter.js index 8f8864b0aa..778810ec0a 100644 --- a/cocos2d/core/utils/profiler/perf-counter.js +++ b/cocos2d/core/utils/profiler/perf-counter.js @@ -1,25 +1,25 @@ const Counter = require('./counter'); class PerfCounter extends Counter { - constructor(id, opts) { - super(id, opts); + constructor(id, opts, now) { + super(id, opts, now); // DISABLE // this._idstart = `${id}_start`; // this._idend = `${id}_end`; - this._time = window.performance.now(); + this._time = now; } - start() { - this._time = window.performance.now(); + start(now) { + this._time = now; // DISABLE: long time running will cause performance drop down // window.performance.mark(this._idstart); } - end() { - this._value = window.performance.now() - this._time; + end(now) { + this._value = now - this._time; // DISABLE: long time running will cause performance drop down // window.performance.mark(this._idend); @@ -33,8 +33,8 @@ class PerfCounter extends Counter { this.start(); } - frame() { - let t = window.performance.now(); + frame(now) { + let t = now; let e = t - this._time; this._total++; let avg = this._opts.average || 1000; diff --git a/cocos2d/tilemap/tmx-layer-assembler.js b/cocos2d/tilemap/tmx-layer-assembler.js index 83af5812c4..aad85d1775 100644 --- a/cocos2d/tilemap/tmx-layer-assembler.js +++ b/cocos2d/tilemap/tmx-layer-assembler.js @@ -110,7 +110,7 @@ let tmxAssembler = js.addon({ let appx = node._anchorPoint.x * node._contentSize.width, appy = node._anchorPoint.y * node._contentSize.height; - node.getWorldMatrix(_mat4_temp); + mat4.copy(_mat4_temp, node._worldMatrix); vec3.set(_vec3_temp, -appx, -appy, 0); mat4.translate(_mat4_temp, _mat4_temp, _vec3_temp); diff --git a/cocos2d/videoplayer/video-player-impl.js b/cocos2d/videoplayer/video-player-impl.js index 62c72824ed..ded173ea9b 100644 --- a/cocos2d/videoplayer/video-player-impl.js +++ b/cocos2d/videoplayer/video-player-impl.js @@ -366,7 +366,6 @@ let VideoPlayerImpl = cc.Class({ updateMatrix (node) { if (!this._video || !this._visible) return; - node._updateWorldMatrix(); var mat = node._worldMatrix; if (!this._forceUpdate && this._m00 === mat.m00 && this._m01 === mat.m01 && this._m04 === mat.m04 && this._m05 === mat.m05 && this._m12 === mat.m12 && this._m13 === mat.m13 && diff --git a/cocos2d/webview/webview-impl.js b/cocos2d/webview/webview-impl.js index a989061aaf..495b051051 100644 --- a/cocos2d/webview/webview-impl.js +++ b/cocos2d/webview/webview-impl.js @@ -299,7 +299,6 @@ var WebViewImpl = cc.Class({ updateMatrix (node) { if (!this._div || !this._visible) return; - node._updateWorldMatrix(); var mat = node._worldMatrix; if (!this._forceUpdate && this._m00 === mat.m00 && this._m01 === mat.m01 && this._m04 === mat.m04 && this._m05 === mat.m05 && this._m12 === mat.m12 && this._m13 === mat.m13 && diff --git a/extensions/dragonbones/CCSlot.js b/extensions/dragonbones/CCSlot.js index b5a94773ac..06cde606fa 100644 --- a/extensions/dragonbones/CCSlot.js +++ b/extensions/dragonbones/CCSlot.js @@ -354,7 +354,7 @@ dragonBones.CCSlot = cc.Class({ let node = this._display.node; math.mat4.copy(node._matrix, t); node._localMatDirty = false; - node._worldMatDirty = true; + node.setWorldDirty(); } this._updateVertices(); diff --git a/extensions/dragonbones/canvas-assembler.js b/extensions/dragonbones/canvas-assembler.js index eaa686712a..e73c1d71ae 100644 --- a/extensions/dragonbones/canvas-assembler.js +++ b/extensions/dragonbones/canvas-assembler.js @@ -17,7 +17,6 @@ let armatureAssembler = { ctx.save(); let node = comp.node; - node._updateWorldMatrix(); let matrix = node._worldMatrix; let texture = comp.dragonAtlasAsset.texture; diff --git a/extensions/dragonbones/webgl-assembler.js b/extensions/dragonbones/webgl-assembler.js index 1fa0bab08a..c89be14a13 100644 --- a/extensions/dragonbones/webgl-assembler.js +++ b/extensions/dragonbones/webgl-assembler.js @@ -99,8 +99,7 @@ let armatureAssembler = js.addon({ let node = comp.node; _z = node._position.z; - - node._updateWorldMatrix(); + _worldMatrix = node._worldMatrix; _a = _worldMatrix.m00; _b = _worldMatrix.m01; _c = _worldMatrix.m04; _d = _worldMatrix.m05; _tx = _worldMatrix.m12; _ty = _worldMatrix.m13; diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index 6bf3513f29..372047a5f3 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -217,9 +217,11 @@ exports.buildJsb = function (sourceFile, outputFile, excludes, opt_macroFlags, c var outFile = Path.basename(outputFile); var outDir = Path.dirname(outputFile); - var bundler = createBundler(sourceFile, { - aliasifyConfig: aliasifyConfig - }); + var opts = {}; + if (opt_macroFlags && opt_macroFlags.nativeRenderer) { + opts.aliasifyConfig = aliasifyConfig; + } + var bundler = createBundler(sourceFile, opts); excludes = excludes.concat(jsbSkipModules); excludes.forEach(function (module) { bundler.ignore(require.resolve(module)); @@ -249,9 +251,11 @@ exports.buildJsbMin = function (sourceFile, outputFile, excludes, opt_macroFlags var outFile = Path.basename(outputFile); var outDir = Path.dirname(outputFile); - var bundler = createBundler(sourceFile, { - aliasifyConfig: aliasifyConfig - }); + var opts = {}; + if (opt_macroFlags && opt_macroFlags.nativeRenderer) { + opts.aliasifyConfig = aliasifyConfig; + } + var bundler = createBundler(sourceFile, opts); excludes = excludes.concat(jsbSkipModules); excludes.forEach(function (module) { bundler.ignore(require.resolve(module)); diff --git a/gulp/util/utils.js b/gulp/util/utils.js index 45774f5c61..cbbfef7622 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -1,6 +1,6 @@ const PLATFORM_MACROS = ['CC_EDITOR', 'CC_PREVIEW', 'CC_BUILD', 'CC_TEST']; -const FLAGS = ['jsb', 'wechatgame', 'qqplay', 'debug']; +const FLAGS = ['jsb', 'wechatgame', 'qqplay', 'debug', 'nativeRenderer']; // generate macros for uglify's global_defs // available platforms: 'editor' | 'preview' | 'build' | 'test' diff --git a/jsb/builtin/glOptMode.js b/jsb/builtin/glOptMode.js new file mode 100644 index 0000000000..23dcf8cea1 --- /dev/null +++ b/jsb/builtin/glOptMode.js @@ -0,0 +1,1473 @@ +var GL_COMMAND_ACTIVE_TEXTURE = 0; +var GL_COMMAND_ATTACH_SHADER = 1; +var GL_COMMAND_BIND_ATTRIB_LOCATION = 2; +var GL_COMMAND_BIND_BUFFER = 3; +var GL_COMMAND_BIND_FRAME_BUFFER = 4; +var GL_COMMAND_BIND_RENDER_BUFFER = 5; +var GL_COMMAND_BIND_TEXTURE = 6; +var GL_COMMAND_BLEND_COLOR = 7; +var GL_COMMAND_BLEND_EQUATION = 8; +var GL_COMMAND_BLEND_EQUATION_SEPARATE = 9; +var GL_COMMAND_BLEND_FUNC = 10; +var GL_COMMAND_BLEND_FUNC_SEPARATE = 11; +var GL_COMMAND_BUFFER_DATA = 12; +var GL_COMMAND_BUFFER_SUB_DATA = 13; +var GL_COMMAND_CLEAR = 14; +var GL_COMMAND_CLEAR_COLOR = 15; +var GL_COMMAND_CLEAR_DEPTH = 16; +var GL_COMMAND_CLEAR_STENCIL = 17; +var GL_COMMAND_COLOR_MASK = 18; +var GL_COMMAND_COMMIT = 19; +var GL_COMMAND_COMPILE_SHADER = 20; +var GL_COMMAND_COMPRESSED_TEX_IMAGE_2D = 21; +var GL_COMMAND_COMPRESSED_TEX_SUB_IMAGE_2D = 22; +var GL_COMMAND_COPY_TEX_IMAGE_2D = 23; +var GL_COMMAND_COPY_TEX_SUB_IMAGE_2D = 24; +var GL_COMMAND_CULL_FACE = 25; +var GL_COMMAND_DELETE_BUFFER = 26; +var GL_COMMAND_DELETE_FRAME_BUFFER = 27; +var GL_COMMAND_DELETE_PROGRAM = 28; +var GL_COMMAND_DELETE_RENDER_BUFFER = 29; +var GL_COMMAND_DELETE_SHADER = 30; +var GL_COMMAND_DELETE_TEXTURE = 31; +var GL_COMMAND_DEPTH_FUNC = 32; +var GL_COMMAND_DEPTH_MASK = 33; +var GL_COMMAND_DEPTH_RANGE = 34; +var GL_COMMAND_DETACH_SHADER = 35; +var GL_COMMAND_DISABLE = 36; +var GL_COMMAND_DISABLE_VERTEX_ATTRIB_ARRAY = 37; +var GL_COMMAND_DRAW_ARRAYS = 38; +var GL_COMMAND_DRAW_ELEMENTS = 39; +var GL_COMMAND_ENABLE = 40; +var GL_COMMAND_ENABLE_VERTEX_ATTRIB_ARRAY = 41; +var GL_COMMAND_FINISH = 42; +var GL_COMMAND_FLUSH = 43; +var GL_COMMAND_FRAME_BUFFER_RENDER_BUFFER = 44; +var GL_COMMAND_FRAME_BUFFER_TEXTURE_2D = 45; +var GL_COMMAND_FRONT_FACE = 46; +var GL_COMMAND_GENERATE_MIPMAP = 47; +var GL_COMMAND_HINT = 48; +var GL_COMMAND_LINE_WIDTH = 49; +var GL_COMMAND_LINK_PROGRAM = 50; +var GL_COMMAND_PIXEL_STOREI = 51; +var GL_COMMAND_POLYGON_OFFSET = 52; +var GL_COMMAND_RENDER_BUFFER_STORAGE = 53; +var GL_COMMAND_SAMPLE_COVERAGE = 54; +var GL_COMMAND_SCISSOR = 55; +var GL_COMMAND_SHADER_SOURCE = 56; +var GL_COMMAND_STENCIL_FUNC = 57; +var GL_COMMAND_STENCIL_FUNC_SEPARATE = 58; +var GL_COMMAND_STENCIL_MASK = 59; +var GL_COMMAND_STENCIL_MASK_SEPARATE = 60; +var GL_COMMAND_STENCIL_OP = 61; +var GL_COMMAND_STENCIL_OP_SEPARATE = 62; +var GL_COMMAND_TEX_IMAGE_2D = 63; +var GL_COMMAND_TEX_PARAMETER_F = 64; +var GL_COMMAND_TEX_PARAMETER_I = 65; +var GL_COMMAND_TEX_SUB_IMAGE_2D = 66; +var GL_COMMAND_UNIFORM_1F = 67; +var GL_COMMAND_UNIFORM_1FV = 68; +var GL_COMMAND_UNIFORM_1I = 69; +var GL_COMMAND_UNIFORM_1IV = 70; +var GL_COMMAND_UNIFORM_2F = 71; +var GL_COMMAND_UNIFORM_2FV = 72; +var GL_COMMAND_UNIFORM_2I = 73; +var GL_COMMAND_UNIFORM_2IV = 74; +var GL_COMMAND_UNIFORM_3F = 75; +var GL_COMMAND_UNIFORM_3FV = 76; +var GL_COMMAND_UNIFORM_3I = 77; +var GL_COMMAND_UNIFORM_3IV = 78; +var GL_COMMAND_UNIFORM_4F = 79; +var GL_COMMAND_UNIFORM_4FV = 80; +var GL_COMMAND_UNIFORM_4I = 81; +var GL_COMMAND_UNIFORM_4IV = 82; +var GL_COMMAND_UNIFORM_MATRIX_2FV = 83; +var GL_COMMAND_UNIFORM_MATRIX_3FV = 84; +var GL_COMMAND_UNIFORM_MATRIX_4FV = 85; +var GL_COMMAND_USE_PROGRAM = 86; +var GL_COMMAND_VALIDATE_PROGRAM = 87; +var GL_COMMAND_VERTEX_ATTRIB_1F = 88; +var GL_COMMAND_VERTEX_ATTRIB_2F = 89; +var GL_COMMAND_VERTEX_ATTRIB_3F = 90; +var GL_COMMAND_VERTEX_ATTRIB_4F = 91; +var GL_COMMAND_VERTEX_ATTRIB_1FV = 92; +var GL_COMMAND_VERTEX_ATTRIB_2FV = 93; +var GL_COMMAND_VERTEX_ATTRIB_3FV = 94; +var GL_COMMAND_VERTEX_ATTRIB_4FV = 95; +var GL_COMMAND_VERTEX_ATTRIB_POINTER = 96; +var GL_COMMAND_VIEW_PORT = 97; + +const gl = __gl; + +// _gl save the orignal gl functions. +var _gl = {}; +for (var k in gl) { + _gl[k] = gl[k]; +} + +var total_size = 100000; +var next_index = 0; +var buffer_data; + +// Batch GL commands is enabled by default. +function batchGLCommandsToNative() { + if (gl._flushCommands) { + if (isSupportTypeArray()) { + console.log('Enable batch GL commands optimization!'); + attachMethodOpt(); + buffer_data = new Float32Array(total_size); + } + else { + console.log(`Disable batch GL commands, TypedArray Native API isn't supported!`); + } + } + else { + console.log(`Disable batch GL commands, _flushCommands isn't binded!`); + } +} + +function disableBatchGLCommandsToNative() { + // Reset __gl variable to the default one. + flushCommands(); + for (var k in _gl) { + __gl[k] = _gl[k]; + } + console.log('Disable batch GL commands optimization!'); +} + +function flushCommands() { + if (next_index > 0) { + gl._flushCommands(next_index, buffer_data); + next_index = 0; + } +} + +function activeTextureOpt(texture) { + if (next_index + 2 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_ACTIVE_TEXTURE; + buffer_data[next_index + 1] = texture; + next_index += 2; +} + +function attachShaderOpt(program, shader) { + if (next_index + 3 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_ATTACH_SHADER; + buffer_data[next_index + 1] = program ? program._id : 0; + buffer_data[next_index + 2] = shader ? shader._id : 0; + next_index += 3; +} + +function bindAttribLocationOpt(program, index, name) { + flushCommands(); + _gl.bindAttribLocation(program, index, name); +} + +function bindBufferOpt(target, buffer) { + if (next_index + 3 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BIND_BUFFER; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = buffer ? buffer._id : 0; + next_index += 3; +} + +function bindFramebufferOpt(target, framebuffer) { + if (next_index + 3 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BIND_FRAME_BUFFER; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = framebuffer ? framebuffer._id : 0; + next_index += 3; +} + +function bindRenderbufferOpt(target, renderbuffer) { + if (next_index + 3 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BIND_RENDER_BUFFER; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = renderbuffer ? renderbuffer._id : 0; + next_index += 3; +} + +function bindTextureOpt(target, texture) { + if (next_index + 3 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BIND_TEXTURE; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = texture ? texture._id : 0; + next_index += 3; +} + +function blendColorOpt(red, green, blue, alpha) { + if (next_index + 5 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BLEND_COLOR; + buffer_data[next_index + 1] = red; + buffer_data[next_index + 2] = green; + buffer_data[next_index + 3] = blue; + buffer_data[next_index + 4] = alpha; + next_index += 5; +} + +function blendEquationOpt(mode) { + if (next_index + 2 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BLEND_EQUATION; + buffer_data[next_index + 1] = mode; + next_index += 2; +} + +function blendEquationSeparateOpt(modeRGB, modeAlpha) { + if (next_index + 3 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BLEND_EQUATION_SEPARATE; + buffer_data[next_index + 1] = modeRGB; + buffer_data[next_index + 2] = modeAlpha; + next_index += 3; +} + +function blendFuncOpt(sfactor, dfactor) { + if (next_index + 3 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BLEND_FUNC; + buffer_data[next_index + 1] = sfactor; + buffer_data[next_index + 2] = dfactor; + next_index += 3; +} + +function blendFuncSeparateOpt(srcRGB, dstRGB, srcAlpha, dstAlpha) { + if (next_index + 5 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_BLEND_FUNC_SEPARATE; + buffer_data[next_index + 1] = srcRGB; + buffer_data[next_index + 2] = dstRGB; + buffer_data[next_index + 3] = srcAlpha; + buffer_data[next_index + 4] = dstAlpha; + next_index += 5; +} + +function bufferDataOpt(target, data, usage) { + flushCommands(); + _gl.bufferData(target, data, usage); +} + +function bufferSubDataOpt(target, offset, data) { + flushCommands(); + _gl.bufferSubData(target, offset, data); +} + +function checkFramebufferStatusOpt(target) { + flushCommands(); + return _gl.checkFramebufferStatus(target); +} + +function clearOpt(mask) { + if (next_index + 2 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_CLEAR; + buffer_data[next_index + 1] = mask; + next_index += 2; +} + +function clearColorOpt(red, green, blue, alpha) { + if (next_index + 5 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_CLEAR_COLOR; + buffer_data[next_index + 1] = red; + buffer_data[next_index + 2] = green; + buffer_data[next_index + 3] = blue; + buffer_data[next_index + 4] = alpha; + next_index += 5; +} + +function clearDepthOpt(depth) { + if (next_index + 2 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_CLEAR_DEPTH; + buffer_data[next_index + 1] = depth; + next_index += 2; +} + +function clearStencilOpt(s) { + if (next_index + 2 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_CLEAR_STENCIL; + buffer_data[next_index + 1] = s; + next_index += 2; +} + +function colorMaskOpt(red, green, blue, alpha) { + if (next_index + 5 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_COLOR_MASK; + buffer_data[next_index + 1] = red ? 1 : 0; + buffer_data[next_index + 2] = green ? 1 : 0; + buffer_data[next_index + 3] = blue ? 1 : 0; + buffer_data[next_index + 4] = alpha ? 1 : 0; + next_index += 5; +} + +function compileShaderOpt(shader) { + if (next_index + 2 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_COMPILE_SHADER; + buffer_data[next_index + 1] = shader ? shader._id : 0; + next_index += 2; +} + +function compressedTexImage2DOpt(target, level, internalformat, width, height, border, data) { + flushCommands(); + _gl.compressedTexImage2D(target, level, internalformat, width, height, border, data); +} + +function compressedTexSubImage2DOpt(target, level, xoffset, yoffset, width, height, format, data) { + flushCommands(); + _gl.compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, data); +} + +function copyTexImage2DOpt(target, level, internalformat, x, y, width, height, border) { + if (next_index + 9 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_COPY_TEX_IMAGE_2D; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = level; + buffer_data[next_index + 3] = internalformat; + buffer_data[next_index + 4] = x; + buffer_data[next_index + 5] = y; + buffer_data[next_index + 6] = width; + buffer_data[next_index + 7] = height; + buffer_data[next_index + 8] = border; + next_index += 9; +} + +function copyTexSubImage2DOpt(target, level, xoffset, yoffset, x, y, width, height) { + if (next_index + 9 > total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_COPY_TEX_SUB_IMAGE_2D; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = level; + buffer_data[next_index + 3] = xoffset; + buffer_data[next_index + 4] = yoffset; + buffer_data[next_index + 5] = x; + buffer_data[next_index + 6] = y; + buffer_data[next_index + 7] = width; + buffer_data[next_index + 8] = height; + next_index += 9; +} + +function createBufferOpt() { + flushCommands(); + return _gl.createBuffer(); +} + +function createFramebufferOpt() { + flushCommands(); + return _gl.createFramebuffer(); +} + +function createProgramOpt() { + flushCommands(); + return _gl.createProgram(); +} + +function createRenderbufferOpt() { + flushCommands(); + return _gl.createRenderbuffer(); +} + +function createShaderOpt(type) { + flushCommands(); + return _gl.createShader(type); +} + +function createTextureOpt() { + flushCommands(); + return _gl.createTexture(); +} + +function cullFaceOpt(mode) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_CULL_FACE; + buffer_data[next_index + 1] = mode; + next_index += 2; +} + +function deleteBufferOpt(buffer) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DELETE_BUFFER; + buffer_data[next_index + 1] = buffer ? buffer._id : 0; + next_index += 2; +} + +function deleteFramebufferOpt(framebuffer) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DELETE_FRAME_BUFFER; + buffer_data[next_index + 1] = framebuffer ? framebuffer._id : 0; + next_index += 2; +} + +function deleteProgramOpt(program) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DELETE_PROGRAM; + buffer_data[next_index + 1] = program ? program._id : 0; + next_index += 2; +} + +function deleteRenderbufferOpt(renderbuffer) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DELETE_RENDER_BUFFER; + buffer_data[next_index + 1] = renderbuffer ? renderbuffer._id : 0; + next_index += 2; +} + +function deleteShaderOpt(shader) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DELETE_SHADER; + buffer_data[next_index + 1] = shader ? shader._id : 0; + next_index += 2; +} + +function deleteTextureOpt(texture) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DELETE_TEXTURE; + buffer_data[next_index + 1] = texture ? texture._id : 0; + next_index += 2; +} + +function depthFuncOpt(func) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DEPTH_FUNC; + buffer_data[next_index + 1] = func; + next_index += 2; +} + +function depthMaskOpt(flag) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DEPTH_MASK; + buffer_data[next_index + 1] = flag ? 1 : 0; + next_index += 2; +} + +function depthRangeOpt(zNear, zFar) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DEPTH_RANGE; + buffer_data[next_index + 1] = zNear; + buffer_data[next_index + 1] = zFar; + next_index += 3; +} + +function detachShaderOpt(program, shader) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DETACH_SHADER; + buffer_data[next_index + 1] = program ? program._id : 0; + buffer_data[next_index + 1] = shader ? shader._id : 0; + next_index += 3; +} + +function disableOpt(cap) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DISABLE; + buffer_data[next_index + 1] = cap; + next_index += 2; +} + +function disableVertexAttribArrayOpt(index) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DISABLE_VERTEX_ATTRIB_ARRAY; + buffer_data[next_index + 1] = index; + next_index += 2; +} + +function drawArraysOpt(mode, first, count) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DRAW_ARRAYS; + buffer_data[next_index + 1] = mode; + buffer_data[next_index + 2] = first; + buffer_data[next_index + 3] = count; + next_index += 4; +} + +function drawElementsOpt(mode, count, type, offset) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_DRAW_ELEMENTS; + buffer_data[next_index + 1] = mode; + buffer_data[next_index + 2] = count; + buffer_data[next_index + 3] = type; + buffer_data[next_index + 4] = offset ? offset : 0; + next_index += 5; +} + +function enableOpt(cap) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_ENABLE; + buffer_data[next_index + 1] = cap; + next_index += 2; +} + +function enableVertexAttribArrayOpt(index) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_ENABLE_VERTEX_ATTRIB_ARRAY; + buffer_data[next_index + 1] = index; + next_index += 2; +} + +function finishOpt() { + if (next_index + 1 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_FINISH; + next_index += 1; +} + +function flushOpt() { + if (next_index + 1 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_FLUSH; + next_index += 1; +} + +function framebufferRenderbufferOpt(target, attachment, renderbuffertarget, renderbuffer) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_FRAME_BUFFER_RENDER_BUFFER; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = attachment; + buffer_data[next_index + 3] = renderbuffertarget; + buffer_data[next_index + 4] = renderbuffer ? renderbuffer._id : 0; + next_index += 5; +} + +function framebufferTexture2DOpt(target, attachment, textarget, texture, level) { + if (next_index + 6 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_FRAME_BUFFER_TEXTURE_2D; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = attachment; + buffer_data[next_index + 3] = textarget; + buffer_data[next_index + 4] = texture ? texture._id : 0; + buffer_data[next_index + 5] = level; + next_index += 6; +} + +function frontFaceOpt(mode) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_FRONT_FACE; + buffer_data[next_index + 1] = mode; + next_index += 2; +} + +function generateMipmapOpt(target) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_GENERATE_MIPMAP; + buffer_data[next_index + 1] = target; + next_index += 2; +} + +function getActiveAttribOpt(program, index) { + flushCommands(); + return _gl.getActiveAttrib(program, index); +} + +function getActiveUniformOpt(program, index) { + flushCommands(); + return _gl.getActiveUniform(program, index); +} + +function getAttachedShadersOpt(program) { + flushCommands(); + return _gl.getAttachedShaders(program); +} + +function getAttribLocationOpt(program, name) { + flushCommands(); + return _gl.getAttribLocation(program, name); +} + +function getBufferParameterOpt(target, pname) { + flushCommands(); + return _gl.getBufferParameter(target, pname); +} + +function getParameterOpt(pname) { + flushCommands(); + return _gl.getParameter(pname); +} + +function getErrorOpt() { + flushCommands(); + return _gl.getError(); +} + +function getFramebufferAttachmentParameterOpt(target, attachment, pname) { + flushCommands(); + return _gl.getFramebufferAttachmentParameter(target, attachment, pname); +} + +function getProgramParameterOpt(program, pname) { + flushCommands(); + return _gl.getProgramParameter(program, pname); +} + +function getProgramInfoLogOpt(program) { + flushCommands(); + return _gl.getProgramInfoLog(program); +} + +function getRenderbufferParameterOpt(target, pname) { + flushCommands(); + return _gl.getRenderbufferParameter(target, pname); +} + +function getShaderParameterOpt(shader, pname) { + flushCommands(); + return _gl.getShaderParameter(shader, pname); +} + +function getShaderPrecisionFormatOpt(shadertype, precisiontype) { + flushCommands(); + return _gl.getShaderPrecisionFormat(shadertype, precisiontype); +} + +function getShaderInfoLogOpt(shader) { + flushCommands(); + return _gl.getShaderInfoLog(shader); +} + +function getShaderSourceOpt(shader) { + flushCommands(); + return _gl.getShaderSource(shader); +} + +function getTexParameterOpt(target, pname) { + flushCommands(); + return _gl.getTexParameter(target, pname); +} + +function getUniformOpt(program, location) { + flushCommands(); + return _gl.getUniform(program, location); +} + +function getUniformLocationOpt(program, name) { + flushCommands(); + return _gl.getUniformLocation(program, name); +} + +function getVertexAttribOpt(index, pname) { + flushCommands(); + return _gl.getVertexAttrib(index, pname); +} + +function getVertexAttribOffsetOpt(index, pname) { + flushCommands(); + return _gl.getVertexAttribOffset(index, pname); +} + +function hintOpt(target, mode) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_HINT; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = mode; + next_index += 3; +} + +function isBufferOpt(buffer) { + flushCommands(); + return _gl.isBuffer(buffer); +} + +function isEnabledOpt(cap) { + flushCommands(); + return _gl.isEnabled(cap); +} + +function isFramebufferOpt(framebuffer) { + flushCommands(); + return _gl.isFramebuffer(framebuffer); +} + +function isProgramOpt(program) { + flushCommands(); + return _gl.isProgram(program); +} + +function isRenderbufferOpt(renderbuffer) { + flushCommands(); + return _gl.isRenderbuffer(renderbuffer); +} + +function isShaderOpt(shader) { + flushCommands(); + return _gl.isShader(shader); +} + +function isTextureOpt(texture) { + flushCommands(); + return _gl.isTexture(texture); +} + +function lineWidthOpt(width) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_LINE_WIDTH; + buffer_data[next_index + 1] = width; + next_index += 2; +} + +function linkProgramOpt(program) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_LINK_PROGRAM; + buffer_data[next_index + 1] = program ? program._id : 0; + next_index += 2; +} + +function pixelStoreiOpt(pname, param) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_PIXEL_STOREI; + buffer_data[next_index + 1] = pname; + buffer_data[next_index + 2] = param; + next_index += 3; +} + +function polygonOffsetOpt(factor, units) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_POLYGON_OFFSET; + buffer_data[next_index + 1] = factor; + buffer_data[next_index + 2] = units; + next_index += 3; +} + +function readPixelsOpt(x, y, width, height, format, type, pixels) { + flushCommands(); + _gl.readPixels(x, y, width, height, format, type, pixels); +} + +function renderbufferStorageOpt(target, internalFormat, width, height) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_RENDER_BUFFER_STORAGE; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = internalFormat; + buffer_data[next_index + 3] = width; + buffer_data[next_index + 4] = height; + next_index += 5; +} + +function sampleCoverageOpt(value, invert) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_SAMPLE_COVERAGE; + buffer_data[next_index + 1] = value; + buffer_data[next_index + 2] = invert ? 1 : 0; + next_index += 3; +} + +function scissorOpt(x, y, width, height) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_SCISSOR; + buffer_data[next_index + 1] = x; + buffer_data[next_index + 2] = y; + buffer_data[next_index + 3] = width; + buffer_data[next_index + 4] = height; + next_index += 5; +} + +function shaderSourceOpt(shader, source) { + flushCommands(); + _gl.shaderSource(shader, source); +} + +function stencilFuncOpt(func, ref, mask) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_STENCIL_FUNC; + buffer_data[next_index + 1] = func; + buffer_data[next_index + 2] = ref; + buffer_data[next_index + 3] = mask; + next_index += 4; +} + +function stencilFuncSeparateOpt(face, func, ref, mask) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_STENCIL_FUNC_SEPARATE; + buffer_data[next_index + 1] = face; + buffer_data[next_index + 2] = func; + buffer_data[next_index + 3] = ref; + buffer_data[next_index + 4] = mask; + next_index += 5; +} + +function stencilMaskOpt(mask) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_STENCIL_MASK; + buffer_data[next_index + 1] = mask; + next_index += 2; +} + +function stencilMaskSeparateOpt(face, mask) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_STENCIL_MASK_SEPARATE; + buffer_data[next_index + 1] = face; + buffer_data[next_index + 2] = mask; + next_index += 3; +} + +function stencilOpOpt(fail, zfail, zpass) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_STENCIL_OP; + buffer_data[next_index + 1] = fail; + buffer_data[next_index + 2] = zfail; + buffer_data[next_index + 3] = zpass; + next_index += 4; +} + +function stencilOpSeparateOpt(face, fail, zfail, zpass) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_STENCIL_OP_SEPARATE; + buffer_data[next_index + 1] = face; + buffer_data[next_index + 2] = fail; + buffer_data[next_index + 3] = zfail; + buffer_data[next_index + 4] = zpass; + next_index += 5; +} + +function texImage2DOpt() { + flushCommands(); + var argCount = arguments.length; + if (argCount === 6) { + _gl.texImage2D(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); + } + else if (argCount === 9) { + _gl.texImage2D(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8]); + } + else { + console.log(`texImage2DOpt: Wrong number of arguments, expected 6 or 9 but got ${argCount}`); + } +} + +function texParameterfOpt(target, pname, param) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_TEX_PARAMETER_F; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = pname; + buffer_data[next_index + 3] = param; + next_index += 4; +} + +function texParameteriOpt(target, pname, param) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_TEX_PARAMETER_I; + buffer_data[next_index + 1] = target; + buffer_data[next_index + 2] = pname; + buffer_data[next_index + 3] = param; + next_index += 4; +} + +function texSubImage2DOpt(target, level, xoffset, yoffset, width, height, format, type, pixels) { + flushCommands(); + var argCount = arguments.length; + if (argCount === 7) { + _gl.texSubImage2D(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]); + } + else if (argCount === 9) { + _gl.texSubImage2D(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8]); + } + else { + console.log(`texSubImage2DOpt: Wrong number of arguments, expected 7 or 9 but got ${argCount}`); + } +} + +function uniform1fOpt(location, x) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_1F; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + next_index += 3; +} + +function uniform2fOpt(location, x, y) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_2F; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + next_index += 4; +} + +function uniform3fOpt(location, x, y, z) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_3F; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + buffer_data[next_index + 4] = z; + next_index += 5; +} + +function uniform4fOpt(location, x, y, z, w) { + if (next_index + 6 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_4F; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + buffer_data[next_index + 4] = z; + buffer_data[next_index + 5] = w; + next_index += 6; +} + +function uniform1iOpt(location, x) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_1I; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + next_index += 3; +} + +function uniform2iOpt(location, x, y) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_2I; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + next_index += 4; +} + +function uniform3iOpt(location, x, y, z) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_3I; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + buffer_data[next_index + 4] = z; + next_index += 5; +} + +function uniform4iOpt(location, x, y, z, w) { + if (next_index + 6 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_4I; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + buffer_data[next_index + 4] = z; + buffer_data[next_index + 5] = w; + next_index += 6; +} + +function uniform1fvOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_1FV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniform2fvOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_2FV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniform3fvOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_3FV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniform4fvOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_4FV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniform1ivOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_1IV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniform2ivOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_2IV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniform3ivOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_3IV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniform4ivOpt(location, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_4IV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function uniformMatrix2fvOpt(location, transpose, value) { + if (next_index + 4 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_MATRIX_2FV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = transpose; + buffer_data[next_index + 3] = value.length; + buffer_data.set(value, next_index + 4); + next_index += 4 + value.length; +} + +function uniformMatrix3fvOpt(location, transpose, value) { + if (next_index + 4 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_MATRIX_3FV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = transpose; + buffer_data[next_index + 3] = value.length; + buffer_data.set(value, next_index + 4); + next_index += 4 + value.length; +} + +function uniformMatrix4fvOpt(location, transpose, value) { + if (next_index + 4 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_UNIFORM_MATRIX_4FV; + buffer_data[next_index + 1] = location; + buffer_data[next_index + 2] = transpose; + buffer_data[next_index + 3] = value.length; + buffer_data.set(value, next_index + 4); + next_index += 4 + value.length; +} + +function useProgramOpt(program) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_USE_PROGRAM; + buffer_data[next_index + 1] = program ? program._id : 0; + next_index += 2; +} + +function validateProgramOpt(program) { + if (next_index + 2 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VALIDATE_PROGRAM; + buffer_data[next_index + 1] = program ? program._id : 0; + next_index += 2; +} + +function vertexAttrib1fOpt(index, x) { + if (next_index + 3 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_1F; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = x; + next_index += 3; +} + +function vertexAttrib2fOpt(index, x, y) { + if (next_index + 4 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_2F; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + next_index += 4; +} + +function vertexAttrib3fOpt(index, x, y, z) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_3F; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + buffer_data[next_index + 4] = z; + next_index += 5; +} + +function vertexAttrib4fOpt(index, x, y, z, w) { + if (next_index + 6 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_4F; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = x; + buffer_data[next_index + 3] = y; + buffer_data[next_index + 4] = z; + buffer_data[next_index + 5] = w; + next_index += 6; +} + +function vertexAttrib1fvOpt(index, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_1FV; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function vertexAttrib2fvOpt(index, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_2FV; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function vertexAttrib3fvOpt(index, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_3FV; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function vertexAttrib4fvOpt(index, value) { + if (next_index + 3 + value.length >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_4FV; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = value.length; + buffer_data.set(value, next_index + 3); + next_index += 3 + value.length; +} + +function vertexAttribPointerOpt(index, size, type, normalized, stride, offset) { + if (next_index + 7 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VERTEX_ATTRIB_POINTER; + buffer_data[next_index + 1] = index; + buffer_data[next_index + 2] = size; + buffer_data[next_index + 3] = type; + buffer_data[next_index + 4] = normalized ? 1 : 0; + buffer_data[next_index + 5] = stride; + buffer_data[next_index + 6] = offset; + next_index += 7; +} + +function viewportOpt(x, y, width, height) { + if (next_index + 5 >= total_size) { + flushCommands(); + } + buffer_data[next_index] = GL_COMMAND_VIEW_PORT; + buffer_data[next_index + 1] = x; + buffer_data[next_index + 2] = y; + buffer_data[next_index + 3] = width; + buffer_data[next_index + 4] = height; + next_index += 5; +} + +function isSupportTypeArray() { + //FIXME: + // if (GameStatusInfo.platform == 'android') { + return true; + // } + // var info = BK.Director.queryDeviceInfo(); + // var vers = info.version.split('.'); + // if (info.platform == 'ios' && Number(vers[0]) >= 10) { + // return true; + // } + // return false; +} + +function attachMethodOpt() { + gl.activeTexture = activeTextureOpt; + gl.attachShader = attachShaderOpt; + gl.bindAttribLocation = bindAttribLocationOpt; + gl.bindBuffer = bindBufferOpt; + gl.bindFramebuffer = bindFramebufferOpt; + gl.bindRenderbuffer = bindRenderbufferOpt; + gl.bindTexture = bindTextureOpt; + gl.blendColor = blendColorOpt; + gl.blendEquation = blendEquationOpt; + gl.blendEquationSeparate = blendEquationSeparateOpt; + gl.blendFunc = blendFuncOpt; + gl.blendFuncSeparate = blendFuncSeparateOpt; + gl.bufferData = bufferDataOpt; + gl.bufferSubData = bufferSubDataOpt; + gl.checkFramebufferStatus = checkFramebufferStatusOpt; + gl.clear = clearOpt; + gl.clearColor = clearColorOpt; + gl.clearDepth = clearDepthOpt; + gl.clearStencil = clearStencilOpt; + gl.colorMask = colorMaskOpt; + gl.compileShader = compileShaderOpt; + gl.compressedTexImage2D = compressedTexImage2DOpt; + gl.compressedTexSubImage2D = compressedTexSubImage2DOpt; + gl.copyTexImage2D = copyTexImage2DOpt; + gl.copyTexSubImage2D = copyTexSubImage2DOpt; + gl.createBuffer = createBufferOpt; + gl.createFramebuffer = createFramebufferOpt; + gl.createProgram = createProgramOpt; + gl.createRenderbuffer = createRenderbufferOpt; + gl.createShader = createShaderOpt; + gl.createTexture = createTextureOpt; + gl.cullFace = cullFaceOpt; + gl.deleteBuffer = deleteBufferOpt; + gl.deleteFramebuffer = deleteFramebufferOpt; + gl.deleteProgram = deleteProgramOpt; + gl.deleteRenderbuffer = deleteRenderbufferOpt; + gl.deleteShader = deleteShaderOpt; + gl.deleteTexture = deleteTextureOpt; + gl.depthFunc = depthFuncOpt; + gl.depthMask = depthMaskOpt; + gl.depthRange = depthRangeOpt; + gl.detachShader = detachShaderOpt; + gl.disable = disableOpt; + gl.disableVertexAttribArray = disableVertexAttribArrayOpt; + gl.drawArrays = drawArraysOpt; + gl.drawElements = drawElementsOpt; + gl.enable = enableOpt; + gl.enableVertexAttribArray = enableVertexAttribArrayOpt; + gl.finish = finishOpt; + gl.flush = flushOpt; + gl.framebufferRenderbuffer = framebufferRenderbufferOpt; + gl.framebufferTexture2D = framebufferTexture2DOpt; + gl.frontFace = frontFaceOpt; + gl.generateMipmap = generateMipmapOpt; + gl.getActiveAttrib = getActiveAttribOpt; + gl.getActiveUniform = getActiveUniformOpt; + gl.getAttachedShaders = getAttachedShadersOpt; + gl.getAttribLocation = getAttribLocationOpt; + gl.getBufferParameter = getBufferParameterOpt; + gl.getParameter = getParameterOpt; + gl.getError = getErrorOpt; + gl.getFramebufferAttachmentParameter = getFramebufferAttachmentParameterOpt; + gl.getProgramParameter = getProgramParameterOpt; + gl.getProgramInfoLog = getProgramInfoLogOpt; + gl.getRenderbufferParameter = getRenderbufferParameterOpt; + gl.getShaderParameter = getShaderParameterOpt; + gl.getShaderPrecisionFormat = getShaderPrecisionFormatOpt; + gl.getShaderInfoLog = getShaderInfoLogOpt; + gl.getShaderSource = getShaderSourceOpt; + gl.getTexParameter = getTexParameterOpt; + gl.getUniform = getUniformOpt; + gl.getUniformLocation = getUniformLocationOpt; + gl.getVertexAttrib = getVertexAttribOpt; + gl.getVertexAttribOffset = getVertexAttribOffsetOpt; + gl.hint = hintOpt; + gl.isBuffer = isBufferOpt; + gl.isEnabled = isEnabledOpt; + gl.isFramebuffer = isFramebufferOpt; + gl.isProgram = isProgramOpt; + gl.isRenderbuffer = isRenderbufferOpt; + gl.isShader = isShaderOpt; + gl.isTexture = isTextureOpt; + gl.lineWidth = lineWidthOpt; + gl.linkProgram = linkProgramOpt; + gl.pixelStorei = pixelStoreiOpt; + gl.polygonOffset = polygonOffsetOpt; + gl.readPixels = readPixelsOpt; + gl.renderbufferStorage = renderbufferStorageOpt; + gl.sampleCoverage = sampleCoverageOpt; + gl.scissor = scissorOpt; + gl.shaderSource = shaderSourceOpt; + gl.stencilFunc = stencilFuncOpt; + gl.stencilFuncSeparate = stencilFuncSeparateOpt; + gl.stencilMask = stencilMaskOpt; + gl.stencilMaskSeparate = stencilMaskSeparateOpt; + gl.stencilOp = stencilOpOpt; + gl.stencilOpSeparate = stencilOpSeparateOpt; + gl.texImage2D = texImage2DOpt; + gl.texParameterf = texParameterfOpt; + gl.texParameteri = texParameteriOpt; + gl.texSubImage2D = texSubImage2DOpt; + gl.uniform1f = uniform1fOpt; + gl.uniform2f = uniform2fOpt; + gl.uniform3f = uniform3fOpt; + gl.uniform4f = uniform4fOpt; + gl.uniform1i = uniform1iOpt; + gl.uniform2i = uniform2iOpt; + gl.uniform3i = uniform3iOpt; + gl.uniform4i = uniform4iOpt; + gl.uniform1fv = uniform1fvOpt; + gl.uniform2fv = uniform2fvOpt; + gl.uniform3fv = uniform3fvOpt; + gl.uniform4fv = uniform4fvOpt; + gl.uniform1iv = uniform1ivOpt; + gl.uniform2iv = uniform2ivOpt; + gl.uniform3iv = uniform3ivOpt; + gl.uniform4iv = uniform4ivOpt; + gl.uniformMatrix2fv = uniformMatrix2fvOpt; + gl.uniformMatrix3fv = uniformMatrix3fvOpt; + gl.uniformMatrix4fv = uniformMatrix4fvOpt; + gl.useProgram = useProgramOpt; + gl.validateProgram = validateProgramOpt; + gl.vertexAttrib1f = vertexAttrib1fOpt; + gl.vertexAttrib2f = vertexAttrib2fOpt; + gl.vertexAttrib3f = vertexAttrib3fOpt; + gl.vertexAttrib4f = vertexAttrib4fOpt; + gl.vertexAttrib1fv = vertexAttrib1fvOpt; + gl.vertexAttrib2fv = vertexAttrib2fvOpt; + gl.vertexAttrib3fv = vertexAttrib3fvOpt; + gl.vertexAttrib4fv = vertexAttrib4fvOpt; + gl.vertexAttribPointer = vertexAttribPointerOpt; + gl.viewport = viewportOpt; +} + +batchGLCommandsToNative(); + +module.exports = { + disableBatchGLCommandsToNative: disableBatchGLCommandsToNative, + flushCommands: flushCommands +} \ No newline at end of file diff --git a/jsb/builtin/index.js b/jsb/builtin/index.js index b8da5248bc..7453dd8df0 100644 --- a/jsb/builtin/index.js +++ b/jsb/builtin/index.js @@ -24,10 +24,11 @@ ****************************************************************************/ window.CC_JSB = true; -window.CC_WECHATGAME = true; +window.CC_WECHATGAME = true; //FIXME: remove CC_WECHATGAME // Simulate wechat game API: +//FIXME: remove wx window.wx = { getSystemInfoSync() { return { @@ -48,30 +49,61 @@ window.wx = { } } -let oldRequestFrameCallback = null; -let requestAnimationFrameID = 0; -let requestAnimationFrameCallbacks = {}; +window.CanvasRenderingContext2D = cc.CanvasRenderingContext2D; +delete cc.CanvasRenderingContext2D; + +const { btoa, atob } = require('./base64/base64.min'); +window.btoa = btoa; +window.atob = atob; +const { Blob, URL } = require('./Blob'); +window.Blob = Blob; +window.URL = URL; +window.DOMParser = require('./xmldom/dom-parser').DOMParser; + +require('./jsb_prepare'); +require('./jsb_opengl'); +require('./jsb-adapter'); +require('./jsb_audioengine'); + +let _oldRequestFrameCallback = null; +let _requestAnimationFrameID = 0; +let _requestAnimationFrameCallbacks = {}; +let _firstTick = true; window.requestAnimationFrame = function(cb) { - let id = ++requestAnimationFrameID; - requestAnimationFrameCallbacks[id] = cb; + let id = ++_requestAnimationFrameID; + _requestAnimationFrameCallbacks[id] = cb; return id; }; window.cancelAnimationFrame = function(id) { - delete requestAnimationFrameCallbacks[id]; + delete _requestAnimationFrameCallbacks[id]; +}; + +const {disableBatchGLCommandsToNative, flushCommands} = require('./glOptMode'); +window.optConfig = { + disableBatchGLCommandsToNative: disableBatchGLCommandsToNative }; function tick(nowMilliSeconds) { - fireTimeout(nowMilliSeconds); - - for (let id in requestAnimationFrameCallbacks) { - oldRequestFrameCallback = requestAnimationFrameCallbacks[id]; - if (oldRequestFrameCallback) { - delete requestAnimationFrameCallbacks[id]; - oldRequestFrameCallback(nowMilliSeconds); + if (_firstTick) { + _firstTick = false; + if (window.onload) { + var event = new Event('load'); + event._target = window; + window.onload(event); } } + fireTimeout(nowMilliSeconds); + + for (let id in _requestAnimationFrameCallbacks) { + _oldRequestFrameCallback = _requestAnimationFrameCallbacks[id]; + if (_oldRequestFrameCallback) { + delete _requestAnimationFrameCallbacks[id]; + _oldRequestFrameCallback(nowMilliSeconds); + } + } + flushCommands(); } let _timeoutIDIndex = 0; @@ -159,23 +191,8 @@ jsb.fileUtils = cc.fileUtils; delete cc.FileUtils; delete cc.fileUtils; -window.CanvasRenderingContext2D = cc.CanvasRenderingContext2D; -delete cc.CanvasRenderingContext2D; - jsb.urlRegExp = new RegExp("^(?:https?|ftp)://\\S*$", "i"); -require('./jsb_prepare'); -require('./jsb_opengl'); -const { btoa, atob } = require('./base64/base64.min'); -window.btoa = btoa; -window.atob = atob; -const { Blob, URL } = require('./Blob'); -window.Blob = Blob; -window.URL = URL; -window.DOMParser = require('./xmldom/dom-parser').DOMParser; -require('./jsb-adapter'); -require('./jsb_audioengine'); - /** * @type {Object} * @name jsb.reflection diff --git a/jsb/builtin/jsb-adapter/Element.js b/jsb/builtin/jsb-adapter/Element.js index 794eb2fc9d..6c4b19b10d 100755 --- a/jsb/builtin/jsb-adapter/Element.js +++ b/jsb/builtin/jsb-adapter/Element.js @@ -44,7 +44,7 @@ class Element extends Node { } getBoundingClientRect() { - return new DOMRect(); + return new DOMRect(0, 0, window.innerWidth, window.innerHeight); } // attrName is a string that names the attribute to be removed from element. diff --git a/jsb/builtin/jsb-adapter/Event.js b/jsb/builtin/jsb-adapter/Event.js index 54e47e2473..cc15b98e66 100644 --- a/jsb/builtin/jsb-adapter/Event.js +++ b/jsb/builtin/jsb-adapter/Event.js @@ -37,7 +37,7 @@ class Event { constructor(type, eventInit) { this._type = type - this._eventTarget = null + this._target = null this._eventPhase = 2 this._currentTarget = null this._canceled = false @@ -59,7 +59,7 @@ class Event { * @type {EventTarget} */ get target() { - return this._eventTarget + return this._target } /** diff --git a/jsb/builtin/jsb-adapter/EventTarget.js b/jsb/builtin/jsb-adapter/EventTarget.js index f4895ca5a7..84ac5929c4 100644 --- a/jsb/builtin/jsb-adapter/EventTarget.js +++ b/jsb/builtin/jsb-adapter/EventTarget.js @@ -152,15 +152,29 @@ EventTarget.prototype = { throw new TypeError("\"event.type\" should be a string.") } + const eventName = event.type + var onFunc = this['on' + eventName]; + if (onFunc && typeof onFunc === 'function') { + event._target = event._currentTarget = this; + onFunc.call(this, event); + event._target = event._currentTarget = null + event._eventPhase = 0 + event._passiveListener = null + + if (event.defaultPrevented) + return false; + } + // If listeners aren't registered, terminate. const listeners = this._listeners - const eventName = event.type + let node = listeners.get(eventName) if (!node) { return true } event._target = event._currentTarget = this; + // This doesn't process capturing phase and bubbling phase. // This isn't participating in a tree. let prev = null @@ -186,9 +200,6 @@ EventTarget.prototype = { if (typeof node.listener === "function") { node.listener.call(this, event) } - else if (node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function") { - node.listener.handleEvent(event) - } // Break if `event.stopImmediatePropagation` was called. if (event._stopped) { diff --git a/jsb/builtin/jsb-adapter/FileReader.js b/jsb/builtin/jsb-adapter/FileReader.js index dabc8b7f44..ba99710ac1 100755 --- a/jsb/builtin/jsb-adapter/FileReader.js +++ b/jsb/builtin/jsb-adapter/FileReader.js @@ -42,7 +42,8 @@ class FileReader extends EventTarget { // Starts reading the contents of the specified Blob, once finished, the result attribute contains a data: URL representing the file's data. readAsDataURL(blob) { this.result = 'data:image/png;base64,' + window.btoa(blob); - this.onload(); + var event = new Event('load'); + this.dispatchEvent(event); } // Starts reading the contents of the specified Blob, once finished, the result attribute contains the contents of the file as a text string. diff --git a/jsb/builtin/jsb-adapter/HTMLCanvasElement.js b/jsb/builtin/jsb-adapter/HTMLCanvasElement.js index 4d38c2b827..4f1c040159 100644 --- a/jsb/builtin/jsb-adapter/HTMLCanvasElement.js +++ b/jsb/builtin/jsb-adapter/HTMLCanvasElement.js @@ -218,8 +218,8 @@ class HTMLCanvasElement extends HTMLElement { this.top = 0; this.left = 0; - this._width = width ? width : window.innerWidth; - this._height = height ? height : window.innerHeight; + this._width = width ? Math.ceil(width) : 1; + this._height = height ? Math.ceil(height) : 1; this._context2D = null; this._data = null; } @@ -227,15 +227,14 @@ class HTMLCanvasElement extends HTMLElement { //TODO: implement opts. getContext(name, opts) { var self = this; - console.log(`==> Canvas getContext(${name})`); + // console.log(`==> Canvas getContext(${name})`); if (name === 'webgl' || name === 'experimental-webgl') { - return window.gl; + return window.__gl; } else if (name === '2d') { if (!this._context2D) { this._context2D = new CanvasRenderingContext2D(this._width, this._height); this._context2D._canvas = this; - this._context2D.setCanvasBufferUpdatedCallback(function(data) { - console.log('setCanvasBufferUpdatedCallback: dataLen: ' + data.length); + this._context2D._setCanvasBufferUpdatedCallback(function(data) { self._data = new ImageData(data, self._width, self._height); }); } @@ -251,7 +250,8 @@ class HTMLCanvasElement extends HTMLElement { } set width(width) { - console.log(`==> HTMLCanvasElement.width = ${width}`); + width = Math.ceil(width); + // console.log(`==> HTMLCanvasElement.width = ${width}`); if (this._width !== width) { this._width = width; if (this._context2D) { @@ -265,7 +265,8 @@ class HTMLCanvasElement extends HTMLElement { } set height(height) { - console.log(`==> HTMLCanvasElement.height = ${height}`); + height = Math.ceil(height); + // console.log(`==> HTMLCanvasElement.height = ${height}`); if (this._height !== height) { this._height = height; if (this._context2D) { @@ -340,7 +341,7 @@ function touchEventHandlerFactory(type) { const touchEvent = new TouchEvent(type) touchEvent.touches = touches; - // touchEvent.targetTouches = Array.prototype.slice.call(event.touches) + touchEvent.targetTouches = Array.prototype.slice.call(touchEvent.touches) touchEvent.changedTouches = touches;//event.changedTouches // touchEvent.timeStamp = event.timeStamp diff --git a/jsb/builtin/jsb-adapter/HTMLImageElement.js b/jsb/builtin/jsb-adapter/HTMLImageElement.js index c04f3fb6e2..a6fef85f98 100755 --- a/jsb/builtin/jsb-adapter/HTMLImageElement.js +++ b/jsb/builtin/jsb-adapter/HTMLImageElement.js @@ -25,6 +25,7 @@ const HTMLElement = require('./HTMLElement'); const Event = require('./Event'); +const gl = window.__gl; class HTMLImageElement extends HTMLElement { constructor(width, height) { @@ -32,7 +33,6 @@ class HTMLImageElement extends HTMLElement { this.width = width; this.height = height; this._data = null; - this.onload = null; this._src = null; this.complete = false; this._glFormat = this._glInternalFormat = gl.RGBA; @@ -67,11 +67,8 @@ class HTMLImageElement extends HTMLElement { this.complete = true; - this.dispatchEvent(new Event('load')); - - if (this.onload) { - this.onload(); - } + var event = new Event('load'); + this.dispatchEvent(event); }); } diff --git a/jsb/builtin/jsb-adapter/HTMLVideoElement.js b/jsb/builtin/jsb-adapter/HTMLVideoElement.js new file mode 100644 index 0000000000..fd511e49a8 --- /dev/null +++ b/jsb/builtin/jsb-adapter/HTMLVideoElement.js @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + 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. + Xiamen Yaji Software Co., Ltd. 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. + ****************************************************************************/ + +let HTMLMediaElement = require('./HTMLMediaElement'); + +class HTMLVideoElement extends HTMLMediaElement { + constructor() { + super('video') + } +} + +module.exports = HTMLVideoElement; diff --git a/jsb/builtin/jsb-adapter/document.js b/jsb/builtin/jsb-adapter/document.js index 917907eaee..6c6d3faf90 100755 --- a/jsb/builtin/jsb-adapter/document.js +++ b/jsb/builtin/jsb-adapter/document.js @@ -23,12 +23,13 @@ THE SOFTWARE. ****************************************************************************/ -let HTMLElement = require('./HTMLElement'); -let Image = require('./Image'); -let Audio = require('./Audio'); -let HTMLCanvasElement = require('./HTMLCanvasElement'); -let Node = require('./Node'); -let FontFaceSet = require('./FontFaceSet') +const HTMLElement = require('./HTMLElement'); +const Image = require('./Image'); +const Audio = require('./Audio'); +const HTMLCanvasElement = require('./HTMLCanvasElement'); +const HTMLVideoElement = require('./HTMLVideoElement'); +const Node = require('./Node'); +const FontFaceSet = require('./FontFaceSet') class Document extends Node { @@ -61,21 +62,17 @@ class Document extends Node { } else if (tagName === 'img') { return new Image() } else if (tagName === 'video') { - return { - canPlayType: () => { - return false; - } - }; + return new HTMLVideoElement(); } return new HTMLElement(tagName) } getElementById(id) { - if (id === window.canvas.id) { + if (id === window.canvas.id || id === 'canvas') { return window.canvas } - return null + return new HTMLElement(id); } getElementsByTagName(tagName) { @@ -86,7 +83,7 @@ class Document extends Node { } else if (tagName === 'canvas') { return [window.canvas] } - return [] + return [new HTMLElement(tagName)] } getElementsByName(tagName) { @@ -97,7 +94,7 @@ class Document extends Node { } else if (tagName === 'canvas') { return [window.canvas] } - return [] + return [new HTMLElement(tagName)] } querySelector(query) { @@ -110,7 +107,7 @@ class Document extends Node { } else if (query === `#${window.canvas.id}`) { return window.canvas } - return null + return new HTMLElement(query); } querySelectorAll(query) { @@ -121,7 +118,7 @@ class Document extends Node { } else if (query === 'canvas') { return [window.canvas] } - return [] + return [new HTMLElement(query)]; } createTextNode() { diff --git a/jsb/builtin/jsb-adapter/location.js b/jsb/builtin/jsb-adapter/location.js index 1c67c7c269..d262037ef2 100755 --- a/jsb/builtin/jsb-adapter/location.js +++ b/jsb/builtin/jsb-adapter/location.js @@ -24,10 +24,12 @@ ****************************************************************************/ const location = { - href: 'game.js', - hash: '', - reload() { - } + href: 'game.js', + pathname: 'game.js', + search: '', + hash: '', + reload() { + } } module.exports = location; diff --git a/jsb/builtin/jsb-adapter/navigator.js b/jsb/builtin/jsb-adapter/navigator.js index 1179322c62..0b5a70a490 100755 --- a/jsb/builtin/jsb-adapter/navigator.js +++ b/jsb/builtin/jsb-adapter/navigator.js @@ -31,7 +31,7 @@ const navigator = { platform: 'wx', //cjh added wx language: 'zh-cn', appVersion: '5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1', - userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 MicroMessenger/6.6.0 MiniGame NetType/WIFI Language/zh_CN', + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E8301 NetType/WIFI Language/zh_CN', onLine: true, // TODO 用 wx.getNetworkStateChange 和 wx.onNetworkStateChange 来返回真实的状态 // TODO 用 wx.getLocation 来封装 geolocation diff --git a/jsb/builtin/jsb-adapter/window.js b/jsb/builtin/jsb-adapter/window.js index 84e266c4e1..1ee0a594e2 100755 --- a/jsb/builtin/jsb-adapter/window.js +++ b/jsb/builtin/jsb-adapter/window.js @@ -41,9 +41,9 @@ function inject () { window.HTMLImageElement = require('./HTMLImageElement'); window.HTMLMediaElement = require('./HTMLMediaElement'); window.HTMLAudioElement = require('./HTMLAudioElement'); + window.HTMLVideoElement = require('./HTMLVideoElement'); window.canvas = new HTMLCanvasElement(); - window.gl.canvas = window.canvas; - window.WebGLRenderingContext = window.gl; + window.__gl.canvas = window.canvas; window.navigator = require('./navigator'); window.Image = require('./Image'); window.Audio = require('./Audio'); @@ -74,15 +74,15 @@ function inject () { window.addEventListener = function(eventName, listener, options) { window.canvas.addEventListener(eventName, listener, options); - } + }; window.removeEventListener = function(eventName, listener, options) { window.canvas.removeEventListener(eventName, listener, options); - } + }; window.dispatchEvent = function(event) { window.canvas.dispatchEvent(event); - } + }; window.getComputedStyle = function(element) { return { @@ -91,7 +91,9 @@ function inject () { top: '0px', height: '0px' }; - } + }; + + window.focus = function() {}; window._isInjected = true; } diff --git a/jsb/builtin/jsb_opengl.js b/jsb/builtin/jsb_opengl.js index 222cba9147..394c01d3dc 100644 --- a/jsb/builtin/jsb_opengl.js +++ b/jsb/builtin/jsb_opengl.js @@ -28,391 +28,12 @@ */ require('./jsb_opengl_constants'); -window.gl = window.gl || {}; + +const gl = __gl; gl.drawingBufferWidth = window.innerWidth; gl.drawingBufferHeight = window.innerHeight; -// -// Create functions -// -gl.createTexture = function() { - // Returns a "WebGLTexture" object - var ret = gl._createTexture(); - return { texture_id:ret }; -}; - -gl.createBuffer = function() { - // Returns a "WebGLBuffer" object - var ret = gl._createBuffer(); - return { buffer_id:ret }; -}; - -gl.createRenderbuffer = function() { - // Returns a "WebGLRenderBuffer" object - var ret = gl._createRenderbuffer(); - return { renderbuffer_id:ret}; -}; - -gl.createFramebuffer = function() { - // Returns a "WebGLFramebuffer" object - var ret = gl._createFramebuffer(); - return {framebuffer_id:ret}; -}; - -gl.createProgram = function() { - // Returns a "WebGLProgram" object - var ret = gl._createProgram(); - return {program_id:ret}; -}; - -gl.createShader = function(shaderType) { - // Returns a "WebGLShader" object - var ret = gl._createShader(shaderType); - return {shader_id:ret}; -}; - -// -// Delete Functions -// -gl.deleteTexture = function(texture) { - var texture_id = texture.texture_id; - // Accept numbers too. eg: gl.deleteTexture(0) - if (typeof texture === 'number') - texture_id = texture; - - gl._deleteTexture(texture_id); -}; - -gl.deleteBuffer = function(buffer) { - var buffer_id = buffer.buffer_id; - // Accept numbers too. eg: gl.deleteBuffer(0) - if( typeof buffer === 'number' ) - buffer_id = buffer; - - gl._deleteBuffer(buffer_id); -}; - -gl.deleteRenderbuffer = function(buffer) { - var buffer_id = buffer.renderbuffer_id; - // Accept numbers too. eg: gl.deleteRenderbuffer(0) - if (typeof buffer === 'number') - buffer_id = buffer; - - gl._deleteRenderbuffer(renderbuffer_id); -}; - -gl.deleteFramebuffer = function(buffer) { - var buffer_id; - if (buffer) - buffer_id = buffer.framebuffer_id; - else - buffer_id = null; - gl._deleteFramebuffer(buffer_id); -}; - -gl.deleteProgram = function(program) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.deleteShader(0) - if (typeof program === 'number') - program_id = program; - - gl._deleteProgram(program_id); -}; - -gl.deleteShader = function(shader) { - var shader_id = shader.shader_id; - // Accept numbers too. eg: gl.deleteShader(0) - if (typeof shader === 'number') - shader_id = shader; - - gl._deleteShader(shader_id); -}; - -// -// Bind Related -// -// void bindTexture(GLenum target, WebGLTexture? texture); -gl.bindTexture = function(target, texture) { - - var texture_id; - // Accept numbers too. eg: gl.bindTexture(0) - if (typeof texture === 'number') - texture_id = texture; - else if( texture === null ) - texture_id = 0; - else - texture_id = texture.texture_id; - - gl._bindTexture( target, texture_id ); -}; - -// void bindBuffer(GLenum target, WebGLBuffer? buffer); -gl.bindBuffer = function(target, buffer) { - var buffer_id; - // Accept numbers too. eg: gl.bindBuffer(0) - if (typeof buffer === 'number') - buffer_id = buffer; - else if (buffer === null) - buffer_id = 0; - else - buffer_id = buffer.buffer_id; - - gl._bindBuffer(target, buffer_id); -}; - -// void bindRenderbuffer(GLenum target, WebGLRenderbuffer? renderbuffer); -gl.bindRenderbuffer = function(target, buffer) { - var buffer_id; - - // Accept numbers too. eg: gl.bindRenderbuffer(0) - if (typeof buffer === 'number') - buffer_id = buffer; - else if (buffer === null) - buffer_id = 0; - else - buffer_id = buffer.renderbuffer_id; - - gl._bindRenderbuffer(target, buffer_id); -}; - -// void bindFramebuffer(GLenum target, WebGLFramebuffer? framebuffer); -gl.bindFramebuffer = function(target, buffer) { - var buffer_id; - - // Accept numbers too. eg: gl.bindFramebuffer(0) - if (typeof buffer === 'number') - buffer_id = buffer; - else if( buffer === null ) - buffer_id = null; - else - buffer_id = buffer.framebuffer_id; - - gl._bindFramebuffer(target, buffer_id); -}; - -gl.framebufferRenderbuffer = function(target, attachment, renderbuffertarget, renderbuffer) { - gl._framebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer.renderbuffer_id); -}; - -gl.framebufferTexture2D = function(target, attachment, textarget, texture, level) { - gl._framebufferTexture2D(target, attachment, textarget, texture.texture_id, level); -}; - -gl.isFramebuffer = function(buffer) { - if (buffer && buffer.framebuffer_id) { - return gl._isFramebuffer(buffer.framebuffer_id); - } - return false; -}; - -gl.isProgram = function(program) { - if (program && program.program_id) { - return gl._isProgram(program.program_id); - } - return false; -}; - -gl.isRenderbuffer = function(buffer) { - if (buffer && buffer.renderbuffer_id) { - return gl._isRenderbuffer(buffer.renderbuffer_id); - } - return false; -}; - -gl.isShader = function(shader) { - if (shader && shader.shader_id) { - return gl._isShader(shader.shader_id); - } - return false; -}; - -gl.isTexture = function(texture) { - if (texture && texture.texture_id) { - return gl._isTexture(texture.texture_id); - } - return false; -}; - -// -// Uniform related -// -// any getUniform(WebGLProgram? program, WebGLUniformLocation? location); -gl.getUniform = function(program, location) { - var program_id; - var location_id; - - // Accept numbers too. eg: gl.bindFramebuffer(0) - if (typeof program === 'number') - program_id = program; - else - program_id = program.program_id; - - if (typeof location === 'number') - location_id = location; - else - location_id = location.location_id; - - return gl._getUniform(program_id, location_id); -}; - -// gl.uniformMatrix2fv = function(location, bool, matrix) { -// gl._uniformMatrix2fv(program.program_id, bool, matrix); -// }; - -// gl.uniformMatrix3fv = function(program, bool, matrix) { -// gl._uniformMatrix3fv(program.program_id, bool, matrix); -// }; - -// gl.uniformMatrix4fv = function(program, bool, matrix) { -// gl._uniformMatrix4fv(program.program_id, bool, matrix); -// }; - - -// -// Shader related -// -// void compileShader(WebGLShader? shader); -gl.compileShader = function(shader) { - gl._compileShader( shader.shader_id); -}; - -// void shaderSource(WebGLShader? shader, DOMString source); -gl.shaderSource = function(shader, source) { - gl._shaderSource(shader.shader_id, source); -}; - -// any getShaderParameter(WebGLShader? shader, GLenum pname); -gl.getShaderParameter = function(shader, e) { - return gl._getShaderParameter(shader.shader_id,e); -}; - -// DOMString? getShaderInfoLog(WebGLShader? shader); -gl.getShaderInfoLog = function(shader) { - return gl._getShaderInfoLog(shader.shader_id); -}; - -// DOMString gl.getShaderSource(shader); -gl.getShaderSource = function(shader) { - return gl._getShaderSource(shader.shader_id); -}; - -// -// program related -// -// void attachShader(WebGLProgram? program, WebGLShader? shader); -gl.attachShader = function(program, shader) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.attachShader(17) - if( typeof program === 'number' ) - program_id = program; - - gl._attachShader(program_id, shader.shader_id); -}; - -// void linkProgram(WebGLProgram? program); -gl.linkProgram = function(program) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.linkProgram(17) - if( typeof program === 'number' ) - program_id = program; - - gl._linkProgram(program_id); -}; - -gl.bindAttribLocation = function(program, index, name) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.linkProgram(17) - if( typeof program === 'number' ) - program_id = program; - - gl._bindAttribLocation(program_id, index, name); -}; - -// any getProgramParameter(WebGLProgram? program, GLenum pname); -gl.getProgramParameter = function(program, e) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.getProgramParameter(17) - if (typeof program === 'number') - program_id = program; - - return gl._getProgramParameter(program_id, e); -}; - -gl.getProgramInfoLog = function(program) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.getProgramParameter(17) - if (typeof program === 'number') - program_id = program; - - return gl._getProgramInfoLog(program_id); -}; - -// void useProgram(WebGLProgram? program); -gl.useProgram = function(program) { - var program_id; - // Accept numbers too. eg: gl.useProgram(17) - if (typeof program === 'number') - program_id = program; - else - program_id = program.program_id; - - gl._useProgram (program_id); -}; - - -// [WebGLHandlesContextLoss] GLint getAttribLocation(WebGLProgram? program, DOMString name); -gl.getAttribLocation = function(program, name) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.getAttribLocation(17) - if (typeof program === 'number') - program_id = program; - - return gl._getAttribLocation(program_id, name); -}; - -// WebGLUniformLocation? getUniformLocation(WebGLProgram? program, DOMString name); -gl.getUniformLocation = function(program, name) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.getUniformLocation(17) - if (typeof program === 'number') - program_id = program; - - // XXX: it should return an object, not an integer - return gl._getUniformLocation(program_id,name); -}; - - -// WebGLActiveInfo? getActiveAttrib(WebGLProgram? program, GLuint index); -gl.getActiveAttrib = function(program, index) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.getActiveAttrib(17) - if (typeof program === 'number') - program_id = program; - - return gl._getActiveAttrib(program_id, index); -}; - -// WebGLActiveInfo? getActiveUniform(WebGLProgram? program, GLuint index); -gl.getActiveUniform = function(program, index) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.getActiveUniform(17) - if (typeof program === 'number') - program_id = program; - - return gl._getActiveUniform(program_id, index); -}; - -// sequence? getAttachedShaders(WebGLProgram? program); -gl.getAttachedShaders = function(program) { - var program_id = program.program_id; - // Accept numbers too. eg: gl.getAttachedShaders(17) - if (typeof program === 'number') - program_id = program; - - return gl._getAttachedShaders(program_id); -}; - // // Extensions // @@ -447,24 +68,23 @@ void gl.texImage2D(target, level, internalformat, format, type, ImageBitmap? pix gl.texImage2D = function(target, level, internalformat, width, height, border, format, type, pixels) { let argCount = arguments.length; if (argCount == 6) { + var image = border; type = height; format = width; if (image instanceof HTMLImageElement) { - // console.log(`==> texImage2D HTMLImageElement internalformat: ${image._glInternalFormat}, format: ${image._glFormat}, image: w:${image.width}, h:${image.height}, dataLen:${image._data.length}`); gl.pixelStorei(gl.UNPACK_ALIGNMENT, image._alignment); - _glTexImage2D(target, level, image._glInternalFormat, image.width, image.height, 0, image._glFormat, image._glType, image._data); } else if (image instanceof HTMLCanvasElement) { - // console.log(`==> texImage2D HTMLCanvasElement internalformat: ${internalformat}, format: ${format}, image: w:${image.width}, h:${image.height}`);//, dataLen:${image._data.length}`); + var data = null; if (image._data) { - _glTexImage2D(target, level, internalformat, image.width, image.height, 0, format, type, image._data._data); + data = image._data._data; } + _glTexImage2D(target, level, internalformat, image.width, image.height, 0, format, type, data); } else if (image instanceof ImageData) { - // console.log(`==> texImage2D ImageData internalformat: ${internalformat}, format: ${format}, image: w:${image.width}, h:${image.height}`); _glTexImage2D(target, level, internalformat, image.width, image.height, 0, format, type, image._data); } else { @@ -473,7 +93,8 @@ gl.texImage2D = function(target, level, internalformat, width, height, border, f } else if (argCount == 9) { _glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); - } else { + } + else { console.error("gl.texImage2D: invalid argument count!"); } } @@ -496,15 +117,16 @@ gl.texSubImage2D = function(target, level, xoffset, yoffset, width, height, form type = height; format = width; - //TODO: ImageData if (image instanceof HTMLImageElement) { gl.pixelStorei(gl.UNPACK_ALIGNMENT, image._alignment); _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, image._glFormat, image._glType, image._data); } else if (image instanceof HTMLCanvasElement) { + var data = null; if (image._data) { - _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, format, type, image._data._data); + data = image._data._data; } + _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, format, type, data); } else if (image instanceof ImageData) { _glTexSubImage2D(target, level, xoffset, yoffset, image.width, image.height, format, type, image._data); @@ -515,7 +137,8 @@ gl.texSubImage2D = function(target, level, xoffset, yoffset, width, height, form } else if (argCount == 9) { _glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); - } else { + } + else { console.error((new Error("gl.texImage2D: invalid argument count!").stack)); } } diff --git a/jsb/builtin/jsb_opengl_constants.js b/jsb/builtin/jsb_opengl_constants.js index b0675ddc16..a9735a0c8c 100644 --- a/jsb/builtin/jsb_opengl_constants.js +++ b/jsb/builtin/jsb_opengl_constants.js @@ -23,13 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -/* -* AUTOGENERATED FILE. DO NOT EDIT IT -* Generated by "generate_jsb.py -c opengl_jsb.ini" on 2013-03-18 -* Script version: v0.6 -*/ - -window.gl = window.gl || {}; +const gl = __gl; gl.GCCSO_SHADER_BINARY_FJ = 0x9260; gl._3DC_XY_AMD = 0x87fa; diff --git a/jsb/config.js b/jsb/config.js new file mode 100644 index 0000000000..92ec7d144d --- /dev/null +++ b/jsb/config.js @@ -0,0 +1,39 @@ +let _stageOffset = 0; +let _name2stageID = {}; + +var config = { + addStage: function (name) { + // already added + if (_name2stageID[name] !== undefined) { + return; + } + + let stageID = 1 << _stageOffset; + _name2stageID[name] = stageID; + + _stageOffset += 1; + + renderer.addStage(name); + }, + + stageID: function (name) { + let id = _name2stageID[name]; + if (id === undefined) { + return -1; + } + return id; + }, + + stageIDs: function (nameList) { + let key = 0; + for (let i = 0; i < nameList.length; ++i) { + let id = _name2stageID[nameList[i]]; + if (id !== undefined) { + key |= id; + } + } + return key; + } +}; + +module.exports = config; \ No newline at end of file diff --git a/jsb/effect.js b/jsb/effect.js new file mode 100644 index 0000000000..9a57d898e3 --- /dev/null +++ b/jsb/effect.js @@ -0,0 +1,89 @@ +let config = renderer.config; + +class Effect { + /** + * @param {Array} techniques + */ + constructor(techniques, properties = {}, defines = []) { + this._techniques = techniques; + this._properties = properties; + this._defines = defines; + + var techniqueObjs = []; + var techniqueObj; + for (var i = 0, len = techniques.length; i < len; ++i) { + techniqueObj = techniques[i]._nativeObj; + techniqueObjs.push(techniqueObj); + } + + this._nativeObj = new renderer.EffectNative(techniqueObjs, properties, defines); + this._nativePtr = this._nativeObj.self(); + + // TODO: check if params is valid for current technique??? + } + + clear() { + this._techniques.length = 0; + this._properties = null; + this._defines.length = 0; + } + + getTechnique(stage) { + let stageID = config.stageID(stage); + for (let i = 0; i < this._techniques.length; ++i) { + let tech = this._techniques[i]; + if (tech.stageIDs & stageID) { + return tech; + } + } + + return null; + } + + getProperty(name) { + return this._properties[name]; + } + + setProperty(name, value) { + // TODO: check if params is valid for current technique??? + this._properties[name] = value; + this._nativeObj.setProperty(name, value); + } + + getDefine(name) { + for (let i = 0; i < this._defines.length; ++i) { + let def = this._defines[i]; + if ( def.name === name ) { + return def.value; + } + } + + console.warn(`Failed to get define ${name}, define not found.`); + return null; + } + + define(name, value) { + for (let i = 0; i < this._defines.length; ++i) { + let def = this._defines[i]; + if ( def.name === name ) { + def.value = value; + return; + } + } + + this._nativeObj.setDefine(name, value); + + console.warn(`Failed to set define ${name}, define not found.`); + } + + extractDefines(out = {}) { + for (let i = 0; i < this._defines.length; ++i) { + let def = this._defines[i]; + out[def.name] = def.value; + } + + return out; + } +} + +module.exports = Effect; diff --git a/jsb/gfx.js b/jsb/gfx.js index 37fb392ecc..320c1a8652 100644 --- a/jsb/gfx.js +++ b/jsb/gfx.js @@ -49,13 +49,15 @@ _p._ctor = function(device, options) { _p = gfx.VertexBuffer.prototype; _p._ctor = function(device, format, usage, data, numVertices) { - this.init(device, format, usage, data, numVertices); + this.init(device, format._nativeObj, usage, data, numVertices); + this._nativePtr = this.self(); }; cc.defineGetterSetter(_p, "count", _p.getCount); _p = gfx.IndexBuffer.prototype; _p._ctor = function(device, format, usage, data, numIndices) { this.init(device, format, usage, data, numIndices); + this._nativePtr = this.self(); }; cc.defineGetterSetter(_p, "count", _p.getCount); diff --git a/jsb/index.js b/jsb/index.js index b1c7f029ed..61e8012370 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -22,8 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -require('./gfx'); -require('./renderer'); + +if (CC_NATIVERENDERER) { + require('./gfx'); + require('./renderer'); +} require('../index') require('./jsb-audio') require('./jsb-loader') diff --git a/jsb/input-assembler.js b/jsb/input-assembler.js new file mode 100644 index 0000000000..865178062e --- /dev/null +++ b/jsb/input-assembler.js @@ -0,0 +1,26 @@ +class InputAssembler { + constructor(vb, ib, pt = gfx.PT_TRIANGLES) { + this._vertexBuffer = vb; + this._indexBuffer = ib; + this._primitiveType = pt; + this._start = 0; + this._count = -1; + + // TODO: instancing data + // this._stream = 0; + } + + getPrimitiveCount () { + if (this._count !== -1) { + return this._count; + } + + if (this._indexBuffer) { + return this._indexBuffer.count; + } + + return this._vertexBuffer.count; + } +} + +module.exports = InputAssembler; \ No newline at end of file diff --git a/jsb/model.js b/jsb/model.js new file mode 100644 index 0000000000..5423ea5034 --- /dev/null +++ b/jsb/model.js @@ -0,0 +1,101 @@ +class Model { + constructor() { + this._poolID = -1; + this._node = null; + this._inputAssemblers = []; + this._effects = []; + this._defines = []; + this._dynamicIA = false; + this._viewID = -1; + + // TODO: we calculate aabb based on vertices + // this._aabb + } + + get inputAssemblerCount() { + return this._inputAssemblers.length; + } + + get dynamicIA() { + return this._dynamicIA; + } + + get drawItemCount() { + return this._dynamicIA ? 1 : this._inputAssemblers.length; + } + + setNode(node) { + this._node = node; + } + + setDynamicIA(enabled) { + this._dynamicIA = enabled; + } + + addInputAssembler(ia) { + if (this._inputAssemblers.indexOf(ia) !== -1) { + return; + } + this._inputAssemblers.push(ia); + } + + clearInputAssemblers() { + this._inputAssemblers.length = 0; + } + + addEffect(effect) { + if (this._effects.indexOf(effect) !== -1) { + return; + } + this._effects.push(effect); + + // + // let defs = Object.create(null); + // effect.extractDefines(defs); + // this._defines.push(defs); + } + + clearEffects() { + this._effects.length = 0; + this._defines.length = 0; + } + + extractDrawItem(out, index) { + if (this._dynamicIA) { + out.model = this; + out.node = this._node; + out.ia = null; + out.effect = this._effects[0]; + out.defines = out.effect.extractDefines(this._defines[0]); + + return; + } + + if (index >= this._inputAssemblers.length ) { + out.model = null; + out.node = null; + out.ia = null; + out.effect = null; + out.defines = null; + + return; + } + + out.model = this; + out.node = this._node; + out.ia = this._inputAssemblers[index]; + + let effect, defines; + if (index < this._effects.length) { + effect = this._effects[index]; + defines = this._defines[index]; + } else { + effect = this._effects[this._effects.length-1]; + defines = this._defines[this._effects.length-1]; + } + out.effect = effect; + out.defines = effect.extractDefines(defines); + } +} + +module.exports = Model; diff --git a/jsb/pass.js b/jsb/pass.js new file mode 100644 index 0000000000..8c77aae1c6 --- /dev/null +++ b/jsb/pass.js @@ -0,0 +1,175 @@ +class Pass { + constructor(name) { + this._programName = name; + + // cullmode + this._cullMode = gfx.CULL_BACK; + + // blending + this._blend = false; + this._blendEq = gfx.BLEND_FUNC_ADD; + this._blendAlphaEq = gfx.BLEND_FUNC_ADD; + this._blendSrc = gfx.BLEND_ONE; + this._blendDst = gfx.BLEND_ZERO; + this._blendSrcAlpha = gfx.BLEND_ONE; + this._blendDstAlpha = gfx.BLEND_ZERO; + this._blendColor = 0xffffffff; + + // depth + this._depthTest = false; + this._depthWrite = false; + this._depthFunc = gfx.DS_FUNC_LESS, + + // stencil + this._stencilTest = false; + // front + this._stencilFuncFront = gfx.DS_FUNC_ALWAYS; + this._stencilRefFront = 0; + this._stencilMaskFront = 0xff; + this._stencilFailOpFront = gfx.STENCIL_OP_KEEP; + this._stencilZFailOpFront = gfx.STENCIL_OP_KEEP; + this._stencilZPassOpFront = gfx.STENCIL_OP_KEEP; + this._stencilWriteMaskFront = 0xff; + // back + this._stencilFuncBack = gfx.DS_FUNC_ALWAYS; + this._stencilRefBack = 0; + this._stencilMaskBack = 0xff; + this._stencilFailOpBack = gfx.STENCIL_OP_KEEP; + this._stencilZFailOpBack = gfx.STENCIL_OP_KEEP; + this._stencilZPassOpBack = gfx.STENCIL_OP_KEEP; + this._stencilWriteMaskBack = 0xff; + + this._binary = new Uint32Array(25); + this._updateBinary(); + } + + setCullMode(cullMode) { + this._cullMode = cullMode; + this._binary[0] = cullMode; + } + + setBlend( + blendEq = gfx.BLEND_FUNC_ADD, + blendSrc = gfx.BLEND_ONE, + blendDst = gfx.BLEND_ZERO, + blendAlphaEq = gfx.BLEND_FUNC_ADD, + blendSrcAlpha = gfx.BLEND_ONE, + blendDstAlpha = gfx.BLEND_ZERO, + blendColor = 0xffffffff + ) { + this._blend = true; + this._blendEq = blendEq; + this._blendSrc = blendSrc; + this._blendDst = blendDst; + this._blendAlphaEq = blendAlphaEq; + this._blendSrcAlpha = blendSrcAlpha; + this._blendDstAlpha = blendDstAlpha; + this._blendColor = blendColor; + + this._binary[1] = this._blendEq; + this._binary[2] = this._blendSrc; + this._binary[3] = this._blendDst; + this._binary[4] = this._blendAlphaEq; + this._binary[5] = this._blendSrcAlpha; + this._binary[6] = this._blendDstAlpha; + this._binary[7] = this._blendColor; + } + + setDepth( + depthTest = false, + depthWrite = false, + depthFunc = gfx.DS_FUNC_LESS + ) { + this._depthTest = depthTest; + this._depthWrite = depthWrite; + this._depthFunc = depthFunc; + + this._binary[8] = this._depthTest; + this._binary[9] = this._depthWrite; + this._binary[10] = this._depthFunc; + } + + setStencilFront( + stencilFunc = gfx.DS_FUNC_ALWAYS, + stencilRef = 0, + stencilMask = 0xff, + stencilFailOp = gfx.STENCIL_OP_KEEP, + stencilZFailOp = gfx.STENCIL_OP_KEEP, + stencilZPassOp = gfx.STENCIL_OP_KEEP, + stencilWriteMask = 0xff + ) { + this._stencilTest = true; + this._stencilFuncFront = stencilFunc; + this._stencilRefFront = stencilRef; + this._stencilMaskFront = stencilMask; + this._stencilFailOpFront = stencilFailOp; + this._stencilZFailOpFront = stencilZFailOp; + this._stencilZPassOpFront = stencilZPassOp; + this._stencilWriteMaskFront = stencilWriteMask; + + this._binary[11] = this._stencilFuncFront; + this._binary[12] = this._stencilRefFront; + this._binary[13] = this._stencilMaskFront; + this._binary[14] = this._stencilFailOpFront; + this._binary[15] = this._stencilZFailOpFront; + this._binary[16] = this._stencilZPassOpFront; + this._binary[17] = this._stencilWriteMaskFront; + } + + setStencilBack( + stencilFunc = gfx.DS_FUNC_ALWAYS, + stencilRef = 0, + stencilMask = 0xff, + stencilFailOp = gfx.STENCIL_OP_KEEP, + stencilZFailOp = gfx.STENCIL_OP_KEEP, + stencilZPassOp = gfx.STENCIL_OP_KEEP, + stencilWriteMask = 0xff + ) { + this._stencilTest = true; + this._stencilFuncBack = stencilFunc; + this._stencilRefBack = stencilRef; + this._stencilMaskBack = stencilMask; + this._stencilFailOpBack = stencilFailOp; + this._stencilZFailOpBack = stencilZFailOp; + this._stencilZPassOpBack = stencilZPassOp; + this._stencilWriteMaskBack = stencilWriteMask; + + this._binary[18] = this._stencilFuncBack; + this._binary[19] = this._stencilRefBack; + this._binary[20] = this._stencilMaskBack; + this._binary[21] = this._stencilFailOpBack; + this._binary[22] = this._stencilZFailOpBack; + this._binary[23] = this._stencilZPassOpBack; + this._binary[24] = this._stencilWriteMaskBack; + } + + _updateBinary() { + this._binary[0] = this._cullMode; + this._binary[1] = this._blendEq; + this._binary[2] = this._blendSrc; + this._binary[3] = this._blendDst; + this._binary[4] = this._blendAlphaEq; + this._binary[5] = this._blendSrcAlpha; + this._binary[6] = this._blendDstAlpha; + this._binary[7] = this._blendColor; + this._binary[8] = this._depthTest; + this._binary[9] = this._depthWrite; + this._binary[10] = this._depthFunc; + this._binary[11] = this._stencilFuncFront; + this._binary[12] = this._stencilRefFront; + this._binary[13] = this._stencilMaskFront; + this._binary[14] = this._stencilFailOpFront; + this._binary[15] = this._stencilZFailOpFront; + this._binary[16] = this._stencilZPassOpFront; + this._binary[17] = this._stencilWriteMaskFront; + this._binary[18] = this._stencilFuncBack; + this._binary[19] = this._stencilRefBack; + this._binary[20] = this._stencilMaskBack; + this._binary[21] = this._stencilFailOpBack; + this._binary[22] = this._stencilZFailOpBack; + this._binary[23] = this._stencilZPassOpBack; + this._binary[24] = this._stencilWriteMaskBack; + } +} + +module.exports = Pass; diff --git a/jsb/renderer.js b/jsb/renderer.js index f6a1cc77e6..a0a566ce13 100644 --- a/jsb/renderer.js +++ b/jsb/renderer.js @@ -22,7 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - + +const utils = require('./utils'); + // projection renderer.PROJ_PERSPECTIVE = 0; renderer.PROJ_ORTHO = 1; @@ -58,27 +60,65 @@ renderer.PARAM_TEXTURE_CUBE = 14; renderer.CLEAR_COLOR = 1; renderer.CLEAR_DEPTH = 2; renderer.CLEAR_STENCIL = 4; +renderer.InputAssembler = require('./input-assembler'); +renderer.config = require('./config'); +renderer.Effect = require('./Effect'); +renderer.Technique = require('./Technique'); +renderer.Pass = require('./Pass'); +renderer.Model = require('./Model'); -renderer.addStage = renderer.Config.addStage; +var models = []; +var sizeOfModel = 23; +// length + 500 modles(8 for each model) +var modlesData = new Float64Array(1 + 500*sizeOfModel); +var fillModelData = function() { + if (models.length > 500) + modlesData = new FloatArray64(1 + models.length*sizeOfModel); + + modlesData[0] = models.length; + var index = 1; + var model; + var worldMatrix; + var ia; + for (var i = 0, len = models.length; i < len; ++i) { + model = models[i]; + modlesData[index++] = model._dynamicIA; + modlesData[index++] = model._viewID; + worldMatrix = utils.getWorldRTInAB(model._node); + modlesData.set(worldMatrix, index); + index += 16; + + // ia + ia = model._inputAssemblers[0]; + modlesData[index++] = ia._vertexBuffer._nativePtr; + modlesData[index++] = ia._indexBuffer._nativePtr; + modlesData[index++] = ia._start; + modlesData[index++] = ia._count; + + // effect + modlesData[index++] = model._effects[0]._nativePtr; + } +} // ForwardRenderer adapter var _p; _p = renderer.ForwardRenderer.prototype; _p._ctor = function(device, builtin) { - this.init(device, builtin.programTemplates, builtin.defaultTexture, canvas.width, canvas.height); + this.init(device, builtin.programTemplates, builtin.defaultTexture, canvas.width, canvas.height); }; +_p.render = function(scene) { + fillModelData(); + this.renderNative(scene, modlesData); -// InputAssembler adapter -_p = renderer.InputAssembler.prototype; -_p._ctor = function(vb, ib, pt = gfx.PT_TRIANGLES) { - this.init(vb, ib, pt); -}; + models.length = 0; +} -cc.defineGetterSetter(_p, "_vertexBuffer", _p.getVertexBuffer, _p.setVertexBuffer); -cc.defineGetterSetter(_p, "_indexBuffer", _p.getIndexBuffer, _p.setIndexBuffer); -cc.defineGetterSetter(_p, "_primitiveType", _p.getPrimitiveType, _p.setPrimitiveType); -cc.defineGetterSetter(_p, "_start", _p.getStart, _p.setStart); -cc.defineGetterSetter(_p, "_count", _p.getCount, _p.setCount); +// Scene +_p = renderer.Scene.prototype; +_p.addModel = function(model) { + models.push(model); +} +_p.removeModel = function() {} diff --git a/jsb/technique.js b/jsb/technique.js new file mode 100644 index 0000000000..7a2672c0a8 --- /dev/null +++ b/jsb/technique.js @@ -0,0 +1,43 @@ +let config = renderer.config; + +let _genID = 0; + +class Technique { + /** + * @param {Array} stages + * @param {Array} parameters + * @param {Array} passes + * @param {Number} layer + */ + constructor(stages, parameters, passes, layer = 0) { + this._id = _genID++; + this._stageIDs = config.stageIDs(stages); + this.stageIDs = this._stageIDs; + this._parameters = parameters; // {name, type, size, val} + this._passes = passes; + this.passes = this._passes; + this._layer = layer; + this._stages = stages; + // TODO: this._version = 'webgl' or 'webgl2' // ???? + + this._nativeObj = new renderer.TechniqueNative(stages, parameters, passes, layer); + + } + + setStages(stages) { + this._stageIDs = config.stageIDs(stages); + this._stages = stages; + + this._nativeObj.setStages(stages); + } + + // get passes() { + // return this._passes; + // } + + // get stageIDs() { + // return this._stageIDs; + // } +} + +module.exports = Technique; \ No newline at end of file diff --git a/jsb/utils.js b/jsb/utils.js new file mode 100644 index 0000000000..f1a4407a64 --- /dev/null +++ b/jsb/utils.js @@ -0,0 +1,65 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + 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. + Xiamen Yaji Software Co., Ltd. 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. + ****************************************************************************/ +'use strict'; + +let _typedArray_temp = new Float32Array(16); +var _mat4_temp = cc.vmath.mat4.create(); + +function _mat4ToArray(typedArray, mat4) { + typedArray[0] = mat4.m00; + typedArray[1] = mat4.m01; + typedArray[2] = mat4.m02; + typedArray[3] = mat4.m03; + typedArray[4] = mat4.m04; + typedArray[5] = mat4.m05; + typedArray[6] = mat4.m06; + typedArray[7] = mat4.m07; + typedArray[8] = mat4.m08; + typedArray[9] = mat4.m09; + typedArray[10] = mat4.m10; + typedArray[11] = mat4.m11; + typedArray[12] = mat4.m12; + typedArray[13] = mat4.m13; + typedArray[14] = mat4.m14; + typedArray[15] = mat4.m15; +} + +function getWorldRTInAB (node) { + node.getWorldRT(_mat4_temp); + _mat4ToArray(_typedArray_temp, _mat4_temp); + return _typedArray_temp; +} + +function getWorldMatrixInAB (node) { + node._updateWorldMatrix(); + _mat4ToArray(_typedArray_temp, node._worldMatrix); + return _typedArray_temp; +} + +module.exports = { + getWorldRTInAB, + getWorldMatrixInAB +} \ No newline at end of file diff --git a/jsb/vertex-format-jsb.js b/jsb/vertex-format-jsb.js index d61910f4e5..62448b01ea 100644 --- a/jsb/vertex-format-jsb.js +++ b/jsb/vertex-format-jsb.js @@ -72,6 +72,8 @@ class VertexFormat { let el = this._elements[i]; el.stride = this._bytes; } + + this._nativeObj = new gfx.VertexFormatNative(this._elements); } /**