glDrawElements batching

Simple class that caches DIPs and example how to use it with box2d debug renderer.

DebugDraw.h

#ifndef __DEBUGDRAW_H__
#define __DEBUGDRAW_H__

#include "cocos2d.h"

#pragma pack(push, 1)
struct ColorVertex
{
    GLfloat x, y;
    GLubyte r, g, b, a;
};
#pragma pack(pop)

// T must be POD type!!!
template class DrawBuffer
{
public:

    DrawBuffer() : data(NULL), len(0), pos(0), nalloc(0) {}
    ~DrawBuffer() {dealloc();}

    void reserve(GLsizei cap)
    {
        GLsizei n = pos + cap;
        if (n > len)
        {
            if (n < ChunkLen) {
                n = ChunkLen;
            }
            else {
                n = ((n / ChunkLen) + ((n % ChunkLen > 0) ? 1 : 0)) * ChunkLen;
            }
            T* newdata = new T[n];
            ++nalloc;
            if (pos > 0) {
                memcpy(newdata, data, pos * sizeof(T));
            }
            if (data) {
                delete [] data;
            }
            data = newdata;
            len = n;
        }
    }

    void dealloc()
    {
        if (data)
        {
            delete [] data;
            data = NULL;
        }
        len = pos = 0;
    }

    void reset()
    {
        pos = 0;
    }

    T* ptr() {return data + pos;}

public:

    T* data;
    GLsizei len;
    GLsizei pos;
    GLsizei nalloc;
};

template class DrawElement
{
public:

    typedef DrawBuffer VertexBuffer;
    typedef DrawBuffer IndexBuffer;

    DrawElement() {reset();}

    void reserve(GLsizei vblen, GLsizei iblen)
    {
        vb.reserve(vblen);
        ib.reserve(iblen);
    }

    void append(GLsizei numvert, GLsizei numind)
    {
        vb.pos += numvert;
        ib.pos += numind;
    }

    void reset()
    {
        vb.reset();
        ib.reset();
    }

public:

    VertexBuffer vb;
    IndexBuffer ib;
};

typedef DrawElement ColorVertexElement;

class DebugDraw
{
public:

    static void draw(ColorVertexElement& elem, GLenum mode);
};

#endif

DebugDraw.cpp

#include "DebugDraw.h"

USING_NS_CC;

void DebugDraw::draw(ColorVertexElement& elem, GLenum mode)
{
    if (elem.vb.pos > 0 && elem.ib.pos > 0)
    {
        ColorVertex* vptr = elem.vb.data;
        GLushort* iptr = elem.ib.data;

        glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(ColorVertex), &vptr[0].x);
        glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ColorVertex), &vptr[0].r);
        glDrawElements(mode, elem.ib.pos, GL_UNSIGNED_SHORT, iptr);

        CC_INCREMENT_GL_DRAWS(elem.ib.pos);
        CHECK_GL_ERROR_DEBUG();
    }
}

Box2dDebugDraw.h

#ifndef __BOX2DDEBUGDRAW_H__
#define __BOX2DDEBUGDRAW_H__

#include "DebugDraw.h"
#include "Box2D/Box2D.h"

class Box2dDebugDraw : public b2Draw
{
public:

    Box2dDebugDraw();
    virtual ~Box2dDebugDraw();

    bool init();
    void shut();
    void beginScene();
    void endScene();

    // b2Draw impl
    virtual void DrawPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);
    virtual void DrawSolidPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);
    virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);
    virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);
    virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
    virtual void DrawTransform(const b2Transform& xf);

    void DrawAABB(b2AABB* aabb, const b2Color& color);
    void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color);
    void DrawString(int x, int y, const char* string, ...); 

    void setRatio(float32 ratio) {mRatio = ratio;}

private:

    cocos2d::CCGLProgram* mShaderProgram;
    ColorVertexElement mLines;
    ColorVertexElement mTris;
    float32 mRatio;
};

#endif

Box2dDebugDraw.cpp

