Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to draw the depth buffer in the fragment shader, I do this:

Vertex shader:

varying vec4 position_;

gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
position_ = gl_ModelViewProjectionMatrix * gl_Vertex;

Fragment shader:

float depth = ((position_.z / position_.w) + 1.0) * 0.5;

gl_FragColor = vec4(depth, depth, depth, 1.0);

But all I print is white, what am I doing wrong?

share|improve this question
Do you want to draw depth buffer of rendered scene or draw scene objects with coloring based on pixel depth? – kravemir Jul 3 '12 at 9:01

position_.z shouldn't be larger than 1 or lower than 0. You should try to use linear depth for the display, which after applying the projection matrix is (usually) stored in the w coordinate instead. Take that, divide by an appropriate number (depending on the scale of your game) to bring the numbers between 0 and 1 for your interesting depth and watch.

gl_fragcoord is not relevant to this discussion; gl_fragdepth is an output variable to modify the post-projection depth in the pixel shader. You're not trying to do that, so don't use that either.

share|improve this answer

A cheesy way might be to set up some linear fog. Make the fog colour black, draw all your geometry white, and voila.

share|improve this answer
Nice idea for a fixed-function pipeline, never thought about that. – Christian Rau Aug 22 '11 at 12:15

Maybe you can try one of these two variables. gl_fragcoord or gl_fragdepth

I didn't read those manuals, but I think, it could be helpful.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.