2017-10-08 166 views
0

我正在使用LWJGL向渲染缓冲区的屏幕外帧缓冲区渲染三角形。渲染场景后,我使用glReadPixels将渲染缓冲区中的数据读出到RAM中。前几帧很好,但程序崩溃了(SEGFAULT,或SIGABRT,...)。几帧后,LWJGL在glReadPixels上崩溃

我在这里做错了什么?

//Create memory buffer in RAM to copy frame from GPU to. 
ByteBuffer buf = BufferUtils.createByteBuffer(3*width*height); 

while(true){ 
    // Set framebuffer, clear screen, render objects, wait for render to finish, ... 
    ... 

    //Read frame from GPU to RAM 
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buf); 

    //Move cursor in buffer back to the begin and copy the contents to the java image 
    buf.position(0); 
    buf.get(imgBackingByteArray); 

    //Use buffer 
    ... 
} 

回答

0
使用

glReadPixelsByteBuffer.get(),或基本上以任何方式访问的ByteBuffer,改变指针在缓冲器中的当前位置。

这里发生的是:

  1. 缓冲区的位置最初为零。
  2. 呼叫到glReadPixels拷贝从GPU到缓冲区中,从当前位置被改变到被写入到缓冲器的字节量的当前位置(= 0
  3. 字节。
  4. buf.position(0)的位置为0。
  5. buf.get()拷贝在缓冲器中的字节复位到imgBackingByteArray并且改变位置以所读取的字节量
  6. 循环的下一次迭代尝试将字节读入缓冲区,但当前位置在缓冲区的末尾,因此发生缓冲区溢出。这会触发崩溃。

解决方案:

//Make sure we start writing to the buffer at offset 0 
buf.position(0); 
//Read frame from GPU to RAM 
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buf); 

//Move cursor in buffer back to the begin and copy the contents to the java image 
buf.position(0); 
buf.get(imgBackingByteArray);