Search code examples
openglcocos2d-x

Why would glDrawArrays result in EXC_BAD_ACCESS (code=2, address=0x0)?


Why would the following line:

glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)numberOfVertices);

result in : EXC_BAD_ACCESS (code=2, address=0x0)

void Earth::onDraw(const cocos2d::Mat4 &transform, bool transformUpdated){
    Sprite *stripes = Sprite::create("stripes.png");
    this->setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::GLProgram::SHADER_NAME_POSITION_TEXTURE));
    CC_NODE_DRAW_SETUP();
    GL::bindTexture2D(stripes->getTexture()->getName());
    GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_TEX_COORD);
    DrawPrimitives::setDrawColor4F(1.0f, 1.0f, 1.0f, 1.0f);
    glVertexAttribPointer(GL::VERTEX_ATTRIB_FLAG_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
    glVertexAttribPointer(GL::VERTEX_ATTRIB_FLAG_TEX_COORD, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)numberOfVertices);
}

Earth is a cocos2d::Node.


Solution

  • Based on the cocos2d-x documentation I found (http://www.cocos2d-x.org/reference/native-cpp/V3.0beta2/d4/d83/group__shaders.html), GL::VERTEX_ATTRIB_FLAG_POSITION and GL::VERTEX_ATTRIB_FLAG_TEX_COORD are bitmask values, with values 1 and 4. But you use them as the first argument to glVertexAttribPointer():

    glVertexAttribPointer(GL::VERTEX_ATTRIB_FLAG_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
    glVertexAttribPointer(GL::VERTEX_ATTRIB_FLAG_TEX_COORD, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates);
    

    The first argument here needs to be the location of the vertex attributes, which is unlikely to be 1 and 4. The way I interpret the documentation, you would need to use these values instead:

    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates);