Christopher Perry
Christopher Perry

Reputation: 39225

Generate a depth texture in OpenGL ES 2.0 or 3.0

I have a scene I'm rendering using OpenGL ES in Android (using the Java libs). I want to apply some effects such as depth of field to the scene. I found a nice bokeh shader, and it needs a depth texture to do the job. What I need then, is to generate a depth texture to pass to the shader. I've been poking around the internet for a day and a half trying to figure this out, and can't seem to find a good example of how to generate a depth texture from an existing scene. It seems I need to do several passes, probably using an off screen render to a frame buffer, then generate a depth texture from that to pass to my bokeh shader to actually render the scene.

How do you generate a depth texture? A good working example would be much appreciated.

Upvotes: 1

Views: 2995

Answers (2)

Joe Davis
Joe Davis

Reputation: 198

For any post processing effects, you will need to render your main scene to an FBO so colour and depth attachment data can be used in subsequent renders.

Rendering to a depth texture is very easy. You simply need to bind a depth texture to your FBO target, e.g.

glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depth_texture, 0);

The PowerVR SDK's RenderToTexture and ShadowMapping demos should have all the reference code you will need:

https://github.com/powervr-graphics/Native_SDK/blob/3.4/Examples/Intermediate/RenderToTexture/OGLES2/OGLES2RenderToTexture.cpp https://github.com/powervr-graphics/Native_SDK/blob/3.4/Examples/Intermediate/ShadowMapping/OGLES2/OGLES2ShadowMapping.cpp

Upvotes: 2

samgak
samgak

Reputation: 24417

You can access the per-pixel depth value from inside a fragment shader using gl_FragCoord. Write a fragment shader that writes the depth out to gl_FragColor, something like this:

gl_FragColor = vec4(gl_FragCoord.z, 0.0, 0.0, 1.0);

Render your scene to a texture using this fragment shader and you'll end up with a depth map.

Upvotes: 1

Related Questions