OpenGL position from depth is wrong

Posted by CoffeeandCode on Game Development See other posts from Game Development or by CoffeeandCode
Published on 2013-11-04T11:57:45Z Indexed on 2013/11/04 16:13 UTC
Read the original article Hit count: 279

Filed under:
|
|
|
|

My engine is currently implemented using a deferred rendering technique, and today I decided to change it up a bit.

First I was storing 5 textures as so:

DEPTH24_STENCIL8 - Depth and stencil
RGBA32F - Position
RGBA10_A2 - Normals
RGBA8 x 2 - Specular & Diffuse

I decided to minimize it and reconstruct positions from the depth buffer. Trying to figure out what is wrong with my method currently has not been fun :/

Currently I get this:

wow such gross so depth

which changes whenever I move the camera... weird


Vertex shader

really simple

#version 150

layout(location = 0) in vec3 position;
layout(location = 1) in vec2 uv;

out vec2 uv_f;

void main(){
    uv_f = uv;
    gl_Position = vec4(position, 1.0);
}

Fragment shader

Where the fun (and not so fun) stuff happens

#version 150

uniform sampler2D depth_tex;
uniform sampler2D normal_tex;
uniform sampler2D diffuse_tex;
uniform sampler2D specular_tex;

uniform mat4 inv_proj_mat;
uniform vec2 nearz_farz;

in vec2 uv_f;

... other uniforms and such ...

layout(location = 3) out vec4 PostProcess;

vec3 reconstruct_pos(){
    float z = texture(depth_tex, uv_f).x;
    vec4 sPos = vec4(uv_f * 2.0 - 1.0, z, 1.0);
    sPos = inv_proj_mat * sPos;

    return (sPos.xyz / sPos.w);
}

void main(){
    vec3 pos = reconstruct_pos();
    vec3 normal = texture(normal_tex, uv_f).rgb;
    vec3 diffuse = texture(diffuse_tex, uv_f).rgb;
    vec4 specular = texture(specular_tex, uv_f);

    ... do lighting ...

    PostProcess = vec4(pos, 1.0); // Just for testing
}

Rendering code

probably nothing wrong here, seeing as though it always worked before

this->gbuffer->bind();
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);

gl::Enable(gl::DEPTH_TEST);
gl::Enable(gl::CULL_FACE);

... bind geometry shader and draw models and shiz ...

gl::Disable(gl::DEPTH_TEST);
gl::Disable(gl::CULL_FACE);
gl::Enable(gl::BLEND);

... bind textures and lighting shaders shown above then draw each light ...

gl::BindFramebuffer(gl::FRAMEBUFFER, 0);
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);

gl::Disable(gl::BLEND);

... bind screen shaders and draw quad with PostProcess texture ...

Rinse_and_repeat(); // not actually a function ;)

Why are my positions being output like they are?

© Game Development or respective owner

Related posts about opengl

Related posts about c++