CCSpriteBatchNode
它是批处理绘制精灵,主要是用来提高精灵的绘制效率的,需要绘制的精灵数量越多,效果越明显。因为cocos2d-x采用opengl es绘制图片的,opengl es绘制每个精灵都会执行:open-draw-close流程。而CCSpriteBatchNode是把多个精灵放到一个纹理上,绘制的时候直接统一绘制该texture,不需要单独绘制子节点,这样opengl es绘制的时候变成了:open-draw()-draw()…-draw()-close(),节省了多次open-close的时间。CCSpriteBatchNode内部封装了一个CCTextureAtlas(纹理图集,它内部封装了一个CCTexture2D)和一个CCArray(用来存储CCSpriteBatchNode的子节点:单个精灵)。注意:因为绘制的时候只open-close一次,所以CCSpriteBatchNode对象的所有子节点都必须和它是用同一个texture(同一张图片),类似下面这样的图片,4个贝壳都在同一纹理上:
在addChild的时候会检查子节点是不是Sprite类型,纹理的名称跟CCSpriteBatchNode的是不是一样,如果不一样就会出错,源码:
void SpriteBatchNode::addChild(Node *child, int zOrder, int tag)
{
CCASSERT(child != nullptr, "child should not be null");
CCASSERT(dynamic_cast<Sprite*>(child) != nullptr, "CCSpriteBatchNode only supports Sprites as children");
Sprite *sprite = static_cast<Sprite*>(child);
// check Sprite is using the same texture id
CCASSERT(sprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "CCSprite is not using the same texture id");
Node::addChild(child, zOrder, tag);
appendChild(sprite);
}
再看看3.0版本里的draw部分
void SpriteBatchNode::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
// Optimization: Fast Dispatch
if( _textureAtlas->getTotalQuads() == 0 )
{
return;
}
for(const auto &child: _children)
child->updateTransform();
_batchCommand.init(
_globalZOrder,
getGLProgram(),
_blendFunc,
_textureAtlas,
transform);
renderer->addCommand(&_batchCommand);
}
向渲染器里添加里一个BatchCommand,跟到BatchCommand里
void BatchCommand::execute()
{
// Set material
_shader->use();
_shader->setUniformsForBuiltins(_mv);
GL::bindTexture2D(_textureID);
GL::blendFunc(_blendType.src, _blendType.dst);
// Draw
_textureAtlas->drawQuads();
}
当程序准备渲染SpriteBatchNode里的精灵时,这个函数就会被调用。里面调用了TextureAtlas的drawQuads对精灵进行批量绘制
下面是使用CCSpriteBatchNode的使用代码示例:
1
2
3
4
5
6
7
8
9
10
11
12
|
CCSpriteBatchNode* BatchNode1 = CCSpriteBatchNode::batchNodeWithFile(
"Images/grossini_dance_atlas.png"
, 50);
addChild(BatchNode1, 0, kTagSpriteBatchNode);
CCSpriteBatchNode* BatchNode = (CCSpriteBatchNode*) getChildByTag( kTagSpriteBatchNode );
int
idx = CCRANDOM_0_1() * 1400 / 100;
int
x = (idx%5) * 85;
int
y = (idx/5) * 121;
CCSprite* sprite = CCSprite::spriteWithTexture(BatchNode->getTexture(), CCRectMake(x,y,85,121));
BatchNode->addChild(sprite);
sprite->setPosition( ccp( p.x, p.y) );
|