Reputation: 23
I am attempting to implement a method to draw a bunch of cubes using vertexBufferObjects in OpenGL and Java however am running into a problem when calling the glDrawArrays command.
Essentially what this program does is cycle through x, y, z coordinates and calculates from there where the vertices of a cube centered at that coordinate are and then enters these vertices to a float buffer. (Note I am only entering the vertex data for one face at the moment as to keep the code simple while it is perfected)
The error that occurs is:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006056ec90, pid=6424, tid=7696
int verticesPerObject = 12; //number of vertices per square
int chunkSizeX = 4; //number of cubes in x direction
int chunkSizeY = 4; //number of cubes in y direction
int chunkSizeZ = 4; //number of cubes in z direction
FloatBuffer vertexData = BufferUtils.createFloatBuffer(chunkSizeX * chunkSizeY * chunkSizeZ * verticesPerObject);
for (int x = 0; x < chunkSizeX; x++) {
for (int y = 0; y < chunkSizeY; y++) {
for (int z = 0; z < chunkSizeZ; z++) {
vertexData.put(new float[]{
(float)x * blockWidth - blockWidth/2, (float)y * blockHeight - blockHeight/2, (float)z * blockDepth + blockDepth/2,
(float)x * blockWidth + blockWidth/2, (float)y * blockHeight - blockHeight/2, (float)z * blockDepth + blockDepth/2,
(float)x * blockWidth + blockWidth/2, (float)y * blockHeight + blockHeight/2, (float)z * blockDepth + blockDepth/2,
(float)x * blockWidth - blockWidth/2, (float)y * blockHeight + blockHeight/2, (float)z * blockDepth + blockDepth/2
});
}
}
}
vertexData.flip();
int vboVertexHandle = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vboVertexHandle);
glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, vboVertexHandle);
glVertexPointer(verticesPerObject, GL_FLOAT, 0, 0L);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_QUADS, 0, verticesPerObject);
glDisableClientState(GL_VERTEX_ARRAY);
Upvotes: 2
Views: 1244
Reputation: 45948
Your call to glVertexPointer
is wrong. Its first parameter is not the number of overall floats, but the number of floats (or rather components) of a single vertex, in your case 3. The reason for the access violation is just, that the glVertexPointer
call fails and glDrawArrays
then uses the default parameters, which might specify 4 components per vertex, or not use your buffer object or use some other unspecified parameters not matching your vertex data. So just replace it by
glVertexPointer(3, GL_FLOAT, 0, 0L);
The variable name verticesPerObject
is a bit misleading anyway, since it doesn't contain the number of vertices, but the number of floats, but this is mere cosmetics, the rest of its usage is correct.
Upvotes: 5