0
votes

I'm writing a small graphics engine in C++/OpenGL and have managed to load a model and render it on screen. However, parts of the mesh seem to be inverted, like normals facing into the wrong direction:

[Screenshot 1](http://www.directupload.net/file/d/3699/nnmhbxy2_png.htm)[Screenshot 2](http://www.directupload.net/file/d/3699/qirjviua_png.htm)

The shader I'm using for the screenshots looks like this (only fragment shader, vertex shader is supposed to be okay):

uniform float t;
uniform sampler2D tex;

varying vec2 v_texCoords;
varying vec3 v_normal;

void main()
{
   float zbuffer = gl_FragCoord.w * 10;
   gl_FragColor = vec4(zbuffer, zbuffer, zbuffer, 1.0);
}

So, basically, I'm rendering the objects distance to the camera to visualize what's wrong. I've used different models, procedural as well as pregenerated meshes in different file formats and it always turns out to look like that.

Don't know if that's important, but I'm using a VAO with one vertex buffer and 3 attributes (position, normal, uv).

I already enabled GL_DEPTH_TEST, my initialization routine looks like this:

/* Enable smooth shading */
glShadeModel( GL_SMOOTH);

/* Set the background black */
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

/* Depth buffer setup */
glClearDepth(1.0f);

/* Enables Depth Testing */
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);

/* The Type Of Depth Test To Do */
glDepthFunc( GL_LEQUAL );

/* Really Nice Perspective Calculations */
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

Am I doing something wrong here?

1
Assuming we are indeed talking z-buffer issues here (it's not that easy to tell from your screenshots, a simple spinning cube would have been clearer), are you (a) properly allocating one with your window (PixelFormatDescriptor!) and (b) properly cleaning it each frame in glClear? - Paul-Jan

1 Answers

0
votes

Give a try by changing

float zbuffer = gl_FragCoord.w * 10;

to

float zbuffer = (gl_FragCoord.z + 1)*0.5;

The z depth value is specified in the Z component of gl_FragCoord in NDC space, which is in [-1,1]. And then we need to remap it to [0,1] interval. That's why we need +1 and *0.5 here.