Skip to content

Instantly share code, notes, and snippets.

@Novum
Created October 8, 2011 21:46
Show Gist options
  • Save Novum/1272928 to your computer and use it in GitHub Desktop.
Save Novum/1272928 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