Cannot seem to get GLFW/OpenGL Depth Testing working - opengl

I cannot get Depth testing working with GLFW using codeblocks in any project, even using the default template provided by codeblocks when you start a new project, as below.
Any help is much appreciated as I know I must be doing something wrong but I haven't been able to find it.
#include <GL/glfw.h>
int main()
{
int width, height;
int frame = 0;
bool running = true;
glfwInit();
if( !glfwOpenWindow( 512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW ) )
{
glfwTerminate();
return 0;
}
glfwSetWindowTitle("GLFW Application");
glEnable(GL_DEPTH_TEST);
while(running)
{
frame++;
glfwGetWindowSize( &width, &height );
height = height > 0 ? height : 1;
glViewport( 0, 0, width, height );
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 65.0f, (GLfloat)width/(GLfloat)height, 1.0f, 100.0f );
// Draw some rotating garbage
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt(0.0f, -10.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f );
//glTranslatef( 1.0f, 1.0f, 0.0f );
glRotatef(frame, 0.25f, 1.0f, 0.75f);
glBegin( GL_TRIANGLES );
glColor3f(0.1f, 0.0f, 0.0f );
glVertex3f(0.0f, 3.0f, -4.0f);
glColor3f(0.0f, 1.0f, 0.0f );
glVertex3f(3.0f, -2.0f, -4.0f);
glColor3f(0.0f, 0.0f, 1.0f );
glVertex3f(-3.0f, -2.0f, -4.0f);
glEnd();
glBegin( GL_TRIANGLES );
glColor3f(0.0f, 0.1f, 0.0f );
glVertex3f(0.0f, 3.0f, -3.0f);
glColor3f(0.0f, 0.0f, 1.0f );
glVertex3f(3.0f, -2.0f, -2.0f);
glColor3f(1.0f, 0.0f, 0.0f );
glVertex3f(-3.0f, -2.0f, 2.0f);
glEnd();
glfwSwapBuffers();
// exit if ESC was pressed or window was closed
running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam( GLFW_OPENED);
}
glfwTerminate();
return 0;
}

From the GLFW2 documentation (emphasis mine):
int glfwOpenWindow
(
int width, int height,
int redbits, int greenbits, int bluebits,
int alphabits,
int depthbits,
int stencilbits,
int mode
)
depthbits: The number of bits to use for the depth buffer (0 means no depth buffer).
And your code:
glfwOpenWindow( 512, 512, 0, 0, 0, 0, 0, 0, GLFW_WINDOW )
^ no depth bits
You can't (usefully) use the depth buffer without any depth bits.

Related

C++ OpenGL texture not rendering as it should

