diff --git a/cocos2d/core/renderer/assemblers/spine-assembler.js b/cocos2d/core/renderer/assemblers/spine-assembler.js new file mode 100644 index 0000000000..d8f19fb123 --- /dev/null +++ b/cocos2d/core/renderer/assemblers/spine-assembler.js @@ -0,0 +1,350 @@ +/**************************************************************************** + Copyright (c) 2017-2018 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +const js = require('../../platform/js'); +const assembler = require('./assembler'); +const Skeleton = require('../../../../extensions/spine/skeleton'); +const spine = require('../../../../extensions/spine/lib/spine'); +const renderer = require('../'); +const renderEngine = require('../render-engine'); +const gfx = renderEngine.gfx; +const SpriteMaterial = renderEngine.SpriteMaterial; +const RenderData = renderEngine.RenderData; + +let _sharedMaterials = {}; + +function _getSlotMaterial (slot, tex, premultiAlpha) { + let src, dst; + switch (slot.data.blendMode) { + case spine.BlendMode.Additive: + src = premultiAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; + dst = cc.macro.ONE; + break; + case spine.BlendMode.Multiply: + src = cc.macro.DST_COLOR; + dst = cc.macro.ONE_MINUS_SRC_ALPHA; + break; + case spine.BlendMode.Screen: + src = cc.macro.ONE; + dst = cc.macro.ONE_MINUS_SRC_COLOR; + break; + case spine.BlendMode.Normal: + default: + src = premultiAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; + dst = cc.macro.ONE_MINUS_SRC_ALPHA; + break; + } + let key = tex.url + src + dst; + let material = _sharedMaterials[key]; + if (!material) { + material = new SpriteMaterial(); + material.useModel = true; + // update texture + let renderTex = tex.getImpl(); + material.texture = tex.getImpl(); + // update blend function + let pass = material._mainTech.passes[0]; + pass.setBlend( + gfx.BLEND_FUNC_ADD, + src, dst, + gfx.BLEND_FUNC_ADD, + src, dst + ); + _sharedMaterials[key] = material; + } + return material; +} + +var spineAssembler = js.addon({ + // Use model to avoid per vertex transform + useModel: true, + + _readRegionAttachmentData (comp, attachment, slot, premultipliedAlpha, data, dataOffset) { + + // if (this._node._debugSlots) { + // // return the quad points info if debug slot enabled + // var VERTEX = spine.RegionAttachment; + // return [ + // cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]), + // cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]), + // cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]), + // cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]) + // ]; + // } + }, + + _readAttachmentData (comp, attachment, slot, premultipliedAlpha, renderData, dataOffset) { + // the vertices in format: + // X1, Y1, C1R, C1G, C1B, C1A, U1, V1 + // get the vertex data + let vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + let vertexCount = vertices.length / 8; + // augment render data size to ensure capacity + renderData.dataLength += vertexCount; + let data = renderData._data; + let nodeColor = comp.node._color; + let nodeR = nodeColor.r, + nodeG = nodeColor.g, + nodeB = nodeColor.b, + nodeA = comp.node._opacity; + for (var i = 0, n = vertices.length; i < n; i += 8) { + let r = vertices[i + 2] * nodeR, + g = vertices[i + 3] * nodeG, + b = vertices[i + 4] * nodeB, + a = vertices[i + 5] * nodeA; + let color = ((a<<24) >>> 0) + (b<<16) + (g<<8) + r; + let content = data[dataOffset]; + content.x = vertices[i]; + content.y = vertices[i + 1]; + content.color = color; + content.u = vertices[i + 6]; + content.v = vertices[i + 7]; + dataOffset++; + } + + return vertexCount; + }, + + genRenderDatas (comp, batchData) { + let locSkeleton = comp._skeleton; + let premultiAlpha = comp.premultipliedAlpha; + + let debugSlotsInfo = null; + if (comp.debugSlots) { + debugSlotsInfo = []; + } + + let attachment, slot; + let dataId = 0, datas = comp._renderDatas, data = datas[dataId], newData = false; + if (!data) { + data = datas[dataId] = RenderData.alloc(); + } + data.dataLength = 0; + let indices; + let material = null, currEffect = null, effect = null; + let vertexCount = 0, vertexOffset = 0, maxVertex = batchData.MAX_VERTEX - batchData.vertexOffset; + let indiceCount = 0, indiceOffset = 0, maxIndice = batchData.MAX_INDICE - batchData.indiceOffset; + for (let i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { + slot = locSkeleton.drawOrder[i]; + if (!slot.attachment) + continue; + attachment = slot.attachment; + + // get the vertices length + vertexCount = 0; + if (attachment instanceof spine.RegionAttachment) { + vertexCount = 4; + indiceCount = 6; + } + else if (attachment instanceof spine.MeshAttachment) { + vertexCount = attachment.regionUVs.length / 2; + indiceCount = attachment.triangles.length; + } + else { + continue; + } + + // no vertices to render + if (vertexCount === 0) { + continue; + } + + newData = false; + material = _getSlotMaterial(slot, attachment.region.texture._texture, premultiAlpha); + effect = material.effect; + // Check break + if (currEffect !== effect) { + if (currEffect) { + newData = true; + } + data.effect = currEffect = effect; + } + if (vertexOffset + vertexCount > maxVertex || indiceOffset + vertexCount > maxIndice) { + currEffect = null; + newData = true; + } + + // Request new render data and new vertex content + if (newData) { + // set old data vertex indice + data.vertexCount = vertexOffset; + data.indiceCount = indiceOffset; + // gen new data + dataId++; + if (!datas[dataId]) { + data = datas[dataId] = RenderData.alloc(); + } + data.dataLength = vertexCount; + data.effect = currEffect; + // reset offset + vertexOffset = 0; + indiceOffset = 0; + // reset max because initial max is depending on batchData.vertexOffset & indiceOffset + maxVertex = batchData.MAX_VERTEX; + maxIndice = batchData.MAX_INDICE; + } + + // Fill up indices + if (attachment instanceof spine.RegionAttachment) { + indices = data._indices; + indices[indiceOffset] = vertexOffset; + indices[indiceOffset + 1] = vertexOffset + 1; + indices[indiceOffset + 2] = vertexOffset + 2; + indices[indiceOffset + 3] = vertexOffset + 0; + indices[indiceOffset + 4] = vertexOffset + 2; + indices[indiceOffset + 5] = vertexOffset + 3; + } else { + let triangles = attachment.triangles; + for (let t = 0; t < triangles.length; t++) { + indices[indiceOffset + t] = vertexOffset + triangles[t]; + } + } + indiceOffset += indiceCount; + // Fill up vertex render data + vertexOffset += this._readAttachmentData(comp, attachment, slot, premultiAlpha, data, vertexOffset); + + // if (this._node._debugSlots) { + // debugSlotsInfo[i] = slotDebugPoints; + // } + } + + data.vertexCount = vertexOffset; + data.indiceCount = indiceOffset; + datas.length = dataId + 1; + + // if (node._debugBones || node._debugSlots) { + // // flush previous vertices + // cc.renderer._batchRendering(); + + // var wt = this._worldTransform, mat = this._matrix.mat; + // mat[0] = wt.a; + // mat[4] = wt.c; + // mat[12] = wt.tx; + // mat[1] = wt.b; + // mat[5] = wt.d; + // mat[13] = wt.ty; + + // cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW); + // //cc.math.glPushMatrixWitMat4(this._matrix); + // cc.current_stack.stack.push(cc.current_stack.top); + // cc.current_stack.top = this._matrix; + // var drawingUtil = cc._drawingUtil; + + // if (node._debugSlots && debugSlotsInfo && debugSlotsInfo.length > 0) { + // // Slots. + // drawingUtil.setDrawColor(0, 0, 255, 255); + // drawingUtil.setLineWidth(1); + + // for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + // var points = debugSlotsInfo[i]; + // if (points) { + // drawingUtil.drawPoly(points, 4, true); + // } + // } + // } + + // if (node._debugBones) { + // // Bone lengths. + // var bone; + // drawingUtil.setLineWidth(2); + // drawingUtil.setDrawColor(255, 0, 0, 255); + + // for (i = 0, n = locSkeleton.bones.length; i < n; i++) { + // bone = locSkeleton.bones[i]; + // var x = bone.data.length * bone.a + bone.worldX; + // var y = bone.data.length * bone.c + bone.worldY; + // drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y)); + // } + + // // Bone origins. + // drawingUtil.setPointSize(4); + // drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. + + // for (i = 0, n = locSkeleton.bones.length; i < n; i++) { + // bone = locSkeleton.bones[i]; + // drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY)); + // if (i == 0) { + // drawingUtil.setDrawColor(0, 255, 0, 255); + // } + // } + // } + // cc.math.glPopMatrix(); + // } + }, + + updateRenderData (comp, batchData) { + let skeleton = comp._skeleton; + let state = comp._state; + if (skeleton) { + let dt = cc.director.getDeltaTime(); + skeleton.update(dt); + + if (state) { + dt *= comp._timeScale; + state.update(dt); + state.apply(skeleton); + } + + skeleton.updateWorldTransform(); + this.genRenderDatas(comp, batchData); + } + else { + comp._renderDatas.length = 0; + } + + return comp._renderDatas; + }, + + fillBuffers (batchData, vertexId, vbuf, uintbuf, ibuf) { + let data = batchData.data; + let vertexs = data._data; + let indices = data._indices; + let z = batchData.comp.node._position.z; + + // fill vertex buffer + let offset = batchData.vertexOffset * batchData.comp._vertexFormat._bytes / 4; + let vert; + for (let i = 0, l = data.dataLength; i < l; i++) { + vert = vertexs[i]; + vbuf[offset + 0] = vert.x; + vbuf[offset + 1] = vert.y; + vbuf[offset + 2] = z; + vbuf[offset + 4] = vert.u; + vbuf[offset + 5] = vert.v; + uintbuf[offset + 3] = vert.color; + offset += 6; + } + + // index buffer + offset = batchData.indiceOffset; + for (let i = 0, l = indices.length; i < l; i ++) { + ibuf[offset++] = vertexId + indices[i]; + } + } +}, assembler); + +Skeleton._assembler = spineAssembler; + +module.exports = spineAssembler; \ No newline at end of file diff --git a/extensions/spine/SGSkeleton.js b/extensions/spine/SGSkeleton.js deleted file mode 100644 index 52b6dcd57a..0000000000 --- a/extensions/spine/SGSkeleton.js +++ /dev/null @@ -1,340 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2014 Shengxiang Chen (Nero Chan) - Copyright (c) 2015-2016 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -var spine = sp.spine; - -sp._SGSkeleton = _ccsg.Node.extend({ - _skeleton: null, - _rootBone: null, - _timeScale: 1, - _debugSlots: false, - _debugBones: false, - _premultipliedAlpha: false, - _ownsSkeletonData: null, - _atlas: null, - - ctor: function(skeletonDataFile, atlasFile, scale) { - _ccsg.Node.prototype.ctor.call(this); - - if(arguments.length === 0) - this.init(); - else - this.initWithArgs(skeletonDataFile, atlasFile, scale); - }, - - _createRenderCmd: function () { - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new sp._SGSkeleton.CanvasRenderCmd(this); - else - return new sp._SGSkeleton.WebGLRenderCmd(this); - }, - - init: function () { - _ccsg.Node.prototype.init.call(this); - this._premultipliedAlpha = (cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA); - this.scheduleUpdate(); - }, - - /** - * Sets whether open debug slots. - * @param {boolean} enabled true to open, false to close. - */ - setDebugSlotsEnabled: function(enabled) { - this._debugSlots = enabled; - }, - - /** - * Gets whether open debug slots. - * @returns {boolean} true to open, false to close. - */ - getDebugSlotsEnabled: function() { - return this._debugSlots; - }, - - /** - * Sets whether open debug bones. - * @param {boolean} enabled - */ - setDebugBonesEnabled: function(enabled) { - this._debugBones = enabled; - }, - - /** - * Gets whether open debug bones. - * @returns {boolean} true to open, false to close. - */ - getDebugBonesEnabled: function() { - return this._debugBones; - }, - - /** - * Sets the time scale of sp._SGSkeleton. - * @param {Number} scale - */ - setTimeScale:function(scale){ - this._timeScale = scale; - }, - - getTimeScale: function(){ - return this._timeScale; - }, - - /** - * Initializes sp._SGSkeleton with Data. - * @param {sp.spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - */ - initWithArgs: function (skeletonDataFile, atlasFile, scale) { - var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, - skeletonData, atlas, ownsSkeletonData; - - if (cc.js.isString(argSkeletonFile)) { - if (cc.js.isString(argAtlasFile)) { - var data = cc.loader.getRes(argAtlasFile); - sp._atlasLoader.setAtlasFile(argAtlasFile); - atlas = new spine.TextureAtlas(data, sp._atlasLoader.load.bind(sp._atlasLoader)); - } else { - atlas = atlasFile; - } - scale = scale || 1 / cc.director.getContentScaleFactor(); - - var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); - var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); - skeletonJsonReader.scale = scale; - - var skeletonJson = cc.loader.getRes(argSkeletonFile); - skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); - atlas.dispose(skeletonJsonReader); - ownsSkeletonData = true; - } else { - skeletonData = skeletonDataFile; - ownsSkeletonData = atlasFile; - } - this.setSkeletonData(skeletonData, ownsSkeletonData); - this.init(); - }, - - /** - * Returns the bounding box of sp._SGSkeleton. - * @returns {Rect} - */ - getBoundingBox: function () { - var minX = cc.macro.FLT_MAX, minY = cc.macro.FLT_MAX, maxX = cc.macro.FLT_MIN, maxY = cc.macro.FLT_MIN; - var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices, - slots = this._skeleton.slots, VERTEX = spine.RegionAttachment; - - for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { - var slot = slots[i]; - var attachment = slot.attachment; - if (!attachment || !(attachment instanceof spine.RegionAttachment)) - continue; - vertices = attachment.updateWorldVertices(slot, false); - minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); - maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); - } - var position = this.getPosition(); - return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); - }, - - /** - * Computes the world SRT from the local SRT for each bone. - */ - updateWorldTransform: function () { - this._skeleton.updateWorldTransform(); - }, - - /** - * Sets the bones and slots to the setup pose. - */ - setToSetupPose: function () { - this._skeleton.setToSetupPose(); - }, - - /** - * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. - */ - setBonesToSetupPose: function () { - this._skeleton.setBonesToSetupPose(); - }, - - /** - * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. - */ - setSlotsToSetupPose: function () { - this._skeleton.setSlotsToSetupPose(); - }, - - /** - * Finds a bone by name. This does a string comparison for every bone.
- * Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Bone object. - * @param {String} boneName - * @returns {sp.spine.Bone} - */ - findBone: function (boneName) { - return this._skeleton.findBone(boneName); - }, - - /** - * Finds a slot by name. This does a string comparison for every slot.
- * Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Slot object. - * - * @param {String} slotName - * @returns {sp.spine.Slot} - */ - findSlot: function (slotName) { - return this._skeleton.findSlot(slotName); - }, - - /** - * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible.
- * Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Skin object. - * - * @param {string} skinName - * @returns {sp.spine.Skin} - */ - setSkin: function (skinName) { - return this._skeleton.setSkinByName(skinName); - }, - - /** - * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin.
- * Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.Attachment object. - * - * @param {String} slotName - * @param {String} attachmentName - * @returns {sp.spine.Attachment} - */ - getAttachment: function (slotName, attachmentName) { - return this._skeleton.getAttachmentByName(slotName, attachmentName); - }, - - /** - * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - */ - setAttachment: function (slotName, attachmentName) { - this._skeleton.setAttachment(slotName, attachmentName); - }, - - /** - * Sets the premultiplied alpha value to sp._SGSkeleton. - * @param {Number} alpha - */ - setPremultipliedAlpha: function (premultiplied) { - this._premultipliedAlpha = premultiplied; - }, - - /** - * Returns whether to enable premultiplied alpha. - * @returns {boolean} - */ - isPremultipliedAlpha: function () { - return this._premultipliedAlpha; - }, - - /** - * Sets skeleton data to sp._SGSkeleton. - * @param {sp.spine.SkeletonData} skeletonData - * @param {sp.spine.SkeletonData} ownsSkeletonData - */ - setSkeletonData: function (skeletonData, ownsSkeletonData) { - if(skeletonData.width != null && skeletonData.height != null) - this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); - - this._skeleton = new spine.Skeleton(skeletonData); - this._skeleton.updateWorldTransform(); - this._rootBone = this._skeleton.getRootBone(); - this._ownsSkeletonData = ownsSkeletonData; - - this._renderCmd._createChildFormSkeletonData(); - }, - - /** - * Return the renderer of attachment. - * @param {sp.spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment - * @returns {sp.spine.TextureAtlasRegion} - */ - getTextureAtlas: function (regionAttachment) { - return regionAttachment.region; - }, - - /** - * Returns the blendFunc of sp._SGSkeleton, actually it's the first slot's blend function. - * @returns {BlendFunc} - */ - getBlendFunc: function () { - var slot = this._skeleton.drawOrder[0]; - if (slot) { - var blend = this._renderCmd._getBlendFunc(slot.data.blendMode, this._premultipliedAlpha); - return blend; - } - else { - return {}; - } - }, - - /** - * Sets the blendFunc of sp._SGSkeleton, it won't have any effect for skeleton, skeleton is using slot's data to determine the blend function. - * @param {BlendFunc|Number} src - * @param {Number} [dst] - */ - setBlendFunc: function (src, dst) { - return; - }, - - /** - * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". - * @param {Number} dt Delta time since last update - */ - update: function (dt) { - this._skeleton.update(dt); - } -}); - - -// fireball#2856 - -var proto = sp._SGSkeleton.prototype; -Object.defineProperty(proto, 'opacityModifyRGB', { - get: proto.isOpacityModifyRGB -}); - -// For renderer webgl to identify skeleton's default blend function -Object.defineProperty(proto, '_blendFunc', { - get: proto.getBlendFunc -}); - -// For renderer webgl to identify skeleton's default texture -Object.defineProperty(proto, '_texture', { - get: function () { - return this._renderCmd._currTexture; - } -}); \ No newline at end of file diff --git a/extensions/spine/SGSkeletonAnimation.js b/extensions/spine/SGSkeletonAnimation.js deleted file mode 100644 index 718e94904b..0000000000 --- a/extensions/spine/SGSkeletonAnimation.js +++ /dev/null @@ -1,322 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2014 Shengxiang Chen (Nero Chan) - Copyright (c) 2015-2016 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -var spine = sp.spine; -var animEventType = sp.AnimationEventType; - -sp._atlasLoader = { - spAtlasFile:null, - setAtlasFile:function(spAtlasFile){ - this.spAtlasFile = spAtlasFile; - }, - load:function(line){ - var texturePath = cc.path.join(cc.path.dirname(this.spAtlasFile), line); - var texture = cc.textureCache.addImage(texturePath); - var tex = new sp.SkeletonTexture({ width: texture.width, height: texture.height }); - tex.setRealTexture(texture); - return tex; - }, - unload:function(obj){ - } -}; - - -sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener, interruptListener, disposeListener){ - this.startListener = startListener || null; - this.endListener = endListener || null; - this.completeListener = completeListener || null; - this.eventListener = eventListener || null; - this.interruptListener = interruptListener || null; - this.disposeListener = disposeListener || null; - this.callback = null; - this.callbackTarget = null; - this.skeletonNode = null; -}; - -var proto = sp.TrackEntryListeners.prototype; -proto.start = function(trackEntry) { - if (this.startListener) { - this.startListener(trackEntry); - } - if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.START, null, 0); - } -}; - -proto.interrupt = function(trackEntry) { - if (this.interruptListener) { - this.interruptListener(trackEntry); - } - if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.INTERRUPT, null, 0); - } -}; - -proto.end = function (trackEntry) { - if (this.endListener) { - this.endListener(trackEntry); - } - if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.END, null, 0); - } -}; - -proto.dispose = function (trackEntry) { - if (this.disposeListener) { - this.disposeListener(trackEntry); - } - if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.DISPOSE, null, 0); - } -}; - -proto.complete = function (trackEntry) { - var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); - if (this.completeListener) { - this.completeListener(trackEntry, loopCount); - } - if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.COMPLETE, null, loopCount); - } -}; - -proto.event = function (trackEntry, event) { - if (this.eventListener) { - this.eventListener(trackEntry, event); - } - if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.EVENT, event, 0); - } -}; - -sp.TrackEntryListeners.getListeners = function(entry){ - if(!entry.listener){ - entry.listener = new sp.TrackEntryListeners(); - } - return entry.listener; -}; - -sp._SGSkeletonAnimation = sp._SGSkeleton.extend({ - _state: null, - - _ownsAnimationStateData: false, - _listener: null, - - /** - * Initializes a sp._SGSkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. - * @override - */ - init: function () { - sp._SGSkeleton.prototype.init.call(this); - this._ownsAnimationStateData = true; - this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); - }, - - /** - * Sets animation state data to sp._SGSkeletonAnimation. - * @param {sp.spine.AnimationStateData} stateData - */ - setAnimationStateData: function (stateData) { - var state = new spine.AnimationState(stateData); - this._listener = new sp.TrackEntryListeners(); - state.rendererObject = this; - state.addListener(this._listener); - this._state = state; - }, - - /** - * Mix applies all keyframe values, interpolated for the specified time and mixed with the current values.
- * @param {String} fromAnimation - * @param {String} toAnimation - * @param {Number} duration - */ - setMix: function (fromAnimation, toAnimation, duration) { - this._state.data.setMixWith(fromAnimation, toAnimation, duration); - }, - - /** - * Sets event listener of sp._SGSkeletonAnimation. - * @param {Object} target - * @param {Function} callback - */ - setAnimationListener: function (target, callback) { - this._listener.callbackTarget = target; - this._listener.callback = callback; - this._listener.skeletonNode = this; - }, - - /** - * Set the current animation. Any queued animations are cleared. - * @param {Number} trackIndex - * @param {String} name - * @param {Boolean} loop - * @returns {sp.spine.TrackEntry|null} - */ - setAnimation: function (trackIndex, name, loop) { - var animation = this._skeleton.data.findAnimation(name); - if (!animation) { - cc.logID(7509, name); - return null; - } - return this._state.setAnimationWith(trackIndex, animation, loop); - }, - - /** - * Adds an animation to be played delay seconds after the current or last queued animation. - * @param {Number} trackIndex - * @param {String} name - * @param {Boolean} loop - * @param {Number} [delay=0] - * @returns {sp.spine.TrackEntry|null} - */ - addAnimation: function (trackIndex, name, loop, delay) { - delay = delay == null ? 0 : delay; - var animation = this._skeleton.data.findAnimation(name); - if (!animation) { - cc.logID(7510, name); - return null; - } - return this._state.addAnimationWith(trackIndex, animation, loop, delay); - }, - - /** - * Find animation with specified name - * @param {String} name - * @returns {sp.spine.Animation|null} - */ - findAnimation: function (name) { - return this._skeleton.data.findAnimation(name); - }, - - /** - * Returns track entry by trackIndex. - * @param trackIndex - * @returns {sp.spine.TrackEntry|null} - */ - getCurrent: function (trackIndex) { - return this._state.getCurrent(trackIndex); - }, - - /** - * Clears all tracks of animation state. - */ - clearTracks: function () { - this._state.clearTracks(); - }, - - /** - * Clears track of animation state by trackIndex. - * @param {Number} trackIndex - */ - clearTrack: function (trackIndex) { - this._state.clearTrack(trackIndex); - }, - - /** - * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". - * It updates animation's state and skeleton's world transform. - * @param {Number} dt Delta time since last update - * @override - */ - update: function (dt) { - this._super(dt); - dt *= this._timeScale; - this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); - this._state.update(dt); - this._state.apply(this._skeleton); - this._skeleton.updateWorldTransform(); - this._renderCmd._updateChild(); - }, - - /** - * Set the start event listener. - * @param {function} listener - */ - setStartListener: function(listener){ - this._listener.startListener = listener; - }, - - /** - * Set the interrupt listener - * @param {function} listener - */ - setInterruptListener: function(listener) { - this._listener.interruptListener = listener; - }, - - /** - * Set the end event listener. - * @param {function} listener - */ - setEndListener: function(listener) { - this._listener.endListener = listener; - }, - - /** - * Set the dispose listener - * @param {function} listener - */ - setDisposeListener: function(listener) { - this._listener.disposeListener = listener; - }, - - setCompleteListener: function(listener) { - this._listener.completeListener = listener; - }, - - setEventListener: function(listener){ - this._listener.eventListener = listener; - }, - - setTrackStartListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).startListener = listener; - }, - - setTrackInterruptListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).interruptListener = listener; - }, - - setTrackEndListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).endListener = listener; - }, - - setTrackDisposeListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).disposeListener = listener; - }, - - setTrackCompleteListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).completeListener = listener; - }, - - setTrackEventListener: function(entry, listener){ - sp.TrackEntryListeners.getListeners(entry).eventListener = listener; - }, - - getState: function(){ - return this._state; - } -}); diff --git a/extensions/spine/SGSkeletonCanvasRenderCmd.js b/extensions/spine/SGSkeletonCanvasRenderCmd.js deleted file mode 100644 index 41c1ed6074..0000000000 --- a/extensions/spine/SGSkeletonCanvasRenderCmd.js +++ /dev/null @@ -1,233 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -var spine = sp.spine; - -sp._SGSkeleton.CanvasRenderCmd = function(renderableObject){ - this._rootCtor(renderableObject); - this._needDraw = true; -}; - -var proto = sp._SGSkeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); -proto.constructor = sp._SGSkeleton.CanvasRenderCmd; - -proto.rendering = function (wrapper, scaleX, scaleY) { - var node = this._node, i, n, slot, slotNode; - wrapper = wrapper || cc._renderContext; - - var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder; - for(i = 0, n = drawOrder.length; i < n; i++){ - slot = drawOrder[i]; - slotNode = slot._slotNode; - if(slotNode._visible && slotNode._renderCmd && slot.currentSprite){ - slotNode._renderCmd.transform(this, true); - slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY); - slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0; - } - } - - if (!node._debugSlots && !node._debugBones) - return; - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.setGlobalAlpha(1); - var attachment, drawingUtil = cc._drawingUtil; - if (node._debugSlots) { - // Slots. - drawingUtil.setDrawColor(0, 0, 255, 255); - drawingUtil.setLineWidth(1); - - var points = []; - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment || !(slot.attachment instanceof spine.RegionAttachment)) - continue; - attachment = slot.attachment; - this._updateRegionAttachmentSlot(attachment, slot, points); - drawingUtil.drawPoly(points, 4, true); - } - } - - if (node._debugBones) { - // Bone lengths. - var bone; - drawingUtil.setLineWidth(2); - drawingUtil.setDrawColor(255, 0, 0, 255); - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.a + bone.worldX; - var y = bone.data.length * bone.c + bone.worldY; - drawingUtil.drawLine( - {x: bone.worldX, y: bone.worldY}, - {x: x, y: y}); - } - - // Bone origins. - drawingUtil.setPointSize(4); - drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY}); - if (i === 0) - drawingUtil.setDrawColor(0, 255, 0, 255); - } - } -}; - -proto.updateStatus = function() { - this.originUpdateStatus(); - this._updateCurrentRegions(); - this._regionFlag = _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble; - this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.contentDirty; -}; - -proto.getLocalBB = function() { - return this._node.getBoundingBox(); -}; - -proto._updateRegionAttachmentSlot = function(attachment, slot, points) { - if(!points) - return; - - var vertices = attachment.updateWorldVertices(slot, false); - var VERTEX = spine.RegionAttachment; - points.length = 0; - points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); - points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); - points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3])); - points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); -}; - -proto._createChildFormSkeletonData = function(){ - var node = this._node; - var locSkeleton = node._skeleton, spriteName, sprite; - for (var i = 0, n = locSkeleton.slots.length; i < n; i++) { - var slot = locSkeleton.slots[i], attachment = slot.attachment; - var slotNode = new _ccsg.Node(); - slot._slotNode = slotNode; - - if(attachment instanceof spine.RegionAttachment){ - spriteName = attachment.region.name; - sprite = this._createSprite(slot, attachment); - slot.currentSprite = sprite; - slot.currentSpriteName = spriteName; - slotNode.addChild(sprite); - } else if(attachment instanceof spine.MeshAttachment){ - //todo for mesh - } - } -}; - -proto._createSprite = function(slot, attachment){ - var rendererObject = attachment.region; - var texture = rendererObject.texture.getRealTexture(); - var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height); - var sprite = new _ccsg.Sprite(); - sprite.initWithTexture(texture, rect, rendererObject.rotate, false); - sprite._rect.width = attachment.width; - sprite._rect.height = attachment.height; - sprite.setContentSize(attachment.width, attachment.height); - sprite.setRotation(-attachment.rotation); - sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX, - rendererObject.height / rendererObject.originalHeight * attachment.scaleY); - - slot.sprites = slot.sprites || {}; - slot.sprites[rendererObject.name] = sprite; - - return sprite; -}; - -proto._updateChild = function(){ - var locSkeleton = this._node._skeleton, slots = locSkeleton.slots; - var color = this._displayedColor, opacity = this._displayedOpacity; - var i, n, selSprite, ax, ay; - - var slot, attachment, slotNode; - for(i = 0, n = slots.length; i < n; i++){ - slot = slots[i]; - attachment = slot.attachment; - slotNode = slot._slotNode; - if(!attachment){ - slotNode.setVisible(false); - continue; - } - if (attachment instanceof spine.RegionAttachment){ - if(attachment.region){ - if(!slot.currentSpriteName || slot.currentSpriteName !== attachment.name){ - var spriteName = attachment.region.name; - if(slot.currentSprite !== undefined) - slot.currentSprite.setVisible(false); - slot.sprites = slot.sprites ||{}; - if(slot.sprites[spriteName] !== undefined) - slot.sprites[spriteName].setVisible(true); - else{ - var sprite = this._createSprite(slot, attachment); - slotNode.addChild(sprite); - } - slot.currentSprite = slot.sprites[spriteName]; - slot.currentSpriteName = spriteName; - } - } - var bone = slot.bone; - if (attachment.region.offsetX === 0 && attachment.region.offsetY === 0) { - ax = attachment.x; - ay = attachment.y; - } - else { - //var regionScaleX = attachment.width / attachment.regionOriginalWidth * attachment.scaleX; - //ax = attachment.x + attachment.regionOffsetX * regionScaleX - (attachment.width * attachment.scaleX - attachment.regionWidth * regionScaleX) / 2; - ax = (attachment.offset[0] + attachment.offset[4]) * 0.5; - ay = (attachment.offset[1] + attachment.offset[5]) * 0.5; - } - slotNode.setPosition(bone.worldX + ax * bone.a + ay * bone.b, bone.worldY + ax * bone.c + ay * bone.d); - slotNode.setScale(bone.getWorldScaleX(), bone.getWorldScaleY()); - - //set the color and opacity - selSprite = slot.currentSprite; - selSprite._flippedX = bone.skeleton.flipX; - selSprite._flippedY = bone.skeleton.flipY; - if(selSprite._flippedY || selSprite._flippedX){ - slotNode.setRotation(bone.getWorldRotationX()); - selSprite.setRotation(attachment.rotation); - }else{ - slotNode.setRotation(-bone.getWorldRotationX()); - selSprite.setRotation(-attachment.rotation); - } - - //hack for sprite - selSprite._renderCmd._displayedOpacity = 0 | (opacity * slot.color.a); - var r = 0 | (color.r * slot.color.r), g = 0 | (color.g * slot.color.g), b = 0 | (color.b * slot.color.b); - selSprite.setColor(cc.color(r,g,b)); - selSprite._renderCmd._updateColor(); - } else if (attachment instanceof spine.MeshAttachment) { - //todo for mesh - } else { - slotNode.setVisible(false); - continue; - } - slotNode.setVisible(true); - } -}; diff --git a/extensions/spine/SGSkeletonWebGLRenderCmd.js b/extensions/spine/SGSkeletonWebGLRenderCmd.js deleted file mode 100644 index cbed1dccee..0000000000 --- a/extensions/spine/SGSkeletonWebGLRenderCmd.js +++ /dev/null @@ -1,308 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -var spine = sp.spine; - -sp._SGSkeleton.WebGLRenderCmd = function (renderableObject) { - this._rootCtor(renderableObject); - this._needDraw = true; - this._matrix = new cc.math.Matrix4(); - this._matrix.identity(); - this._currTexture = null; - this._currBlendFunc = {}; - this.vertexType = cc.renderer.VertexType.CUSTOM; - this.setShaderProgram(cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR)); -}; - -var proto = sp._SGSkeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); -proto.constructor = sp._SGSkeleton.WebGLRenderCmd; - -proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ - var node = this._node; - var color = this._displayedColor, locSkeleton = node._skeleton; - - var attachment, slot, i, n; - var premultiAlpha = node._premultipliedAlpha; - - locSkeleton.r = color.r / 255; - locSkeleton.g = color.g / 255; - locSkeleton.b = color.b / 255; - locSkeleton.a = this._displayedOpacity / 255; - if (premultiAlpha) { - locSkeleton.r *= locSkeleton.a; - locSkeleton.g *= locSkeleton.a; - locSkeleton.b *= locSkeleton.a; - } - - var debugSlotsInfo = null; - if (this._node._debugSlots) { - debugSlotsInfo = []; - } - - for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment) - continue; - attachment = slot.attachment; - - // get the vertices length - var vertCount = 0; - if (attachment instanceof spine.RegionAttachment) { - vertCount = 6; // a quad = two triangles = six vertices - } - else if (attachment instanceof spine.MeshAttachment) { - vertCount = attachment.regionUVs.length / 2; - } - else { - continue; - } - - // no vertices to render - if (vertCount === 0) { - continue; - } - var regionTextureAtlas = node.getTextureAtlas(attachment); - - // Broken for changing batch info - this._currTexture = regionTextureAtlas.texture.getRealTexture(); - var batchBroken = cc.renderer._updateBatchedInfo(this._currTexture, this._getBlendFunc(slot.data.blendMode, premultiAlpha), this._shaderProgram); - - // Broken for vertex data overflow - if (!batchBroken && vertexDataOffset + vertCount * 6 > f32buffer.length) { - // render the cached data - cc.renderer._batchRendering(); - batchBroken = true; - } - if (batchBroken) { - vertexDataOffset = 0; - } - - // update the vertex buffer - var slotDebugPoints = null; - if (attachment instanceof spine.RegionAttachment) { - slotDebugPoints = this._uploadRegionAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); - } - else if (attachment instanceof spine.MeshAttachment) { - this._uploadMeshAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); - } - else { - continue; - } - - if (this._node._debugSlots) { - debugSlotsInfo[i] = slotDebugPoints; - } - - // update the index buffer - if (attachment instanceof spine.RegionAttachment) { - cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.TRIANGLE); - } else { - cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.CUSTOM, attachment.triangles); - } - - // update the index data - vertexDataOffset += vertCount * 6; - } - - if (node._debugBones || node._debugSlots) { - // flush previous vertices - cc.renderer._batchRendering(); - - var wt = this._worldTransform, mat = this._matrix.mat; - mat[0] = wt.a; - mat[4] = wt.c; - mat[12] = wt.tx; - mat[1] = wt.b; - mat[5] = wt.d; - mat[13] = wt.ty; - - cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW); - //cc.math.glPushMatrixWitMat4(this._matrix); - cc.current_stack.stack.push(cc.current_stack.top); - cc.current_stack.top = this._matrix; - var drawingUtil = cc._drawingUtil; - - if (node._debugSlots && debugSlotsInfo && debugSlotsInfo.length > 0) { - // Slots. - drawingUtil.setDrawColor(0, 0, 255, 255); - drawingUtil.setLineWidth(1); - - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - var points = debugSlotsInfo[i]; - if (points) { - drawingUtil.drawPoly(points, 4, true); - } - } - } - - if (node._debugBones) { - // Bone lengths. - var bone; - drawingUtil.setLineWidth(2); - drawingUtil.setDrawColor(255, 0, 0, 255); - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.a + bone.worldX; - var y = bone.data.length * bone.c + bone.worldY; - drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y)); - } - - // Bone origins. - drawingUtil.setPointSize(4); - drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY)); - if (i == 0) { - drawingUtil.setDrawColor(0, 255, 0, 255); - } - } - } - cc.math.glPopMatrix(); - } - - return 0; -}; - -proto._getBlendFunc = function (blendMode, premultiAlpha) { - var ret = this._currBlendFunc; - switch (blendMode) { - case spine.BlendMode.Normal: - ret.src = premultiAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; - ret.dst = cc.macro.ONE_MINUS_SRC_ALPHA; - break; - case spine.BlendMode.Additive: - ret.src = premultiAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA; - ret.dst = cc.macro.ONE; - break; - case spine.BlendMode.Multiply: - ret.src = cc.macro.DST_COLOR; - ret.dst = cc.macro.ONE_MINUS_SRC_ALPHA; - break; - case spine.BlendMode.Screen: - ret.src = cc.macro.ONE; - ret.dst = cc.macro.ONE_MINUS_SRC_COLOR; - break; - default: - ret = this._node._blendFunc; - break; - } - - return ret; -}; - -proto._createChildFormSkeletonData = function(){}; - -proto._updateChild = function(){}; - -proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { - // the vertices in format: - // [ - // X1, Y1, C1R, C1G, C1B, C1A, U1, V1, // bottom left - // X2, Y2, C2R, C2G, C2B, C2A, U2, V2, // top left - // X3, Y3, C3R, C3G, C3B, C3A, U3, V3, // top right - // X4, Y4, C4R, C4G, C4B, C4A, U4, V4 // bottom right - // ] - // - var nodeColor = this._displayedColor; - var nodeR = nodeColor.r, - nodeG = nodeColor.g, - nodeB = nodeColor.b, - nodeA = this._displayedOpacity; - var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); - var wt = this._worldTransform, - wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, - wx = wt.tx, wy = wt.ty, - z = this._node.vertexZ; - - var offset = vertexDataOffset; - // generate 6 vertices data (two triangles) from the quad vertices - // using two angles : (0, 1, 2) & (0, 2, 3) - for (var i = 0; i < 6; i++) { - var srcIdx = i < 4 ? i % 3 : i - 2; - var vx = vertices[srcIdx * 8], - vy = vertices[srcIdx * 8 + 1]; - var x = vx * wa + vy * wc + wx, - y = vx * wb + vy * wd + wy; - var r = vertices[srcIdx * 8 + 2] * nodeR, - g = vertices[srcIdx * 8 + 3] * nodeG, - b = vertices[srcIdx * 8 + 4] * nodeB, - a = vertices[srcIdx * 8 + 5] * nodeA; - var color = ((a<<24) | (b<<16) | (g<<8) | r); - f32buffer[offset] = x; - f32buffer[offset + 1] = y; - f32buffer[offset + 2] = z; - ui32buffer[offset + 3] = color; - f32buffer[offset + 4] = vertices[srcIdx * 8 + 6]; - f32buffer[offset + 5] = vertices[srcIdx * 8 + 7]; - offset += 6; - } - - if (this._node._debugSlots) { - // return the quad points info if debug slot enabled - var VERTEX = spine.RegionAttachment; - return [ - cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]), - cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]), - cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]), - cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]) - ]; - } -}; - -proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { - var wt = this._worldTransform, - wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, - wx = wt.tx, wy = wt.ty, - z = this._node.vertexZ; - // get the vertex data - var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); - var offset = vertexDataOffset; - var nodeColor = this._displayedColor; - var nodeR = nodeColor.r, - nodeG = nodeColor.g, - nodeB = nodeColor.b, - nodeA = this._displayedOpacity; - for (var i = 0, n = vertices.length; i < n; i += 8) { - var vx = vertices[i], - vy = vertices[i + 1]; - var x = vx * wa + vy * wc + wx, - y = vx * wb + vy * wd + wy; - var r = vertices[i + 2] * nodeR, - g = vertices[i + 3] * nodeG, - b = vertices[i + 4] * nodeB, - a = vertices[i + 5] * nodeA; - var color = ((a<<24) | (b<<16) | (g<<8) | r); - - f32buffer[offset] = x; - f32buffer[offset + 1] = y; - f32buffer[offset + 2] = z; - ui32buffer[offset + 3] = color; - f32buffer[offset + 4] = vertices[i + 6]; - f32buffer[offset + 5] = vertices[i + 7]; - offset += 6; - } -}; \ No newline at end of file diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 740cd6e593..8e7decf4c9 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -23,12 +23,18 @@ THE SOFTWARE. ****************************************************************************/ +const TrackEntryListeners = require('./track-entry-listeners'); +const RenderComponent = require('../../cocos2d/core/components/CCRenderComponent'); +const spine = require('./lib/spine'); +const renderEngine = require('../../cocos2d/core/renderer/render-engine'); +const RenderData = renderEngine.RenderData; +const SpriteMaterial = renderEngine.SpriteMaterial; + /** * @module sp */ - -var DefaultSkinsEnum = cc.Enum({ 'default': -1 }); -var DefaultAnimsEnum = cc.Enum({ '': 0 }); +let DefaultSkinsEnum = cc.Enum({ 'default': -1 }); +let DefaultAnimsEnum = cc.Enum({ '': 0 }); function setEnumAttr (obj, propName, enumDef) { cc.Class.attr(obj, propName, { @@ -54,12 +60,9 @@ function setEnumAttr (obj, propName, enumDef) { * @class Skeleton * @extends Component */ - -// 由于 Spine 的 _sgNode 需要参数才能初始化, 所以这里的 _sgNode 不在构造函数中赋值, 每次访问前都要先判断一次是否初始化了 - sp.Skeleton = cc.Class({ name: 'sp.Skeleton', - extends: cc.Component, + extends: RenderComponent, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Spine Skeleton', help: 'app://docs/html/components/spine.html', @@ -67,35 +70,6 @@ sp.Skeleton = cc.Class({ }, properties: { - - /** - * Record the listeners. - */ - _startListener: { - default: null, - serializable: false, - }, - _endListener: { - default: null, - serializable: false, - }, - _completeListener: { - default: null, - serializable: false, - }, - _eventListener: { - default: null, - serializable: false, - }, - _disposeListener: { - default: null, - serializable: false, - }, - _interruptListener: { - default: null, - serializable: false, - }, - /** * !#en The skeletal animation is paused? * !#zh 该骨骼动画是否暂停。 @@ -104,23 +78,8 @@ sp.Skeleton = cc.Class({ * @readOnly * @default false */ - _paused: false, paused: { - get: function () { - return this._paused; - }, - set: function (value) { - this._paused = value; - if (!this._sgNode) { - return; - } - if (value) { - this._sgNode.pause(); - } - else { - this._sgNode.resume(); - } - }, + default: false, visible: false }, @@ -138,10 +97,12 @@ sp.Skeleton = cc.Class({ skeletonData: { default: null, type: sp.SkeletonData, - notify: function () { + notify () { this.defaultSkin = ''; this.defaultAnimation = ''; - this._refresh(); + if (CC_EDITOR) { + this._refreshInspector(); + } }, tooltip: CC_DEV && 'i18n:COMPONENT.skeleton.skeleton_data' }, @@ -153,7 +114,7 @@ sp.Skeleton = cc.Class({ //atlasFile: { // default: '', // url: cc.TextAsset, - // notify: function () { + // notify () { // this.defaultSkin = ''; // this.defaultAnimation = ''; // this._applyAsset(); @@ -187,11 +148,11 @@ sp.Skeleton = cc.Class({ * @property {String} animation */ animation: { - get: function () { + get () { var entry = this.getCurrent(0); return (entry && entry.animation.name) || ""; }, - set: function (value) { + set (value) { this.defaultAnimation = value; if (value) { this.setAnimation(0, value, this.loop); @@ -208,7 +169,7 @@ sp.Skeleton = cc.Class({ * @property {Number} _defaultSkinIndex */ _defaultSkinIndex: { - get: function () { + get () { if (this.skeletonData && this.defaultSkin) { var skinsEnum = this.skeletonData.getSkinsEnum(); if (skinsEnum) { @@ -220,7 +181,7 @@ sp.Skeleton = cc.Class({ } return 0; }, - set: function (value) { + set (value) { var skinsEnum; if (this.skeletonData) { skinsEnum = this.skeletonData.getSkinsEnum(); @@ -233,7 +194,7 @@ sp.Skeleton = cc.Class({ if (skinName !== undefined) { this.defaultSkin = skinName; if (CC_EDITOR && !cc.engine.isPlaying) { - this._refresh(); + this._refreshInspector(); } } else { @@ -248,7 +209,7 @@ sp.Skeleton = cc.Class({ // value of 0 represents no animation _animationIndex: { - get: function () { + get () { var animationName = (!CC_EDITOR || cc.engine.isPlaying) ? this.animation : this.defaultAnimation; if (this.skeletonData && animationName) { var animsEnum = this.skeletonData.getAnimsEnum(); @@ -261,7 +222,7 @@ sp.Skeleton = cc.Class({ } return 0; }, - set: function (value) { + set (value) { if (value === 0) { this.animation = ''; return; @@ -322,17 +283,8 @@ sp.Skeleton = cc.Class({ * @property {Boolean} premultipliedAlpha * @default true */ - _premultipliedAlpha: true, premultipliedAlpha: { - get: function () { - return this._premultipliedAlpha; - }, - set: function (value) { - this._premultipliedAlpha = value; - if (this._sgNode) { - this._sgNode.setPremultipliedAlpha(value); - } - }, + default: true, tooltip: CC_DEV && 'i18n:COMPONENT.skeleton.premultipliedAlpha' }, @@ -344,11 +296,6 @@ sp.Skeleton = cc.Class({ */ timeScale: { default: 1, - notify: function () { - if (this._sgNode) { - this._sgNode.setTimeScale(this.timeScale); - } - }, tooltip: CC_DEV && 'i18n:COMPONENT.skeleton.time_scale' }, @@ -360,11 +307,6 @@ sp.Skeleton = cc.Class({ */ debugSlots: { default: false, - notify: function () { - if (this._sgNode) { - this._sgNode.setDebugSlotsEnabled(this.debugSlots); - } - }, editorOnly: true, tooltip: CC_DEV && 'i18n:COMPONENT.skeleton.debug_slots' }, @@ -377,138 +319,104 @@ sp.Skeleton = cc.Class({ */ debugBones: { default: false, - notify: function () { - if (this._sgNode) { - this._sgNode.setDebugBonesEnabled(this.debugBones); - } - }, editorOnly: true, tooltip: CC_DEV && 'i18n:COMPONENT.skeleton.debug_bones' } }, - // IMPLEMENT + // CONSTRUCTOR + ctor () { + this._skeleton = null; + this._rootBone = null; + this._timeScale = 1.0; + this._listener = null; + this._boundingBox = cc.rect(); + this._material = new SpriteMaterial(); + this._renderDatas = []; + }, - __preload: function () { + /** + * !#en + * Sets runtime skeleton data to sp.Skeleton.
+ * This method is different from the `skeletonData` property. This method is passed in the raw data provided by the Spine runtime, and the skeletonData type is the asset type provided by Creator. + * !#zh + * 设置底层运行时用到的 SkeletonData。
+ * 这个接口有别于 `skeletonData` 属性,这个接口传入的是 Spine runtime 提供的原始数据,而 skeletonData 的类型是 Creator 提供的资源类型。 + * @method setSkeletonData + * @param {sp.spine.SkeletonData} skeletonData + */ + setSkeletonData (skeletonData) { + if (skeletonData.width != null && skeletonData.height != null) { + this.node.setContentSize(skeletonData.width, skeletonData.height); + } + + this._skeleton = new spine.Skeleton(skeletonData); + // this._skeleton.updateWorldTransform(); + this._rootBone = this._skeleton.getRootBone(); + }, + + /** + * !#en Sets animation state data.
+ * The parameter type is {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.AnimationStateData. + * !#zh 设置动画状态数据。
+ * 参数是 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.AnimationStateData。 + * @method setAnimationStateData + * @param {sp.spine.AnimationStateData} stateData + */ + setAnimationStateData (stateData) { + var state = new spine.AnimationState(stateData); + if (this._listener) { + if (this._state && this._listener) { + this._state.removeListener(this._listener); + } + state.addListener(this._listener); + } + this._state = state; + }, + + // IMPLEMENT + __preload () { if (CC_EDITOR) { var Flags = cc.Object.Flags; this._objFlags |= (Flags.IsAnchorLocked | Flags.IsSizeLocked); + + this._refreshInspector(); } - // sgNode 的尺寸不是很可靠 同时 Node 的框框也没办法和渲染匹配 只好强制尺寸为零 - this.node.setContentSize(0, 0); - // - this._refresh(); - }, - _createSgNode: function () { - if (this.skeletonData/* && self.atlasFile*/) { - if (CC_JSB) { - var uuid = this.skeletonData._uuid; - if ( !uuid ) { - cc.errorID(7504); - return null; - } - var jsonFile = this.skeletonData.rawUrl; - var atlasFile = this.skeletonData.atlasUrl; - if (atlasFile) { - if (typeof atlasFile !== 'string') { - cc.errorID(7505); - return null; - } - try { - return new sp._SGSkeletonAnimation(jsonFile, atlasFile, this.skeletonData.scale); - } - catch (e) { - cc._throw(e); + if (this.skeletonData/* && this.atlasFile*/) { + var data = this.skeletonData.getRuntimeData(); + if (data) { + try { + this.setSkeletonData(data); + this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); + if (this.defaultSkin) { + this._skeleton.setSkinByName(this.defaultSkin); } } - } - else { - var data = this.skeletonData.getRuntimeData(); - if (data) { - try { - return new sp._SGSkeletonAnimation(data, null, this.skeletonData.scale); - } - catch (e) { - cc._throw(e); - } + catch (e) { + cc.warn(e); } + this.animation = this.defaultAnimation; } } - return null; - }, - - _initSgNode: function () { - var sgNode = this._sgNode; - sgNode.setTimeScale(this.timeScale); - - var self = this; - sgNode.onEnter = function () { - _ccsg.Node.prototype.onEnter.call(this); - if (self._paused) { - this.pause(); - } - }; - - // using the recorded event listeners - this._startListener && this.setStartListener(this._startListener); - this._endListener && this.setEndListener(this._endListener); - this._completeListener && this.setCompleteListener(this._completeListener); - this._eventListener && this.setEventListener(this._eventListener); - this._interruptListener && this.setInterruptListener(this._interruptListener); - this._disposeListener && this.setDisposeListener(this._disposeListener); - - //if (!CC_EDITOR) { - // function animationCallback (ccObj, trackIndex, type, event, loopCount) { - // var eventType = AnimEvents[type];3 - // var detail = { - // trackIndex: trackIndex - // }; - // if (type === sp.ANIMATION_EVENT_TYPE.COMPLETE) { - // detail.loopCount = loopCount; - // } - // else if (type === sp.ANIMATION_EVENT_TYPE.EVENT) { - // detail.event = event; - // } - // //Fire.log("[animationCallback] eventType: %s, time: '%s'", eventType, Fire.Time.time); - // self.entity.emit(eventType, detail); - // } - // sgNode.setAnimationListener(target, animationCallback); - //} - if (this.defaultSkin) { - try { - sgNode.setSkin(this.defaultSkin); - } - catch (e) { - cc._throw(e); - } - } - - sgNode.setPremultipliedAlpha(this._premultipliedAlpha); - - this.animation = this.defaultAnimation; - if (CC_EDITOR) { - sgNode.setDebugSlotsEnabled(this.debugSlots); - sgNode.setDebugBonesEnabled(this.debugBones); - } }, - _getLocalBounds: CC_EDITOR && function (out_rect) { - if (this._sgNode) { - var rect = this._sgNode.getBoundingBox(); - out_rect.x = rect.x; - out_rect.y = rect.y; - out_rect.width = rect.width; - out_rect.height = rect.height; - } - else { - out_rect.x = 0; - out_rect.y = 0; - out_rect.width = 0; - out_rect.height = 0; + onDestroy () { + this._super(); + for (let i = 0; i < this._renderDatas.length; i++) { + RenderData.free(this._renderDatas[i]); } + this._renderDatas.length = 0; }, + // _getLocalBounds: CC_EDITOR && function (out_rect) { + // var rect = this._boundingBox; + // out_rect.x = rect.x; + // out_rect.y = rect.y; + // out_rect.width = rect.width; + // out_rect.height = rect.height; + // }, + // RENDERER /** @@ -523,9 +431,9 @@ sp.Skeleton = cc.Class({ * bone = spine.findBone('head'); * cc.log(bone.worldX); // return -23.12; */ - updateWorldTransform: function () { - if (this._sgNode) { - this._sgNode.updateWorldTransform(); + updateWorldTransform () { + if (this._skeleton) { + this._skeleton.updateWorldTransform(); } }, @@ -534,9 +442,9 @@ sp.Skeleton = cc.Class({ * !#zh 还原到起始动作 * @method setToSetupPose */ - setToSetupPose: function () { - if (this._sgNode) { - this._sgNode.setToSetupPose(); + setToSetupPose () { + if (this._skeleton) { + this._skeleton.setToSetupPose(); } }, @@ -549,9 +457,9 @@ sp.Skeleton = cc.Class({ * 使用 SkeletonData 中的 BoneData 列表中的值。 * @method setBonesToSetupPose */ - setBonesToSetupPose: function () { - if (this._sgNode) { - this._sgNode.setBonesToSetupPose(); + setBonesToSetupPose () { + if (this._skeleton) { + this._skeleton.setBonesToSetupPose(); } }, @@ -564,9 +472,9 @@ sp.Skeleton = cc.Class({ * 使用 SkeletonData 中的 SlotData 列表中的值。 * @method setSlotsToSetupPose */ - setSlotsToSetupPose: function () { - if (this._sgNode) { - this._sgNode.setSlotsToSetupPose(); + setSlotsToSetupPose () { + if (this._skeleton) { + this._skeleton.setSlotsToSetupPose(); } }, @@ -584,9 +492,9 @@ sp.Skeleton = cc.Class({ * @param {String} boneName * @return {sp.spine.Bone} */ - findBone: function (boneName) { - if (this._sgNode) { - return this._sgNode.findBone(boneName); + findBone (boneName) { + if (this._skeleton) { + return this._skeleton.findBone(boneName); } return null; }, @@ -603,9 +511,9 @@ sp.Skeleton = cc.Class({ * @param {String} slotName * @return {sp.spine.Slot} */ - findSlot: function (slotName) { - if (this._sgNode) { - return this._sgNode.findSlot(slotName); + findSlot (slotName) { + if (this._skeleton) { + return this._skeleton.findSlot(slotName); } return null; }, @@ -625,9 +533,9 @@ sp.Skeleton = cc.Class({ * @param {String} skinName * @return {sp.spine.Skin} */ - setSkin: function (skinName) { - if (this._sgNode) { - return this._sgNode.setSkin(skinName); + setSkin (skinName) { + if (this._skeleton) { + return this._skeleton.setSkin(skinName); } return null; }, @@ -646,9 +554,9 @@ sp.Skeleton = cc.Class({ * @param {String} attachmentName * @return {sp.spine.Attachment} */ - getAttachment: function (slotName, attachmentName) { - if (this._sgNode) { - return this._sgNode.getAttachment(slotName, attachmentName); + getAttachment (slotName, attachmentName) { + if (this._skeleton) { + return this._skeleton.getAttachment(slotName, attachmentName); } return null; }, @@ -664,57 +572,23 @@ sp.Skeleton = cc.Class({ * @param {String} slotName * @param {String} attachmentName */ - setAttachment: function (slotName, attachmentName) { - if (this._sgNode) { - this._sgNode.setAttachment(slotName, attachmentName); + setAttachment (slotName, attachmentName) { + if (this._skeleton) { + this._skeleton.setAttachment(slotName, attachmentName); } }, /** - * !#en - * Sets runtime skeleton data to sp.Skeleton.
- * This method is different from the `skeletonData` property. This method is passed in the raw data provided by the Spine runtime, and the skeletonData type is the asset type provided by Creator. - * !#zh - * 设置底层运行时用到的 SkeletonData。
- * 这个接口有别于 `skeletonData` 属性,这个接口传入的是 Spine runtime 提供的原始数据,而 skeletonData 的类型是 Creator 提供的资源类型。 - * @method setSkeletonData - * @param {sp.spine.SkeletonData} skeletonData - * @param {sp.spine.SkeletonData} ownsSkeletonData - */ - setSkeletonData: function (skeletonData, ownsSkeletonData) { - if (this._sgNode) { - this._sgNode.setSkeletonData(skeletonData, ownsSkeletonData); - } + * Return the renderer of attachment. + * @method getTextureAtlas + * @param {sp.spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment + * @return {sp.spine.TextureAtlasRegion} + */ + getTextureAtlas (regionAttachment) { + return regionAttachment.region; }, - ///** - // * Return the renderer of attachment. - // * @method getTextureAtlas - // * @param {sp.spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment - // * @return {_ccsg.Node} - // */ - //getTextureAtlas: function (regionAttachment) { - // if (this._sgNode) { - // this._sgNode.getTextureAtlas(regionAttachment); - // } - //}, - // ANIMATION - - /** - * !#en Sets animation state data.
- * The parameter type is {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.AnimationStateData. - * !#zh 设置动画状态数据。
- * 参数是 {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.AnimationStateData。 - * @method setAnimationStateData - * @param {sp.spine.AnimationStateData} stateData - */ - setAnimationStateData: function (stateData) { - if (this._sgNode) { - return this._sgNode.setAnimationStateData(stateData); - } - }, - /** * !#en * Mix applies all keyframe values, @@ -725,9 +599,9 @@ sp.Skeleton = cc.Class({ * @param {String} toAnimation * @param {Number} duration */ - setMix: function (fromAnimation, toAnimation, duration) { - if (this._sgNode) { - this._sgNode.setMix(fromAnimation, toAnimation, duration); + setMix (fromAnimation, toAnimation, duration) { + if (this._state) { + this._state.data.setMixWith(fromAnimation, toAnimation, duration); } }, @@ -738,9 +612,9 @@ sp.Skeleton = cc.Class({ * @param {Object} target * @param {Function} callback */ - setAnimationListener: function (target, callback) { - if (this._sgNode) { - this._sgNode.setAnimationListener(target, callback); + setAnimationListener (target, callback) { + if (this._skeleton) { + this._skeleton.setAnimationListener(target, callback); } }, @@ -755,24 +629,23 @@ sp.Skeleton = cc.Class({ * @param {Boolean} loop * @return {sp.spine.TrackEntry} */ - setAnimation: function (trackIndex, name, loop) { - if (this._sgNode) { - var res = this._sgNode.setAnimation(trackIndex, name, loop); + setAnimation (trackIndex, name, loop) { + if (this._skeleton) { + var animation = this._skeleton.data.findAnimation(name); + if (!animation) { + cc.logID(7509, name); + return null; + } + var res = this._state.setAnimationWith(trackIndex, animation, loop); if (CC_EDITOR && !cc.engine.isPlaying) { - this._sample(); - this.clearTrack(trackIndex); + this._state.update(0); + this._state.clearTracks(); } return res; } return null; }, - _sample: function () { - if (this._sgNode) { - this._sgNode.update(0); - } - }, - /** * !#en Adds an animation to be played delay seconds after the current or last queued animation.
* Returns a {{#crossLinkModule "sp.spine"}}sp.spine{{/crossLinkModule}}.TrackEntry object. @@ -785,9 +658,15 @@ sp.Skeleton = cc.Class({ * @param {Number} [delay=0] * @return {sp.spine.TrackEntry} */ - addAnimation: function (trackIndex, name, loop, delay) { - if (this._sgNode) { - return this._sgNode.addAnimation(trackIndex, name, loop, delay || 0); + addAnimation (trackIndex, name, loop, delay) { + if (this._skeleton) { + delay = delay || 0; + var animation = this._skeleton.data.findAnimation(name); + if (!animation) { + cc.logID(7510, name); + return null; + } + return this._state.addAnimationWith(trackIndex, animation, loop, delay); } return null; }, @@ -799,9 +678,9 @@ sp.Skeleton = cc.Class({ * @param {String} name * @returns {sp.spine.Animation} */ - findAnimation: function (name) { - if (this._sgNode) { - return this._sgNode.findAnimation(name); + findAnimation (name) { + if (this._skeleton) { + return this._skeleton.data.findAnimation(name); } return null; }, @@ -815,9 +694,9 @@ sp.Skeleton = cc.Class({ * @param trackIndex * @return {sp.spine.TrackEntry} */ - getCurrent: function (trackIndex) { - if (this._sgNode) { - return this._sgNode.getCurrent(trackIndex); + getCurrent (trackIndex) { + if (this._state) { + return this._state.getCurrent(trackIndex); } return null; }, @@ -827,9 +706,9 @@ sp.Skeleton = cc.Class({ * !#zh 清除所有 track 的动画状态。 * @method clearTracks */ - clearTracks: function () { - if (this._sgNode) { - this._sgNode.clearTracks(); + clearTracks () { + if (this._state) { + this._state.clearTracks(); } }, @@ -839,11 +718,11 @@ sp.Skeleton = cc.Class({ * @method clearTrack * @param {number} trackIndex */ - clearTrack: function (trackIndex) { - if (this._sgNode) { - this._sgNode.clearTrack(trackIndex); + clearTrack (trackIndex) { + if (this._state) { + this._state.clearTrack(trackIndex); if (CC_EDITOR && !cc.engine.isPlaying) { - this._sample(); + this._state.update(0); } } }, @@ -867,17 +746,22 @@ sp.Skeleton = cc.Class({ setEnumAttr(this, '_defaultSkinIndex', skinEnum || DefaultSkinsEnum); }, + _ensureListener () { + if (!this._listener) { + this._listener = new TrackEntryListeners(); + this._state.addListener(this._listener); + } + }, + /** * !#en Set the start event listener. * !#zh 用来设置开始播放动画的事件监听。 * @method setStartListener * @param {function} listener */ - setStartListener: function (listener) { - this._startListener = listener; - if (this._sgNode) { - this._sgNode.setStartListener(listener); - } + setStartListener (listener) { + this._ensureListener(); + this._listener.start = listener; }, /** @@ -886,11 +770,9 @@ sp.Skeleton = cc.Class({ * @method setInterruptListener * @param {function} listener */ - setInterruptListener: function (listener) { - this._interruptListener = listener; - if (this._sgNode) { - this._sgNode.setInterruptListener(listener); - } + setInterruptListener (listener) { + this._ensureListener(); + this._listener.interrupt = listener; }, /** @@ -899,11 +781,9 @@ sp.Skeleton = cc.Class({ * @method setEndListener * @param {function} listener */ - setEndListener: function (listener) { - this._endListener = listener; - if (this._sgNode) { - this._sgNode.setEndListener(listener); - } + setEndListener (listener) { + this._ensureListener(); + this._listener.end = listener; }, /** @@ -912,11 +792,9 @@ sp.Skeleton = cc.Class({ * @method setDisposeListener * @param {function} listener */ - setDisposeListener: function (listener) { - this._disposeListener = listener; - if (this._sgNode) { - this._sgNode.setDisposeListener(listener); - } + setDisposeListener (listener) { + this._ensureListener(); + this._listener.dispose = listener; }, /** @@ -925,11 +803,9 @@ sp.Skeleton = cc.Class({ * @method setCompleteListener * @param {function} listener */ - setCompleteListener: function (listener) { - this._completeListener = listener; - if (this._sgNode) { - this._sgNode.setCompleteListener(listener); - } + setCompleteListener (listener) { + this._ensureListener(); + this._listener.complete = listener; }, /** @@ -938,11 +814,9 @@ sp.Skeleton = cc.Class({ * @method setEventListener * @param {function} listener */ - setEventListener: function (listener) { - this._eventListener = listener; - if (this._sgNode) { - this._sgNode.setEventListener(listener); - } + setEventListener (listener) { + this._ensureListener(); + this._listener.event = listener; }, /** @@ -952,10 +826,8 @@ sp.Skeleton = cc.Class({ * @param {sp.spine.TrackEntry} entry * @param {function} listener */ - setTrackStartListener: function (entry, listener) { - if (this._sgNode) { - this._sgNode.setTrackStartListener(entry, listener); - } + setTrackStartListener (entry, listener) { + TrackEntryListeners.getListeners(entry).start = listener; }, /** @@ -965,10 +837,8 @@ sp.Skeleton = cc.Class({ * @param {sp.spine.TrackEntry} entry * @param {function} listener */ - setTrackInterruptListener: function (entry, listener) { - if (this._sgNode) { - this._sgNode.setTrackInterruptListener(entry, listener); - } + setTrackInterruptListener (entry, listener) { + TrackEntryListeners.getListeners(entry).interrupt = listener; }, /** @@ -978,10 +848,8 @@ sp.Skeleton = cc.Class({ * @param {sp.spine.TrackEntry} entry * @param {function} listener */ - setTrackEndListener: function (entry, listener) { - if (this._sgNode) { - this._sgNode.setTrackEndListener(entry, listener); - } + setTrackEndListener (entry, listener) { + TrackEntryListeners.getListeners(entry).end = listener; }, /** @@ -991,10 +859,8 @@ sp.Skeleton = cc.Class({ * @param {sp.spine.TrackEntry} entry * @param {function} listener */ - setTrackDisposeListener: function(entry, listener){ - if (this._sgNode) { - this._sgNode.setTrackDisposeListener(entry, listener); - } + setTrackDisposeListener(entry, listener){ + TrackEntryListeners.getListeners(entry).dispose = listener; }, /** @@ -1003,11 +869,14 @@ sp.Skeleton = cc.Class({ * @method setTrackCompleteListener * @param {sp.spine.TrackEntry} entry * @param {function} listener + * @param {sp.spine.TrackEntry} listener.entry + * @param {Number} listener.loopCount */ - setTrackCompleteListener: function (entry, listener) { - if (this._sgNode) { - this._sgNode.setTrackCompleteListener(entry, listener); - } + setTrackCompleteListener (entry, listener) { + TrackEntryListeners.getListeners(entry).complete = function (trackEntry) { + var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); + listener(trackEntry, loopCount); + }; }, /** @@ -1017,52 +886,26 @@ sp.Skeleton = cc.Class({ * @param {sp.spine.TrackEntry} entry * @param {function} listener */ - setTrackEventListener: function (entry, listener) { - if (this._sgNode) { - this._sgNode.setTrackEventListener(entry, listener); - } + setTrackEventListener (entry, listener) { + TrackEntryListeners.getListeners(entry).event = listener; }, - // - - getState: function () { - if (this._sgNode) { - return this._sgNode.getState(); - } + /** + * !#en Get the animation state object + * !#zh 获取 + * @method setTrackEventListener + * @return {sp.spine.AnimationState} state + */ + getState () { + return this._state; }, - _refresh: function () { - var self = this; - - // discard exists sgNode - if (self._sgNode) { - if ( self.node._sizeProvider === self._sgNode ) { - self.node._sizeProvider = null; - } - self._removeSgNode(); - self._sgNode = null; - } - - // recreate sgNode... - var sgNode = self._sgNode = self._createSgNode(); - if (sgNode) { - if (CC_JSB) { - sgNode.retain(); - } - if ( !self.enabledInHierarchy ) { - sgNode.setVisible(false); - } - sgNode.setContentSize(0, 0); // restore content size - self._initSgNode(); - self._appendSgNode(sgNode); - self._registSizeProvider(); - } - - if (CC_EDITOR) { - // update inspector - self._updateAnimEnum(); - self._updateSkinEnum(); - Editor.Utils.refreshSelectedInspector('node', this.node.uuid); - } + _refreshInspector () { + // update inspector + this._updateAnimEnum(); + this._updateSkinEnum(); + Editor.Utils.refreshSelectedInspector('node', this.node.uuid); } }); + +module.exports = sp.Skeleton; \ No newline at end of file diff --git a/extensions/spine/index.js b/extensions/spine/index.js index de6b95f8c4..362ab4e4e1 100644 --- a/extensions/spine/index.js +++ b/extensions/spine/index.js @@ -42,18 +42,6 @@ sp = CC_JSB ? sp : {}; -// The vertex index of spine. -sp.VERTEX_INDEX = { - X1: 0, - Y1: 1, - X2: 2, - Y2: 3, - X3: 4, - Y3: 5, - X4: 6, - Y4: 7 -}; - // The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. sp.ATTACHMENT_TYPE = { REGION: 0, @@ -107,24 +95,19 @@ sp.AnimationEventType = cc.Enum({ /** * @module sp */ - if (!CC_EDITOR || !Editor.isMainProcess) { if (!CC_JSB) { sp.spine = require('./lib/spine'); - - require('./SGSkeletonTexture'); - // require('./SGSkeleton'); - // require('./SGSkeletonCanvasRenderCmd'); - // require('./SGSkeletonWebGLRenderCmd'); - // require('./SGSkeletonAnimation'); } - require('./SkeletonData'); - require('./Skeleton'); + require('./skeleton-texture'); + require('./skeleton-data'); + require('./skeleton'); + require('../../cocos2d/core/renderer/assemblers/spine-assembler'); } else { - require('./SkeletonData'); + require('./skeleton-data'); } /** diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/skeleton-data.js similarity index 95% rename from extensions/spine/SkeletonData.js rename to extensions/spine/skeleton-data.js index 67493c1670..fe338c5846 100644 --- a/extensions/spine/SkeletonData.js +++ b/extensions/spine/skeleton-data.js @@ -28,7 +28,7 @@ */ // implements a simple texture loader like sp._atlasLoader -var TextureLoader = !CC_JSB && cc.Class({ +var TextureLoader = cc.Class({ ctor: function () { // {SkeletonData} this.asset = arguments[0]; @@ -46,7 +46,7 @@ var TextureLoader = !CC_JSB && cc.Class({ for (var i = 0; i < urls.length; i++) { var url = urls[i]; if (url.endsWith(line)) { - var texture = cc.textureCache.addImage(url); + var texture = cc.textureUtil.loadImage(url); var tex = new sp.SkeletonTexture({ width: texture.width, height: texture.height }); tex.setRealTexture(texture); return tex; @@ -154,11 +154,6 @@ var SkeletonData = cc.Class({ // PUBLIC createNode: CC_EDITOR && function (callback) { - //var Url = require('fire-url'); - //var node = new cc.Node(Url.basenameNoExt(info.url)); - //var skeleton = node.addComponent(sp.Skeleton); - //skeleton.skeletonFile = info.url; - var node = new cc.Node(this.name); var skeleton = node.addComponent(sp.Skeleton); skeleton.skeletonData = this; @@ -192,12 +187,11 @@ var SkeletonData = cc.Class({ * @param {Boolean} [quiet=false] * @return {sp.spine.SkeletonData} */ - getRuntimeData: !CC_JSB && function (quiet) { + getRuntimeData: function (quiet) { if (this._skeletonCache) { return this._skeletonCache; } - if ( !(this.textures && this.textures.length > 0) ) { if ( !quiet ) { cc.errorID(7507, this.name); @@ -264,7 +258,7 @@ var SkeletonData = cc.Class({ * @return {sp.spine.Atlas} * @private */ - _getAtlas: !CC_JSB && function (quiet) { + _getAtlas: function (quiet) { if (this._atlasCache) { return this._atlasCache; } diff --git a/extensions/spine/SGSkeletonTexture.js b/extensions/spine/skeleton-texture.js similarity index 69% rename from extensions/spine/SGSkeletonTexture.js rename to extensions/spine/skeleton-texture.js index 455ee25a54..688409750b 100644 --- a/extensions/spine/SGSkeletonTexture.js +++ b/extensions/spine/skeleton-texture.js @@ -26,6 +26,7 @@ sp.SkeletonTexture = cc.Class({ name: 'sp.SkeletonTexture', extends: sp.spine.Texture, _texture: null, + _material: null, setRealTexture: function(tex) { this._texture = tex; @@ -36,29 +37,16 @@ sp.SkeletonTexture = cc.Class({ }, setFilters: function(minFilter, magFilter) { - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - var gl = cc._renderContext; - this.bind(); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); + if (this._texture) { + this._texture.setFilters(minFilter, magFilter); } }, setWraps: function(uWrap, vWrap) { - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - var gl = cc._renderContext; - this.bind(); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, uWrap); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, vWrap); + if (this._texture) { + this._texture.setWrapMode(uWrap, vWrap); } }, - dispose: function() { - }, - - bind: function() { - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - cc.gl.bindTexture2DN(0, this._texture); - } - } + dispose: function() {} }); diff --git a/extensions/spine/track-entry-listeners.js b/extensions/spine/track-entry-listeners.js new file mode 100644 index 0000000000..47a7d12a8b --- /dev/null +++ b/extensions/spine/track-entry-listeners.js @@ -0,0 +1,17 @@ +let TrackEntryListeners = function () { + this.start = null; + this.end = null; + this.complete = null; + this.event = null; + this.interrupt = null; + this.dispose = null; +}; + +TrackEntryListeners.getListeners = function(entry){ + if (!entry.listener) { + entry.listener = new TrackEntryListeners(); + } + return entry.listener; +}; + +module.exports = TrackEntryListeners; \ No newline at end of file