glDrawArrays Exception_Access_Violation

Jam*_*mes 2 java opengl

我试图在OpenGL和Java中使用vertexBufferObjects实现一个方法来绘制一堆立方体但是在调用glDrawArrays命令时遇到问题.

本程序的基本操作是循环通过x,y,z坐标,并从那里计算以该坐标为中心的立方体的顶点,然后将这些顶点输入浮点缓冲区.(注意我现在只输入一个面的顶点数据,以便在完美时保持代码简单)

发生的错误是:

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);
Run Code Online (Sandbox Code Playgroud)

Chr*_*ica 5

你的来电glVertexPointer是错的.它的第一个参数不是整个浮点数,而是单个顶点的浮点数(或更确切地说是组件),在你的情况下3.访问冲突的原因只是,glVertexPointer调用失败glDrawArrays然后使用默认参数,可能为每个顶点指定4个组件,或者不使用缓冲区对象或使用一些与顶点数据不匹配的其他未指定参数.所以只需替换它

glVertexPointer(3, GL_FLOAT, 0, 0L);
Run Code Online (Sandbox Code Playgroud)

变量名verticesPerObject有点误导,因为它不包含顶点数,但浮点数,但这仅仅是化妆品,其余的使用是正确的.