I've successfully got some triangles to show up on screen together with some textures and a couple of event listeners. However, my texture is not rendering properly, it seems like pixels between 0 and 255 in brightness gets disorted while completely black/white pixels are rendering as they should. <- This might not be the best description but I will provide an example below.
This is the texture I'm trying to map onto my two triangles at the moment:
Here is the result after compiling and running the program:
What I think is that it may have something to do with the shaders, at the moment I do not have any shaders activated, neither vertex nor fragment shaders. I don't know if this is the problem but it might be a clue to it all.
Below is my main.cpp:
#include <iostream>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysymdef.h>
#include <GL/glx.h>
#include <GL/gl.h>
// #include <GL/glut.h>
// #include <GL/glu.h>
#include <sys/time.h>
#include <unistd.h>
#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 800
#define FPS 30
uint8_t shutdown = 0;
#define SKIP_TICKS ( 1000 / FPS )
// macros
void Render( void );
void HandleEvents( XEvent ev );
void Resize( int w, int h );
void Shutdown( void );
void fill_triangle_buffer( void );
struct triangle {
float color[ 3 ];
float p1[ 3 ];
float p2[ 3 ];
float p3[ 3 ];
};
struct triangle triangles[ 12 ];
static double GetMilliseconds() {
static timeval s_tTimeVal;
gettimeofday(&s_tTimeVal, NULL);
double time = s_tTimeVal.tv_sec * 1000.0; // sec to ms
time += s_tTimeVal.tv_usec / 1000.0; // us to ms
return time;
}
GLuint loadBMP_custom( const char * imagepath ) {
// Data read from the header of the BMP file
unsigned char header[54]; // Each BMP file begins by a 54-bytes header
unsigned int dataPos; // Position in the file where the actual data begins
unsigned int width, height;
unsigned int imageSize; // = width*height*3
// Actual RGB data
unsigned char * data;
// Open the file
FILE * file = fopen(imagepath,"rb");
if (!file) {
printf("Image could not be opened\n");
return 0;
}
if ( fread(header, 1, 54, file)!=54 ){ // If not 54 bytes read : problem
printf("Not a correct BMP file\n");
return false;
}
if ( header[0]!='B' || header[1]!='M' ){
printf("Not a correct BMP file\n");
return 0;
}
// Read ints from the byte array
dataPos = *(int*)&(header[0x0A]);
imageSize = *(int*)&(header[0x22]);
width = *(int*)&(header[0x12]);
height = *(int*)&(header[0x16]);
// Some BMP files are misformatted, guess missing information
if (imageSize==0)
imageSize=width*height*3; // 3 : one byte for each Red, Green and Blue component
if (dataPos==0)
dataPos=54; // The BMP header is done that way
// Create a buffer
data = new unsigned char [imageSize];
// Read the actual data from the file into the buffer
fread(data,1,imageSize,file);
//Everything is in memory now, the file can be closed
fclose(file);
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// return GLuint
return textureID;
}
int main (int argc, char ** argv){
Display *dpy = XOpenDisplay(0);
Window win;
XEvent ev;
int nelements;
GLXFBConfig *fbc = glXChooseFBConfig(dpy, DefaultScreen(dpy), 0, &nelements);
static int attributeList[] = { GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, None };
XVisualInfo *vi = glXChooseVisual(dpy, DefaultScreen(dpy),attributeList);
// Set Window attributes
XSetWindowAttributes swa;
swa.colormap = XCreateColormap(dpy, RootWindow(dpy, vi->screen), vi->visual, AllocNone);
swa.border_pixel = 0;
swa.event_mask = StructureNotifyMask;
win = XCreateWindow(dpy, RootWindow(dpy, vi->screen), 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa);
// Select window inputs to be triggered in the eventlistener
XSelectInput( dpy, win, PointerMotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask );
XMapWindow (dpy, win);
//oldstyle context:
// GLXContext ctx = glXCreateContext(dpy, vi, 0, GL_TRUE);
std::cout << "glXCreateContextAttribsARB " << (void*) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB") << std::endl;
GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
int attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 0,
0};
// Redirect Close
Atom atomWmDeleteWindow = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(dpy, win, &atomWmDeleteWindow, 1);
// Create GLX OpenGL context
GLXContext ctx = glXCreateContextAttribsARB(dpy, *fbc, 0, true, attribs);
glXMakeCurrent( dpy, win, ctx );
glMatrixMode( GL_PROJECTION );
glEnable( GL_CULL_FACE );
glCullFace( GL_FRONT );
glFrustum( -1, 1, 1, -1, -1, 1 );
glClearColor (0, 0.5, 1, 1);
glClear (GL_COLOR_BUFFER_BIT);
glXSwapBuffers (dpy, win);
fill_triangle_buffer();
// Load and bind texture
glEnable(GL_TEXTURE_2D);
loadBMP_custom("textures/texture.bmp");
// prepare gameloop
double prevTime = GetMilliseconds();
double currentTime = GetMilliseconds();
double deltaTime = 0.0;
timeval time;
long sleepTime = 0;
gettimeofday(&time, NULL);
long nextGameTick = (time.tv_sec * 1000) + (time.tv_usec / 1000);
while ( shutdown != 1 ) {
// Get events if there is any
if (XPending(dpy) > 0) {
XNextEvent(dpy, &ev);
if (ev.type == Expose) {
XWindowAttributes attribs;
XGetWindowAttributes(dpy, win, &attribs);
Resize(attribs.width, attribs.height);
}
if (ev.type == ClientMessage) {
if (ev.xclient.data.l[0] == atomWmDeleteWindow) {
break;
}
}
else if (ev.type == DestroyNotify) {
break;
}
}
// Framelimit calculations, before heavy load
currentTime = GetMilliseconds();
deltaTime = double( currentTime - prevTime ) * 0.001;
prevTime = currentTime;
// Do work
HandleEvents( ev );
//Render();
glClear( GL_COLOR_BUFFER_BIT );
glBegin(GL_TRIANGLES);
glColor3f( 255, 255, 255 );
/*
glTexCoord2f( 0.0f, 1.0f );
glVertex3f( -0.5f, 0.5f, 0.0f );
glTexCoord2f( 1.0f, 1.0f );
glVertex3f( 0.5f, 0.5f, 0.0f );
glTexCoord2f( 0.0f, 0.0f );
glVertex3f( -0.5f, -0.5f, 0.0f );
glVertex3f( 0.5f, 0.5f, 0.0f );
glTexCoord2f( 1.0f, 0.0f );
glVertex3f( 0.5f, -0.5f, 0.0f );
glVertex3f( -0.5f, -0.5f, 0.0f );
*/
// first triangle, bottom left half
glTexCoord2f( 0.0f, 0.0f ); glVertex3f( -0.5f, -0.5f, 0 );
glTexCoord2f( 0.0f, 1.0f ); glVertex3f( -0.5f, 0.5f, 0 );
glTexCoord2f( 1.0f, 0.0f ); glVertex3f( 0.5f, -0.5f, 0 );
// second triangle, top right half
glTexCoord2f( 1.0f, 0.0f ); glVertex3f( 0.5f, -0.5f, 0 );
glTexCoord2f( 0.0f, 1.0f ); glVertex3f( -0.5f, 0.5f, 0 );
glTexCoord2f( 1.0f, 1.0f ); glVertex3f( 0.5f, 0.5f, 0 );
glEnd();
glFlush();
glXSwapBuffers( dpy, win );
// Limit Framerate
gettimeofday( &time, NULL );
nextGameTick += SKIP_TICKS;
sleepTime = nextGameTick - ( (time.tv_sec * 1000) + (time.tv_usec / 1000) );
usleep((unsigned int)(sleepTime/1000));
}
ctx = glXGetCurrentContext();
glXDestroyContext(dpy, ctx);
}
void fill_triangle_buffer( void ){
triangles[ 0 ] = {
{ 1.0f, 0.0f, 0.0f },
{ -0.5f, -0.5f, -0.5f },
{ 0.5f, 0.5f, -0.5f },
{ 0.5f, -0.5f, -0.5f } };
triangles[ 1 ] = {
{ 0.0f, 0.0f, 1.0f },
{ -0.5f, -0.5f, -0.5f },
{ -0.5f, 0.5f, -0.5f },
{ 0.5f, 0.5f, -0.5f } };
triangles[ 2 ] = {
{ 0.0f, 0.0f, 1.0f },
{ 0.5f, 0.5f, -0.5f },
{ 0.5f, -0.5f, 0.5f },
{ 0.5f, -0.5f, -0.5f } };
triangles[ 3 ] = {
{ 1.0f, 1.0f, 0.0f },
{ 0.5f, 0.5f, -0.5f },
{ 0.5f, 0.5f, 0.5f },
{ 0.5f, -0.5f, 0.5f } };
triangles[ 4 ] = {
{ 1.0f, 0.0f, 0.0f },
{ -0.5f, -0.5f, 0.5f },
{ 0.5f, -0.5f, 0.5f },
{ -0.5f, 0.5f, 0.5f } };
triangles[ 5 ] = {
{ 0.0f, 0.0f, 1.0f },
{ 0.5f, -0.5f, 0.5f },
{ 0.5f, 0.5f, 0.5f },
{ -0.5f, 0.5f, 0.5f } };
triangles[ 6 ] = {
{ 0.0f, 0.0f, 1.0f },
{ -0.5f, 0.5f, -0.5f },
{ -0.5f, -0.5f, 0.5f },
{ -0.5f, 0.5f, 0.5f } };
triangles[ 7 ] = {
{ 1.0f, 1.0f, 0.0f },
{ -0.5f, 0.5f, -0.5f },
{ -0.5f, -0.5f, -0.5f },
{ -0.5f, -0.5f, 0.5f } };
triangles[ 8 ] = {
{ 1.0f, 0.0f, 0.0f },
{ -0.5f, 0.5f, -0.5f },
{ -0.5f, 0.5f, 0.5f },
{ 0.5f, 0.5f, 0.5f } };
triangles[ 9 ] = {
{ 0.0f, 0.0f, 1.0f },
{ -0.5f, 0.5f, -0.5f },
{ 0.5f, 0.5f, 0.5f },
{ 0.5f, 0.5f, -0.5f } };
triangles[ 10 ] = {
{ 0.0f, 0.0f, 1.0f },
{ 0.5f, -0.5f, -0.5f },
{ 0.5f, -0.5f, 0.5f },
{ -0.5f, -0.5f, 0.5f } };
triangles[ 11 ] = {
{ 1.0f, 1.0f, 0.0f },
{ 0.5f, -0.5f, -0.5f },
{ -0.5f, -0.5f, 0.5f },
{ -0.5f, -0.5f, -0.5f } };
}
void Resize(int w, int h) {
glViewport(0, 0, w, h);
}
void Shutdown() {
shutdown = 1;
}
void Render( void ) {
glClearColor ( 1.0f, 1.0f, 1.0f, 1 );
glClear( GL_COLOR_BUFFER_BIT );
glBegin(GL_TRIANGLES);
/*glColor3f( 0.0f, 1.0f, 0.0f );
glVertex3f( test_cnt, 0.0f, 1.0f );
glVertex3f( 1.0f, 0.0f, 1.0f );
glVertex3f( 0.0f, -1.0f, 1.0f );
*/
int numTriangles = sizeof(triangles)/sizeof(triangles[0]);
for ( int i = 0; i < numTriangles; i++ ) {
glClear( GL_COLOR_BUFFER_BIT );
glBegin(GL_TRIANGLES);
struct triangle tr = triangles[ i ];
glColor3f( tr.color[ 0 ], tr.color[ 1 ], tr.color[ 2 ] );
glVertex3f( tr.p1[ 0 ], tr.p1[ 1 ], tr.p1[ 2 ] );
glVertex3f( tr.p2[ 0 ], tr.p2[ 1 ], tr.p2[ 2 ] );
glVertex3f( tr.p3[ 0 ], tr.p3[ 1 ], tr.p3[ 2 ] );
}
glEnd();
glFlush();
}
float dx, dy;
float prevx, prevy;
uint8_t prev_defined = 0;
uint8_t key_down = 0;
void HandleEvents( XEvent ev ) {
int x, y;
switch ( ev.type ) {
case ButtonPress:
if ( ev.xbutton.button == 1 ) {
std::cout << "Left mouse down \n";
// glRotatef( 0.01, 0.0, 0.0, 1.0 );
if ( key_down == 0 )
prev_defined = 0;
key_down = 1;
}
break;
case ButtonRelease:
if ( ev.xbutton.button == 1 ) {
std::cout << "Left mouse up \n";
key_down = 0;
}
break;
case KeyPress:
if ( ev.xkey.keycode == 9 ) { // ESC
Shutdown();
}
break;
case MotionNotify:
x = ev.xmotion.x;
y = ev.xmotion.y;
if ( key_down == 0 )
break;
if ( !prev_defined ) {
prevx = x;
prevy = y;
prev_defined = 1;
break;
}
dx = x - prevx;
dy = y - prevy;
prevx = x;
prevy = y;
glRotatef( -dy/10, 1.0f, 0.0f, 0.0f );
glRotatef( -dx/10, 0.0f, 1.0f, 0.0f );
//std::cout << "Mouse X:" << x << ", Y: " << y << "\n";
break;
}
}
I compile with:
g++ -g -Wall -o _build/main main.cpp -I/opt/x11/include -L/usr/x11/lib -lglfw -lGLEW -lGL -lX11
OS:
Linux kali 5.9.0-kali4-amd64 #1 SMP Debian 5.9.11-1kali1 (2020-12-01) x86_64 GNU/Linux
Do anyone know how to resolve this issue in order to completely show above texture on my triangles?