#include "Box2dDebugDraw.h"
//#include "Debug.h"

USING_NS_CC;

Box2dDebugDraw::Box2dDebugDraw() :
    mShaderProgram(NULL),
    mRatio(1)
{
    //DTRACE("Box2dDebugDraw");
    init();
}

Box2dDebugDraw::~Box2dDebugDraw()
{
    //DTRACE("~Box2dDebugDraw");
    shut();
}

bool Box2dDebugDraw::init()
{
    //DTRACE("Box2dDebugDraw::init");
    mShaderProgram = CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionColor);
    mLines.reserve(1024, 1024);
    mTris.reserve(1024, 1024);
    return true;
}

void Box2dDebugDraw::shut()
{
    //DTRACE("Box2dDebugDraw::shut");
}

void Box2dDebugDraw::beginScene()
{
    mShaderProgram->use();
    mShaderProgram->setUniformForModelViewProjectionMatrix();
    ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position | kCCVertexAttribFlag_Color);

    mLines.reset();
    mTris.reset();
}

void Box2dDebugDraw::endScene()
{
    DebugDraw::draw(mTris, GL_TRIANGLES);
    DebugDraw::draw(mLines, GL_LINES);
}

inline GLubyte f2byte(float32 f)
{
    return (GLubyte)(f * 255);
}

inline void colorvertex(ColorVertex& v, const b2Vec2& pos, const b2Color& color, float32 alpha = 1)
{
    v.x = pos.x;
    v.y = pos.y;
    v.r = f2byte(color.r * alpha);
    v.g = f2byte(color.g * alpha);
    v.b = f2byte(color.b * alpha);
    v.a = f2byte(alpha);
}

void Box2dDebugDraw::DrawPolygon(const b2Vec2* old_vertices, int vertexCount, const b2Color& color)
{
    if (vertexCount < 3) {
        //DASSERT(false && "invalid polygon");
        return;
    }

    int indexCount = vertexCount * 2;

    mLines.reserve(vertexCount, indexCount);
    ColorVertex* vb = mLines.vb.ptr();
    GLushort* ib = mLines.ib.ptr();
    GLsizei vbp0 = mLines.vb.pos;
    GLsizei vbp = vbp0;

    for (int i = 0; i < vertexCount; i++)
    {
        colorvertex(*vb++, old_vertices[i], color);
        *ib++ = vbp;
        *ib++ = vbp + 1;
        ++vbp;
    }

    *--ib = vbp0;
    mLines.append(vertexCount, indexCount);
}

void Box2dDebugDraw::DrawSolidPolygon(const b2Vec2* old_vertices, int vertexCount, const b2Color& color)
{
    if (vertexCount < 3) {
        //DASSERT(false && "invalid polygon");
        return;
    }

    int trisCount = vertexCount - 2;
    int indexCount = trisCount * 3;

    mTris.reserve(vertexCount, indexCount);
    ColorVertex* vb = mTris.vb.ptr();
    GLushort* ib = mTris.ib.ptr();
    GLsizei vbp0 = mTris.vb.pos;
    GLsizei vbp = vbp0;

    for (int i = 0; i < vertexCount; i++)
    {
        colorvertex(*vb++, old_vertices[i], color, 0.5f);
    }

    for (int i = 0; i < trisCount; ++i)
    {
        *ib++ = vbp0;
        *ib++ = vbp + 1;
        *ib++ = vbp + 2;
        ++vbp;
    }

    mTris.append(vertexCount, indexCount);

    DrawPolygon(old_vertices, vertexCount, color);
}

