Opengl4.0中可以进行离屏渲染,即创造一个帧缓存对象(FBO),绑定一个帧缓存对象后,所有对Op--engl的操作都会针对这个帧缓存对象执行。而最近做项目时,在做一个拍照功能——读取Opengl渲染出的像素,并存入到BMP位图中。项目采用的是Opengl1.0和Opengl4.3结合的方法,并且两者的使用相对独立。使用旧的Opengl方法运行程序时,通过 glReadBuffer(GL_FRONT);//指定要读取的缓存 glReadPixels(0, 0, width, height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, (unsigned char*)imageData); 即可读取到像素,并保存起来。 但是,一旦使用Opengl4.3进行离屏渲染后,发现glReadBuffer()和glReadPixels()不能再读取到像素,于是我对每一部分使用Opengl4.3的代码都做了glGetError()检测,发现使用Opengl4.3的代码部分并没有调用错误,所以就一直查不出来问题在哪里。最后我想会不会是Opengl绑定的问题,终于发现Opengl4.3使用离屏渲染后没有解绑帧缓存,即: glBindFramebuffer(GL_FRAMEBUFFER, GL_NONE); 于是我去查了www.khronos.org/关于glBindFramebuffer的定义: While a non-zero framebuffer object name is bound, all rendering to the framebuffer (with glDrawArrays and glDrawElements) and reading from the framebuffer (with glReadPixels, glCopyTexImage2D, or glCopyTexSubImage2D) use the images attached to the application-created framebuffer object rather than the default window-system-provided framebuffer. Application created framebuffer objects (i.e. those with a non-zero name) differ from the default window-system-provided framebufferin a few important ways. First, they have modifiable attachment points for a color buffer, a depth buffer, and a stencil buffer to which framebuffer attachable images may be attached and detached. Second, the size and format of the attached images are controlled entirely within the GL and are not affected by window-system events, such as pixel format selection, window resizes, and display mode changes. Third, when rendering to or reading from an application created framebuffer object, the pixel ownership test always succeeds (i.e. they own all their pixels).Fourth, there are no visible color buffer bitplanes, only a single "off-screen" color image attachment, so there is no sense of front and back buffers or swapping. Finally, there is no multisample buffer, so the value of the implementation-dependent state variablesGL_SAMPLES
andGL_SAMPLE_BUFFERS
are both zero for application created framebuffer objects. 也就是说,使用glBindFramebuffer()进行离屏渲染时,Opengl的渲染和读取都是通过attached的纹理对帧缓存进行操作的,不再是对windows系统提供的默认帧缓存进行操作,所以我们见到的屏幕上显示出来的图像并不是一个可见的颜色缓存位面(visible color buffer bitplane),只不过是一个“离屏”的颜色纹理("off-screen" color image attachment),所以双缓存就不起作用了(即使调用swapbuffer(),像素也不会被渲染到前后缓存中),所以glReadBuffer(GL_FRONT);也就读取不出像素出来。 这个Bug前后找了将近两个星期,在这里Mark一下,说白了还是对Opengl理解不够,Opengl的使用个人感觉比较晦涩,还需要好好研究。希望对大家有所帮助。 格式一直调不好。。好吧。。
时间: 2024-11-19 16:13:02