I've been struggling with OpenGL's Z-Buffer, i can't get it to work. This is the code (i narrowed it down to the minimum necessary to show the problem):
#include <stdio.h>
#include <stdlib.h>
#include <glad\glad.h>
#include <SFML\Graphics.hpp>
#define WIDTH 800
#define HEIGHT 600
int main(void) {
sf::ContextSettings settings;
settings.antialiasingLevel = 16;
settings.majorVersion = 4;
settings.minorVersion = 6;
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Test", sf::Style::Close, settings);
if (!gladLoadGL()) {
printf("COULD NOT INITALIZE OPENGL CONTEXT\n");
}
window.setActive(true);
window.setVerticalSyncEnabled(true);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f); // red
glVertex3f(-1.0f, -1.0f, 0.25f); // first triangle
glVertex3f( 1.0f, -1.0f, 0.25f);
glVertex3f( 0.0f, 1.0f, 0.25f);
glColor3f(0.0f, 0.0f, 1.0f); // blue
glVertex3f(-1.0f, 1.0f, 0.5f); // second triangle
glVertex3f( 1.0f, 1.0f, 0.5f);
glVertex3f( 0.0f, -1.0f, 0.5f);
glEnd();
window.display();
}
return(0);
}
The blue triangle is on top of the red one cause i drawed it for second, even though it should stay behind. I first noticed this behaviour on my main OpenGL project where i would import 3D models and i would have triangles being rendered in front of others, suggesting that the Z-Buffer was not doing its thing. I tried many solutions, such as enabling GL_CULL_FACE, playing around with the near plane from the projection matrix (on the 3d project), but nothing seems to work. Every fix i found online that works for almost everyone doesn't seem to work for me, so i'm kind of desperate... If anyone knows the issue let me know!