javaopengllibgdxterrainvertex-array

Problems with making 2D terrain in OpenGL


Some time ago I asked this question about how to make a 2D terrain with opengl vertices. I got a good answer, but when trying it out it didn't draw anything, and I can't figure out what's wrong, or how to fix it.

I have this now :

public class Terrain extends Actor {

Mesh mesh;
private final int LENGTH = 1500; //length of the whole terrain

public Terrain(int res) {

    Random r = new Random();

    //res (resolution) is the number of height-points 
    //minimum is 2, which will result in a box (under each height-point there is another vertex)
    if (res < 2)
        res = 2;

    mesh = new Mesh(VertexDataType.VertexArray, true, 2 * res, 50, new VertexAttribute(Usage.Position, 2, "a_position")); 

    float x = 0f;     //current position to put vertices
    float med = 100f; //starting y
    float y = med;

    float slopeWidth = (float) (LENGTH / ((float) (res - 1))); //horizontal distance between 2 heightpoints


    // VERTICES
    float[] tempVer = new float[2*2*res]; //hold vertices before setting them to the mesh
    int offset = 0; //offset to put it in tempVer

    for (int i = 0; i<res; i++) {

        tempVer[offset+0] = x;      tempVer[offset+1] = 0f; // below height
        tempVer[offset+2] = x;      tempVer[offset+3] = y;  // height

        //next position: 
        x += slopeWidth;
        y += (r.nextFloat() - 0.5f) * 50;
        offset +=4;
    }
    mesh.setVertices(tempVer);


    // INDICES
    short[] tempIn = new short[(res-1)*6];
    offset = 0;
    for (int i = 0; i<res; i+=2) {

        tempIn[offset + 0] = (short) (i);       // below height
        tempIn[offset + 1] = (short) (i + 2);   // below next height
        tempIn[offset + 2] = (short) (i + 1);   // height

        tempIn[offset + 3] = (short) (i + 1);   // height
        tempIn[offset + 4] = (short) (i + 2);   // below next height
        tempIn[offset + 5] = (short) (i + 3);   // next height

        offset+=6;
    }
}

@Override
public void draw(SpriteBatch batch, float delta) {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    mesh.render(GL10.GL_TRIANGLES);
}

This is being rendered by Libgdx, which also provides the class Mesh, but this is not really relevant since I believe that works fine. My problems lay by the vertex and indices generation. I don't really know how to debug it either, so could anyone please look at it, and help me to find why nothing is being rendered?


Solution

  • After a full day has passed, and I have tried everything to solve it, it seemed I forgot to actually set the indices to the mesh.

    mesh.setIndices(tempIn);  
    

    One missing line, hours of pain... i'm an idiot :)