opengl cube won't render

I'm trying to draw a cube on OpenGL.
When I compile and run this code, all I see is a black window. Which part of my
code causes this problem? Any help would be appreciated as I am very new to opengl
Here is my source file:
#include <GL/glew.h>
#include <GL/glfw.h>
#include <iostream>
#include <cmath>
void drawCube() {
//vertices of the triangle
GLfloat vertices[] = {
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f
};
//colors of the triangle
GLfloat colors[] = {
0.410f, 0.481f, 0.675f,
0.177f, 0.823f, 0.970f,
0.604f, 0.516f, 0.611f,
0.676f, 0.779f, 0.331f,
0.179f, 0.275f, 0.338f,
0.041f, 0.616f, 0.984f,
0.799f, 0.315f, 0.460f,
0.945f, 0.719f, 0.295f
};
static float alpha = 0;
//attempt to rotate cube
glRotatef(alpha, 0, 1, 0);
/* We have a color array and a vertex array */
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3, GL_FLOAT, 0, colors);
/* Send data : 24 vertices */
glDrawArrays(GL_TRIANGLES, 0, 24);
/* Cleanup states */
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
alpha += 1;
};
int main() {
if (!glfwInit()) {
std::cerr << "Unable to initialize OpenGL!\n";
return -1;
}
if (!glfwOpenWindow(1024, 768, //width and height of the screen
8, 8, 8, 0, //Red, Green, Blue and Alpha bits
0, 0, //Depth and Stencil bits
GLFW_WINDOW)) {
std::cerr << "Unable to create OpenGL window.\n";
glfwTerminate();
return -1;
}
glfwSetWindowTitle("GLFW Simple Example");
// Ensure we can capture the escape key being pressed below
glfwEnable(GLFW_STICKY_KEYS);
do {
GLint width, height;
// Get window size (may be different than the requested size)
//we do this every frame to accommodate window resizing.
glfwGetWindowSize(&width, &height);
glViewport(0, 0, width, height);
glEnable(GL_DEPTH_TEST); // Depth Testing
glDepthFunc(GL_LEQUAL);
glDisable(GL_CULL_FACE);
glCullFace(GL_BACK);
glfwSwapInterval(1);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW_MATRIX);
glTranslatef(0, 0, -5);
gluPerspective(60, (double)width / (double)height, 0.1, 100);
drawCube();
//VERY IMPORTANT: displays the buffer to the screen
glfwSwapBuffers();
} while (glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS &&
glfwGetWindowParam(GLFW_OPENED));
glfwTerminate();
return 0;
}
The problem is that you don't use a perspective projection, so you are basically seeing one face of the cube in an orthogonal view.
To use perspective, you can use gluPerspective:
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadIdentity();
gluPerspective(60, (double)width / (double)height, 0.1, 100); // Set up perspective matrix.

