Search code examples
javaopengllwjglopengl-compat

Is this an efficient way of rendering tiles with OpenGL?


This is the routine I use for rendering the tiles

    private static void renderTile(int x1, int y1, int size) {
        glBegin(GL_TRIANGLES);

        double halfSize = size/2;

        glVertex2d(x1 + halfSize, y1 + halfSize);
        glVertex2d(x1 + halfSize, y1 - halfSize);
        glVertex2d(x1 - halfSize, y1 - halfSize);

        glVertex2d(x1 - halfSize, y1 - halfSize);
        glVertex2d(x1 - halfSize, y1 + halfSize);
        glVertex2d(x1 + halfSize, y1 + halfSize);
        glEnd();
    }

Now, the routine works, but, it looks a bit messy. Is there a better way to do this with Java OpenGL + LWJGL?


Solution

  • Your code in old GL has major problems:

    • computing the coordinates inside glBegin/glEnd
    • mixing double and int forcing costly conversion between types
    • not using vectors
    • expensive primitive
    • using double

    Much faster would be to use glVertex2dv and precompute the coordinates once into some table (sadly your current api does not support static table that would require change in your app architecture). From that its a simple small leap into VBO usage btw. Also doubles are usually wasted in old GL as the interpolators are 32bit anyways (even on new HW). So to optimize I would convert your code to something like this (sorry not a JAVA coder I code in C++ so it might be syntacticaly incorrect):

    private static void renderTile(float x, float y, float size) 
        {
        const float  a = 0.5*size;
        const float p[4*2]= 
            {
            x-a,y-a,
            x+a,y-a,
            x+a,y+a,
            x-a,y+a,
            };
    
        glBegin(GL_QUADS);
        glVertex2fv(p); p+=2;
        glVertex2fv(p); p+=2;
        glVertex2fv(p); p+=2;
        glVertex2fv(p); p+=2;
        glEnd();
        }
    

    However if you want true power then use VBO. See