Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy depth buffer to a texture on the GPU?

Tags:

opengl

glsl

depth

I want to get the current depth buffer to a texture, to access it in a shader. For various reasons I can't do a separate depth pass, but would need to copy the already-rendered depth.

glReadPixels would involve the CPU and potentially kill performance, and as far as I know glBlitFramebuffer can't blit depth-to-color, only depth-to-depth.

How to do this on the GPU?

like image 526
Anon Avatar asked Jun 14 '11 08:06

Anon


2 Answers

The modern way of doing this would be to use a FBO. Attach a color and depth texture to it, render, then disable the FBO and use the textures as inputs to a shader that will render to the default framebuffer.

All the details you need about FBO can be found here.

like image 114
Nicolas Lefebvre Avatar answered Sep 23 '22 03:09

Nicolas Lefebvre


Copying the depth buffer to a texture is pretty simple. If you have created a new texture that you haven't called glTexImage* on, you can use glCopyTexImage2D. This will copy pixels from the framebuffer to the texture. To copy depth pixels, you use a GL_DEPTH_COMPONENT format. I'd suggest GL_DEPTH_COMPONENT24.

If you have previously created a texture with a depth component format (ie: anytime after the first frame), then you can copy directly into this image data with glCopyTexSubImage2D.

It also seems as though you're having trouble accessing depth component textures in your shader, since you want to copy depth-to-color (which is not allowed). If you are, then that is a problem you should get fixed.

In any case, copying should be the method of last resort. You should use framebuffer objects whenever possible. Just render directly to your texture.

like image 24
Nicol Bolas Avatar answered Sep 22 '22 03:09

Nicol Bolas