void Box2dDebugDraw::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color)
{
    const int vertexCount = 16;
    const int indexCount = vertexCount * 2;
    const float32 k_increment = 2.0f * b2_pi / (float32)vertexCount;
    float32 theta = 0.0f;

    mLines.reserve(vertexCount, indexCount);
    ColorVertex* vb = mLines.vb.ptr();
    GLushort* ib = mLines.ib.ptr();
    GLsizei vbp0 = mLines.vb.pos;
    GLsizei vbp = vbp0;

    for (int i = 0; i < vertexCount; i++)
    {
        b2Vec2 vert = center + radius * b2Vec2(cosf(theta), sinf(theta));
        theta += k_increment;
        colorvertex(*vb++, vert, color);
        *ib++ = vbp;
        *ib++ = vbp + 1;
        ++vbp;
    }

    *--ib = vbp0;
    mLines.append(vertexCount, indexCount);
}

void Box2dDebugDraw::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color)
{
    const int vertexCount = 16;
    const float32 k_increment = 2.0f * b2_pi / (float32)vertexCount;
    float32 theta = 0.0f;

    int trisCount = vertexCount - 2;
    int indexCount = trisCount * 3;

    mTris.reserve(vertexCount, indexCount);
    ColorVertex* vb = mTris.vb.ptr();
    GLushort* ib = mTris.ib.ptr();
    GLsizei vbp0 = mTris.vb.pos;
    GLsizei vbp = vbp0;

    for (int i = 0; i < vertexCount; i++)
    {
        b2Vec2 vert = center + radius * b2Vec2(cosf(theta), sinf(theta));
        theta += k_increment;
        colorvertex(*vb++, vert, color, 0.5f);
    }

    for (int i = 0; i < trisCount; ++i)
    {
        *ib++ = vbp0;
        *ib++ = vbp + 1;
        *ib++ = vbp + 2;
        ++vbp;
    }

    mTris.append(vertexCount, indexCount);

    DrawCircle(center, radius, color);
    DrawSegment(center, center + radius * axis, color);
}

void Box2dDebugDraw::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color)
{
    mLines.reserve(2, 2);
    ColorVertex* vb = mLines.vb.ptr();
    GLushort* ib = mLines.ib.ptr();
    GLsizei vbp0 = mLines.vb.pos;

    colorvertex(*vb++, p1, color);
    colorvertex(*vb++, p2, color);
    *ib++ = vbp0;
    *ib++ = vbp0 + 1;
    mLines.append(2, 2);
}

void Box2dDebugDraw::DrawTransform(const b2Transform& xf)
{
    const float32 k_axisScale = 0.5f;
    b2Vec2 p1 = xf.p;
    b2Vec2 p2 = p1 + k_axisScale * xf.q.GetXAxis();
    b2Vec2 p3 = p1 + k_axisScale * xf.q.GetYAxis();
    b2Color c1(1, 0, 0);
    b2Color c2(0, 1, 0);

    mLines.reserve(4, 4);
    ColorVertex* vb = mLines.vb.ptr();
    GLushort* ib = mLines.ib.ptr();
    GLsizei vbp0 = mLines.vb.pos;

    colorvertex(*vb++, p1, c1);
    colorvertex(*vb++, p2, c1);
    colorvertex(*vb++, p1, c2);
    colorvertex(*vb++, p3, c2);
    *ib++ = vbp0;
    *ib++ = vbp0 + 1;
    *ib++ = vbp0 + 2;
    *ib++ = vbp0 + 3;
    mLines.append(4, 4);
}

void Box2dDebugDraw::DrawAABB(b2AABB* aabb, const b2Color& color)
{
    b2Vec2 vert[4];
    vert[0].x = aabb->lowerBound.x;
    vert[0].y = aabb->lowerBound.y;
    vert[1].x = aabb->upperBound.x;
    vert[1].y = aabb->lowerBound.y;
    vert[2].x = aabb->upperBound.x;
    vert[2].y = aabb->upperBound.y;
    vert[3].x = aabb->lowerBound.x;
    vert[3].y = aabb->upperBound.y;
    DrawPolygon(vert, 4, color);
}

void Box2dDebugDraw::DrawPoint(const b2Vec2& p, float32 size, const b2Color& color)
{
    DrawCircle(p, 0.5f, color);
}

void Box2dDebugDraw::DrawString(int x, int y, const char *string, ...)
{
}