Converting World Values to Depth Buffer Values

I need a way to convert world coordinates to depth buffer coordinates without just drawing something and reading the depth buffer. For some reason that doesn’t seem to be working for me. Is there some kind of formula?

There is even a function to help you: gluProject.

If you need the depth value as integer, take the resulting windows z-coordinate which should be in the 0.0 to 1.0 range (I think), and scale it with (2^number of depth bits)-1.

This will not be invariant with what implementations calculate internally due to different algorithms and precisions, but should come close.