Skip to content

Instantly share code, notes, and snippets.

@galek
Forked from Novum/gist:1272928
Created May 7, 2016 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galek/d103a568c0b71fe5b74e42a7d4a28550 to your computer and use it in GitHub Desktop.
Save galek/d103a568c0b71fe5b74e42a7d4a28550 to your computer and use it in GitHub Desktop.
world position from depth buffer value
// Reconstruct worldspace depth value from z/w depth buffer
float depth = -(z_near * z_far) / (zbuffer_depth * (z_far - z_near) - z_far);
// Compute screenspace coordinate of pixel
float2 screenspace = (float2(pixel.xy) / float2(viewport_size.xy)) * 2.0f - 1.0f;
// Get direction of ray from camera through pixel
float3 ray_direction = normalize(camera_forward + camera_right * screenspace.x - camera_up * screenspace.y);
// Reconstruct world position from depth: depth in z buffer is distance to picture plane, not camera
float distance_to_camera = depth / dot(ray_direction, camera_forward);
float3 world_position = camera_position + ray_direction * distance_to_camera;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment