Search code examples
androidopengl-esopengl-es-2.0garbage

android opengl rendering garbage


I've been doing some simple shaders and Im encountering an error that happens randomly, when I start rendering my scene, sometimes the mesh is rendered with extra vectors, and if I kill the activity and then I open the same activity it renders sometimes without the extra vectors.

My guesses are that the memory on the GPU is not completely wiped out when I kill the activity. Whats more weird is that these extra polygons are rendered sometimes using my shader logic and other times they render as if they were filled with random squares.

Im going all crazy I've reviewed all the code, from where I read the obj, to where I set the vertex attributes, if you have been seen this before please let me know. BTW I'm using a motorola milestone with android 2.1.

This is the code related where I create a simple triangle and set the attributes of the vertices:

//This is where I create the mesh
mMesh = new Mesh();
mMesh.setVertices(new float[]{-0.5f, 0f, 0.5f, 
                               0.5f, 0f, -0.5f, 
                              -0.5f, 0f, -0.5f});

ArrayList<VertexAttribute> attributes = new ArrayList<VertexAttribute>();
attributes.add(new VertexAttribute(Usage.Position, 3, ProgramShader.POSITION_ATTRIBUTE));

VertexAttributes vertexAttributes = new VertexAttributes(attributes.toArray(new VertexAttribute[attributes.size()]));
mMesh.setVertexAttributes(vertexAttributes);

...
...
.......
//This is where I send the mesh to opengl
for(VertexAttribute attr :mVertexAttributes.getAttributes().values()){
   mVertexBuffer.position(attr.offset);
   int handler = shader.getHandler(attr.alias);
      if(handler != -1){
         try{
            GLES20.glVertexAttribPointer(handler, attr.numComponents, GLES20.GL_FLOAT, false, mVertexAttributes.vertexSize, mVertexBuffer);     
            GLES20.glEnableVertexAttribArray(handler);

         }catch (RuntimeException e) {
            Log.d("CG", attr.alias);
            throw e;
         }
      }
   }

//(length = 3 for a triangle)
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, length);

Here are some screenshots for you to see the issue:

Also here is a link to a video I took when I run the app on the phone.


Solution

  • So... I found the problem it was a really dumb thing I was doing,

    //on this line I was sending length, where length was
    //the length of the vertices for the triangle it was "9" (x,y,z for each vertex)
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, length);
    //I had to divide that by the number of components for each vertex
    //so when the vertex only has position attributes (x,y,z) is divided by 3
    //when you have more i.e. normals it will be divided by 6 (x,y,z, normalX, normalY, normalZ)
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, length/mVertexAttributes.vertexNumComponents);
    

    I hope this helps others.