Overlaping rectangels and clipping at the bottom in opengl

I have to make some 3D figures using opengl (the older versions). I created 3 GL_POLYGON rectangles that are connected to one another and which have different colors.
My problem is that when the figure rotates the last color added (last added rectangle) is always above the other ones. For example the cyan one is above the pink and the yellow one, and the pink one is above the yellow one. I also noted some clipping at the bottom of the figure, which I think is caused by gluPerspective(). What I'm trying to achieve is having the eye look from z+ to the center and the figure rotating around the y+ axis ( which I think I managed to do) and also to have the overlapping and clipping removed.
Any ideas why this happens and how to fix it?
The code is bellow:
#include <GL/glfw.h>
int main()
{
int width, height;
int frame = 0;
bool running = true;
glfwInit();
if( !glfwOpenWindow( 700, 800, 0, 0, 0, 0, 0, 0, GLFW_WINDOW ) )
{
glfwTerminate();
return 0;
}
glfwSetWindowTitle("GLFW Application");
while(running)
{
frame++;
glfwGetWindowSize( &width, &height );
height = height > 0 ? height : 1;
glViewport( 0, 0, width, height );
glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective( 65.0f, (GLfloat)width/(GLfloat)height, 1.0f, 100.0f );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
gluLookAt(0.0f, 0.0f, 40.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f );
glRotatef(frame, 0.0f, 1.0f, 0.0f);
glColor3ub(255,255,0);
glBegin( GL_POLYGON );
glVertex3f(5.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(0.0f, 10.0f, 0.0f);
glVertex3f(5.0f, 10.0f, 0.0f);
glEnd();
glColor3ub(255,0,255);
glBegin( GL_POLYGON );
glVertex3f(5.0f, 0.0f, -2.0f);
glVertex3f(0.0f, 0.0f, -2.0f);
glVertex3f(0.0f, 10.0f, -2.0f);
glVertex3f(5.0f, 10.0f, -2.0f);
glEnd();
glColor3ub(0,255,255);
glBegin( GL_POLYGON );
glVertex3f(5.0f, 0.0f, 0.0f);
glVertex3f(5.0f, 0.0f, -2.0f);
glVertex3f(5.0f, 10.0f, -2.0f);
glVertex3f(5.0f, 10.0f, 0.0f);
glEnd();
glfwSwapBuffers();
running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam( GLFW_OPENED);}
glfwTerminate();
return 0;
}
I don't see depth feature in your code, try looking for depth buffer and GL_DEPTH_TEST, if not implemented, drawing order rules..

OpenGL code Works in Windows but not Mac

My school uses windows computers but I only have a mac at home.
The code runs fine in windows but for some reason I get errors running it in xCode.
I wasn't sure which frameworks to include so I added GLKit, Cocoa, GLUT, and OpenGL.
Am I missing something??
I would like to get Xcode setup so I can work on homework with the same code that will work on windows.
Here is the code
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
#define GL_GLEXT_PROTOTYPES
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#define GLUT_KEY_ESCAPE 27
const GLsizei windowWidth = 500;
const GLsizei windowHeight = 500;
GLfloat cubeRotateX = 45.0f;
GLfloat cubeRotateY = 45.0f;
bool keys[255];
GLvoid establishProjectionMatrix(GLsizei width, GLsizei height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 200.0f);
}
GLvoid initGL(GLsizei width, GLsizei height)
{
establishProjectionMatrix(width, height);
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_PERSPECTIVE_CORRECTION_HINT);
}
GLvoid displayFPS(GLvoid)
{
static long lastTime = glutGet(GLUT_ELAPSED_TIME);
static int loops = 0;
static GLfloat fps = 0.0f;
int newTime = glutGet(GLUT_ELAPSED_TIME);
if (newTime - lastTime > 100)
{
float newFPS = (float)loops / float(newTime - lastTime) * 1000.0f;
fps = (fps + newFPS) / 2.0f;
char title[80];
sprintf_s(title, "OpenGL Demo - %.2f", fps);
glutSetWindowTitle(title);
lastTime = newTime;
loops = 0;
}
loops++;
}
GLvoid drawScene(GLvoid)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -5.0f);
glRotatef(cubeRotateX, 1.0, 0.0, 0.0);
glRotatef(cubeRotateY, 0.0, 1.0, 0.0);
glBegin(GL_QUADS);
glColor3f(0.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
glColor3f(1.0f, 1.0f, 0.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glColor3f(1.0f, 0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, -1.0f);
glVertex3f( 1.0f, -1.0f, 1.0f);
glEnd();
glFlush();
glutSwapBuffers();
displayFPS();
}
GLboolean checkKeys(GLvoid)
{
const GLfloat speed = 1.0f;
if ( keys[GLUT_KEY_ESCAPE] )
return true;
if (keys[GLUT_KEY_LEFT])
cubeRotateY -= speed;
if (keys[GLUT_KEY_RIGHT])
cubeRotateY += speed;
if (keys[GLUT_KEY_UP])
cubeRotateX -= speed;
if (keys[GLUT_KEY_DOWN])
cubeRotateX += speed;
return false;
}
GLvoid timerLoop(int value)
{
if (checkKeys())
exit(0);
glutPostRedisplay();
glutTimerFunc(1, timerLoop, 0);
}
GLvoid keyboardCB(unsigned char key, int x, int y)
{
keys[key] = true;
}
GLvoid keyboardUpCB(unsigned char key, int x, int y)
{
keys[key] = false;
}
GLvoid keyboardSpecialCB(int key, int x, int y)
{
keys[key] = true;
}
GLvoid keyboardSpecialUpCB(int key, int x, int y)
{
keys[key] = false;
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
int windowID = glutCreateWindow("OpenGL Cube Demo");
glutReshapeWindow(windowWidth, windowHeight);
initGL(windowWidth, windowHeight);
glutDisplayFunc(drawScene);
glutKeyboardFunc(keyboardCB);
glutKeyboardUpFunc(keyboardUpCB);
glutSpecialFunc(keyboardSpecialCB);
glutSpecialUpFunc(keyboardSpecialUpCB);
glutTimerFunc(1, timerLoop, 0);
glutMainLoop();
return 0;
}
Why does it work in visual studio and not in Xcode??
The errors from the compiler seem pretty clear. The superficial reason it doesn't work is because this code contains Windows-isms that are not portable.
C++ doesn't allow a typedef of void to indicate an empty parameter list. You have to use void itself. So, just changed those GLvoids to voids.
sprintf_s() is a Windows-specific function. You can replace it with snprintf(), but you have to add a parameter after the buffer which is the size of the buffer. So, replace this:
sprintf_s(title, ...);
with:
snprintf(title, sizeof(title), ...);
The exit() function is available cross-platform, but you have to include the right header. Add #include <stdlib.h> near the top of your file.

OpenGL + SDL2 Black Screen

I'm currently learning OpenGL and have been using it with SDL2 and when trying to run a simple program I am getting a black screen. Any help would be appreciated. I'm using OpenGL 2.1 and vc compiler.
Here's my code
#include <iostream>
#include <SDL.h>
#include <Windows.h>
#include <gl/GL.h>
#include <gl/GLU.h>
using namespace std;
int main(int argc, char* argv[]) {
int width, height;
width = 640;
height = 480;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Window* win;
win = SDL_CreateWindow("SDL Application", 100, 100, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
SDL_GLContext context;
context = SDL_GL_CreateContext(win);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
height = (height <= 0) ? height = height : height = 1;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat) width / (GLfloat) height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
SDL_GL_SwapWindow(win);
glColor3f(1.0f, 1.0f, 1.0f);
glTranslatef(-1.5f, 0.0f, -6.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glEnd();
glTranslatef(3.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 0.0f);
glEnd();
SDL_Delay(5000);
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
The order of those is wrong:
SDL_GLContext context;
context = SDL_GL_CreateContext(win);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
The OpenGL context attributes must be set before creating the context (they are state variables, that control the context creation process).
This makes no sense: First you clear, then you swap, then you draw (into a then undefined back buffer, since the content of the back buffer is undefined after a swap) and then you don't swap.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
SDL_GL_SwapWindow(win);
glColor3f(1.0f, 1.0f, 1.0f);
/* this translate will move the triangle out
* of the NDC space i.e. it gets clipped or
* won't be visible at all. */
glTranslatef(-1.5f, 0.0f, -6.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0.0f, 1.0f, 0.0f);
This should be something like
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glEnd();
glTranslatef(3.0f, 0.0f, 0.0f);
glBegin(GL_QUADS);
glVertex3f(-1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 0.0f);
glEnd();
SDL_GL_SwapWindow(win);
SDL_Delay(5000);
To make any sense at all. There are still loads of problems with the rest of the code, but if you change it that way, you should at least see some white triangle on a black ground.