美文网首页
从Cocos2d看OpenGL的使用

从Cocos2d看OpenGL的使用

作者: 奔向火星005 | 来源:发表于2019-01-02 14:25 被阅读0次

1. 上下文切换

cocos2d中切换上下文时,先判断当前上下文是否是将要切换的上下文,若不是,先调用glFlush(),再切换,源码如下(在CCDirectorCaller-ios.mm文件):

        EAGLContext* cocos2dxContext = [(CCEAGLView*)director->getOpenGLView()->getEAGLView() context];
        if (cocos2dxContext != [EAGLContext currentContext])
            glFlush();
        
        [EAGLContext setCurrentContext: cocos2dxContext];

2. 纹理对齐

cocos2d在加载图片生成纹理时,会根据图片宽度,用glPixelStorei来设置纹理数据的对齐数值。源码如下(在CCTexture2D.cpp文件):

bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat pixelFormat, int pixelsWide, int pixelsHigh)
{
///省略
    if (mipmapsNum == 1 && !info.compressed)
    {
        unsigned int bytesPerRow = pixelsWide * info.bpp / 8;

        if(bytesPerRow % 8 == 0)  //根据图片的宽来决定纹理数据对齐
        {
            glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
        }
        else if(bytesPerRow % 4 == 0)
        {
            glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
        }
        else if(bytesPerRow % 2 == 0)
        {
            glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
        }
        else
        {
            glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        }
    }else
    {
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    }

    if(_name != 0)
    {
        GL::deleteTexture(_name);
        _name = 0;
    }

    glGenTextures(1, &_name);
    GL::bindTexture2D(_name);
///省略
}

未完待续...

相关文章

网友评论

      本文标题:从Cocos2d看OpenGL的使用

      本文链接:https://www.haomeiwen.com/subject/gidzlqtx.html