glReadPixels 导致崩溃

glReadPixels causing crash

我有一个可以在显示器上渲染的 3d 场景。但是,除了渲染它以显示之外,我还希望能够将渲染的场景导出为图像(比如每 100 帧一次)(比如 JPG 或 PNG 图像),也许将其保存为文件保存在我的某个地方机.

do{
    glfwPollEvents();
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffername);
    drawScene();
    glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices.size());
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
    image = (GLuint*)malloc(windowWidth * windowHeight);
    glReadPixels(0, 0, windowWidth, windowHeight, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, &image);
    free(image);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    drawScene();
    glfwSwapBuffers(window);
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
       glfwWindowShouldClose(window) == 0 );

我想做的是将我的场景同时渲染到显示器和我定义的帧缓冲区对象。上面的崩溃并给了我一个奇怪的 Visual Studio 错误:"ig75icd64.pdb not loaded"。但是如果我注释掉这一行:

glReadPixels(0, 0, windowWidth, windowHeight, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, &image);

然后程序不会崩溃,并且会正确呈现到显示器(但我希望能够使用 glReadPixels 写入 2d 纹理)。我的最终目标是能够将显示导出为格式化图像,以便以后进行图像处理。

建议?

正如Derhass所说,你需要传递指针,而不是指针的地址。

此代码(技术上)有效:

image = (GLuint*)malloc(windowWidth * windowHeight * sizeof(GLuint)); //Need to make it large enough!
glReadPixels(0, 0, windowWidth, windowHeight, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, image); //Note we're not taking the address of image
free(image);

以下代码会更安全,并且是全面更好的代码(假设您使用的是 C++,您对 vertices.size() 的调用似乎暗示了这一点):

std::vector<GLuint> image(windowWidth * windowHeight);
glReadPixels(0, 0, windowWidth, windowHeight, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, image.data());

另一个考虑因素:glfwCreateWindow(windowWidth, windowHeight, "Dragon!", nullptr, nullptr); 根据提供的宽度和高度创建一个 window,但 [=23= 的实际大小]Framebuffer(window 中实际发生渲染的部分)可能不同(通常较小),尤其是当 window 可由用户调整大小时。在尝试调整大小之前,您应该查询 Framebuffer 的大小:

do {
    glfwPollEvents();
    int fbwidth, fbheight;
    glfwGetFramebufferSize(window, &fbwidth, &fbheight);
    //use fbwidth and fbheight in all code that needs the size of the rendered image
    /*...*/
while(/*...*/);