clip(divide by w) -> screen space
Be careful, if you're really in screen space. My guess is, you're doing picking or deferred rendering, in which case you're probably reading fragments in Normalized Device Space (i.e. x and y in range [-1, 1]
*).
If so, you can do it like this:
Read out Normalized Device Coordinates as vec4
with depth as z value and 1.0
as w value and bring them into [0, 1]
range by multiplying by 2
and subtracting 1
.
Convert them into Eye Space with the inverted projection matrix.
Divide your new vector by its w
coordinate (which is your undivide step). Now you're in Eye Space.
There are more ways to do this, you can have a look at Reconstructing Position From Depth to dive further into how.
*I'm assuming OpenGL, ranges might be different in DirectX