I created a 5 face box and put a ball inside of it and allowed it to bounce around inside the box. I created this using glOrtho.
I want to create a 3d Brick breaker style game for my course so I want to get my camera down into the box. I changed from glOrtho to gluPerspective. I had to change some values for my box to render correctly but the ball seems to have gone missing unless i put it on the origin.
This is my value initialization:
void variableInits(){
//Floor Plane
pl1.pos.x = 0; pl1.pos.y = -50; pl1.pos.z = 0;
pl1.norm.x = 0; pl1.norm.y = 1; pl1.norm.z = 0;
//Ceiling Plane
pl2.pos.x = 0; pl2.pos.y = 50; pl2.pos.z = 0;
pl2.norm.x = 0; pl2.norm.y = -1; pl2.norm.z = 0;
//Right Wall Plane
pl3.pos.x = 50; pl3.pos.y = 0; pl3.pos.z = 0;
pl3.norm.x = -1; pl3.norm.y = 0; pl3.norm.z = 0;
//Left Wall Plane
pl4.pos.x = -50; pl4.pos.y = 0; pl4.pos.z = 0;
pl4.norm.x = 1; pl4.norm.y = 0; pl4.norm.z = 0;
//Back Wall Plane
pl5.pos.x = 0; pl5.pos.y = 0; pl5.pos.z = -100;
pl5.norm.x = 0; pl5.norm.y = 0; pl5.norm.z = 1;
//Paddle Plane
paddlePlane.max.x=.25; paddlePlane.max.y=.25; paddlePlane.max.z=1;
paddlePlane.min.x=-.25; paddlePlane.min.y=-.25; paddlePlane.min.z=1;
paddlePlane.normals.x=0; paddlePlane.normals.y=0;paddlePlane.normals.z=-0;
//Ball Init
b1.radius = 10;
b1.pathDirection.x = 0; b1.pathDirection.y = 0; b1.pathDirection.z = 0;
b1.pos.x = 0; b1.pos.y = 0, b1.pos.z = -25;
}
So my ball should draw with a radius of 10 on -25 value of the Z axis. Sadly it does not.
Maybe its an issue with my gluPerspective call?
void reshape(int width, int height)
{
if (height==0)
{
height=1;
}
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.0f,50.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
Ill go ahead and post my complete code but it is a bit long.
#include <stdio.h>
#include <gl/glut.h>
#include "pHeader.h"
#define EPSILON 1.0e-8
#define ZERO EPSILON
int g_mainWindow = -1;
float g_lightPos[] = {0, 0, 0, -50};
int angle = 0;
int g_moving;
int g_mouse_x;
int g_mouse_y;
int g_x_angle;
int g_y_angle;
double mX,mY,mZ;
float speed = 1;
plane pl1, pl2, pl3, pl4 ,pl5;
paddlePl paddlePlane;
float collDist = 1000;
ball b1;
void mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state==GLUT_DOWN)
{
g_moving = 1;
g_mouse_x = x;
g_mouse_y = y;
}
else {
g_moving = 0;
}
}
void mouseDrag(int x, int y)
{
int dx, dy;
if (g_moving){
dx = x - g_mouse_x;
dy = y - g_mouse_y;
g_x_angle += dy;
g_y_angle += dx;
g_mouse_x = x;
g_mouse_y = y;
}
}
void paddle(int x, int y){
GLint viewport[4];
GLdouble modelview[16],projection[16];
glGetIntegerv(GL_VIEWPORT,viewport);
glGetDoublev(GL_MODELVIEW_MATRIX,modelview);
glGetDoublev(GL_PROJECTION_MATRIX,projection);
gluUnProject(x,viewport[3]-y,0,modelview,projection,viewport,&mX,&mY,&mZ);
}
/*************************************************
Vector Math
**************************************************/
float dot(vector XYZ , vector nXYZ){
return (XYZ.x * nXYZ.x) + (XYZ.y * nXYZ.x) + (XYZ.z * nXYZ.z);
}
vector cross(vector v1 , vector v2){
vector result;
result.x = v1.y * v2.z - v1.z * v2.y;
result.y = v1.z * v2.x - v1.x * v2.z;
result.z = v1.x * v2.y - v1.y * v2.x;
return result;
}
vector vectScale(float scale, vector v1){
vector result;
result.x = v1.x * scale;
result.y = v1.y * scale;
result.z = v1.z * scale;
return result;
}
vector vectorSub(vector v1, vector v2){
vector result;
result.x = v1.x - v2.x;
result.y = v1.y - v2.y;
result.z = v1.z - v2.y;
return result;
}
vector flipVect(vector v1){
vector result;
result.x = -v1.x;
result.y = -v1.y;
result.z = -v1.z;
return result;
}
vector vectorAdd(vector v1, vector v2){
vector result;
result.x = v1.x + v2.x;
result.y = v1.y + v2.y;
result.z = v1.z + v2.z;
return result;
}
/****************************************************
End Vecotor Math
****************************************************/
void planeCollision(){
//Check Ceiling
if(b1.pos.y + b1.radius >= 50){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl2.norm) , pl2.norm) , b1.pathDirection);
}
//Check Floor
if(b1.pos.y-b1.radius <= -50){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl1.norm) , pl1.norm) , b1.pathDirection);
}
//Check Right Wall
if(b1.pos.x + b1.radius >= 1){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl3.norm) , pl3.norm) , b1.pathDirection);
}
//Check Left Wall
if(b1.pos.x - b1.radius <= -1){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl4.norm) , pl4.norm) , b1.pathDirection);
}
//Check Back Wall
if(b1.pos.z - b1.radius <= -1){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl5.norm) , pl5.norm) , b1.pathDirection);
}
//Check paddle
if(b1.pos.z + b1.radius >= paddlePlane.max.z && b1.pos.x >= paddlePlane.min.x && b1.pos.x <= paddlePlane.max.x && b1.pos.y >= paddlePlane.min.y && b1.pos.y <= paddlePlane.max.y){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), paddlePlane.normals) , paddlePlane.normals) , b1.pathDirection);
}
}
void drawPlanes(){
glBegin(GL_QUADS);
//Floor
glColor3f(1,0,0);
glNormal3f( 0.0f , 1.0f, 0.0f);
glVertex3f( 050.0f , -050.0f , -100.0f);
glVertex3f(-050.0f , -050.0f , -100.0f);
glVertex3f(-050.0f , -050.0f , 000.0f);
glVertex3f( 050.0f , -050.0f , 000.0f);
//Ceiling
glColor3f(1,0,1);
glNormal3f(0.0f,-1.0f,0.0f);
glVertex3f( 050.0f, 050.0f, -100.0f);
glVertex3f(-050.0f, 050.0f, -100.0f);
glVertex3f(-050.0f, 050.0f, 000.0f);
glVertex3f( 050.0f, 050.0f, 000.0f);
//Right Wall
glColor3f(0,1,0);
glNormal3f( -1.0f , 0.0f, 0.0f);
glVertex3f(050.0f , 050.0f , 000.0f);
glVertex3f(050.0f , 050.0f , -100.0f);
glVertex3f(050.0f ,-050.0f , -100.0f);
glVertex3f(050.0f ,-050.0f, 000.0f);
//LeftWall
glColor3f(0,1,1);
glNormal3f( 1.0f , 0.0f, 0.0f);
glVertex3f(-050.0f , 050.0f , -100.0f);
glVertex3f(-050.0f , 050.0f , 000.0f);
glVertex3f(-050.0f , -050.0f , 000.0f);
glVertex3f(-050.0f , -050.0f , -100.0f);
//Back Wall
glColor3f(0,0,1);
glNormal3f( 0.0f , 0.0f, 1.0f);
glVertex3f( 050.0f , 050.0f , -100.0f);
glVertex3f(-050.0f , 050.0f , -100.0f);
glVertex3f(-050.0f , -050.0f , -100.0f);
glVertex3f( 050.0f , -050.0f , -100.0f);
glEnd();
}
void ballMove(){
glPushMatrix();
glColor3f(1,1,0);
b1.pos.x += (b1.pathDirection.x * speed); b1.pos.y += (b1.pathDirection.y * speed); b1.pos.z += (b1.pathDirection.z * speed);
glTranslatef(b1.pos.x,b1.pos.y,b1.pos.z);
glutSolidSphere(b1.radius,100,100);
printf("%.2f %.2f %.2f\n", b1.pos.x, b1.pos.y, b1.pos.z);
glPopMatrix();
planeCollision();
}
void drawPaddle(){
//printf("x %f y %f\n" , mX , mY);
glPushMatrix();
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_QUADS);
glColor3f(1,1,1);
glVertex3f(mX + 25.0f , mY + 25.0f , 0.0f);
glVertex3f(mX + -25.0f , mY + 25.0f , 0.0f);
glVertex3f(mX + -25.0f , mY + -25.0f , 0.0f);
glVertex3f(mX + 25.0f , mY + -25.0f , 0.0f);
glEnd();
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL);
glPopMatrix();
paddlePlane.max.x=mX + 0.25f; paddlePlane.max.y=mY + 0.25f; paddlePlane.max.z=1;
paddlePlane.min.x=mX + -0.25f; paddlePlane.min.y=mY + -0.25f; paddlePlane.min.z=1;
}
void display()
{
float red[] = {1,0,0,1};
float blue[] = {0,0,1,1};
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glPushMatrix();
glRotated(g_y_angle, 0, 1, 0);
glRotated(g_x_angle,1,0,0);
glTranslated(0,0,-100);
drawPaddle();
ballMove();
drawPlanes();
glPopMatrix();
angle += 1;
glFlush();
glutSwapBuffers();
}
void reshape(int width, int height)
{
if (height==0)
{
height=1;
}
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.0f,50.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void idle()
{
glutSetWindow(g_mainWindow);
glutPostRedisplay();
}
void variableInits(){
//Floor Plane
pl1.pos.x = 0; pl1.pos.y = -50; pl1.pos.z = 0;
pl1.norm.x = 0; pl1.norm.y = 1; pl1.norm.z = 0;
//Ceiling Plane
pl2.pos.x = 0; pl2.pos.y = 50; pl2.pos.z = 0;
pl2.norm.x = 0; pl2.norm.y = -1; pl2.norm.z = 0;
//Right Wall Plane
pl3.pos.x = 50; pl3.pos.y = 0; pl3.pos.z = 0;
pl3.norm.x = -1; pl3.norm.y = 0; pl3.norm.z = 0;
//Left Wall Plane
pl4.pos.x = -50; pl4.pos.y = 0; pl4.pos.z = 0;
pl4.norm.x = 1; pl4.norm.y = 0; pl4.norm.z = 0;
//Back Wall Plane
pl5.pos.x = 0; pl5.pos.y = 0; pl5.pos.z = -100;
pl5.norm.x = 0; pl5.norm.y = 0; pl5.norm.z = 1;
//Paddle Plane
paddlePlane.max.x=.25; paddlePlane.max.y=.25; paddlePlane.max.z=1;
paddlePlane.min.x=-.25; paddlePlane.min.y=-.25; paddlePlane.min.z=1;
paddlePlane.normals.x=0; paddlePlane.normals.y=0;paddlePlane.normals.z=-0;
//Ball Init
b1.radius = 10;
b1.pathDirection.x = 0; b1.pathDirection.y = 0; b1.pathDirection.z = 0;
b1.pos.x = 0; b1.pos.y = 0, b1.pos.z = -25;
}
int main(int ac, char* av[])
{
glutInit(&ac, av);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
g_mainWindow = glutCreateWindow("Hello, glut");
variableInits();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glutMouseFunc(mouse);
glutMotionFunc(mouseDrag);
glutPassiveMotionFunc(paddle);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
glLightfv(GL_LIGHT0, GL_POSITION, g_lightPos);
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glutMainLoop(); //no return
}
Header
#pragma once
#ifndef pHeader_INCLUDED
#define pHeader_H_INCLUDED
typedef struct vector{
float x,y,z;
}vector;
typedef struct ball{
float radius;
vector pathDirection;
vector pos;
} ball;
typedef struct planeStruc{
vector pos;
vector norm;
} plane;
typedef struct paddlePlane{
vector min;
vector max;
vector normals;
} paddlePl;
#endif
gluPerspective cannot have a value of 0.0 for the near plane, it either generates an error (I'm not sure) or causes some weird infinity math to happen that's certainly not what you want.
You should make the value of the near plane greater than zero, and ideally as large as possible without cutting off things that you want to see. If you make it too small you'll lose a ton of z precision.
Try a value of 0.1 to start with.
Related
I need help adding another object to my "drawing".
With the help of my college teacher code with Google I was able to create a face shape.
I want to add a smile to the face
What to add another shape to the drawing?
I tried to append to the void face() something like:
glVertex2f(100, 125);
glVertex2f(400, 125);
This is the code in C language:
#include <GL/glut.h>
#include <math.h>
#include<Windows.h>
#include <GL/gl.h>
#include <GL/GLU.h>
#include <stdlib.h>
float counter = 200;
static GLfloat spin = 0.0;
static GLfloat R = 0.2;
static GLfloat G = 0.9;
static GLfloat B = 0.8;
float carx = 500, cary = 50, fr = 0, fl = 0, fo = 0, fu = 0, mx = 0, my = 0;
void initOpenGl()
{
glClearColor(0.0, 0.0, 1.8, 0); //Background Color
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 1500, 0, 500);
glMatrixMode(GL_MODELVIEW);
}
void eye(int x, int y)
{
float th;
glBegin(GL_POLYGON);
glColor3f(0, 0, 0);
for (int i = 0; i < 360; i++)
{
th = i * (3.1416 / 180);
glVertex2f(x + 25 * cos(th), y + 20 * sin(th));
}
glEnd();
}
void face()
{
glLoadIdentity();//Bottom Par
counter = counter - 0.03;
if (fr > 0)
carx += fr;
if (fl > 0)
carx -= fl;
if (fu > 0)
cary += fu;
if (fo > 0)
cary -= fo;
if (mx > 0)
carx += mx;
if (my > 0)
carx -= my;
glTranslated(carx, cary, 0.0);
glBegin(GL_POLYGON); //Top Part
glVertex2f(100, 125);
glVertex2f(400, 125);
glVertex2f(400, 300);
glVertex2f(100, 300);
glEnd();
eye(165, 230);
eye(315, 230);
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.5, 0.9, 0.33); //Push and pop matrix for separating circle object from Background
face();
pa();
glutSwapBuffers();
glFlush();
}
void mouse(int button)
{
switch (button) {
case GLUT_LEFT_BUTTON: mx = 0.3;
break;
case GLUT_RIGHT_BUTTON:my = 0.2;
break;
default:
break;
}
}
void keyFunc(unsigned char key, int x, int y)
{
switch (key) {
case 'w': fu = 0.3, fo = 0, fr = 0, fl = 0;
break;
case 's': fu = 0, fo = 0.2, fr = 0, fl = 0;
break;
case 'a': fu = 0.01, fo = 0, fr = 0, fl = 0.2;
break;
case 'd': fu = 0.01, fo = 0, fr = 0.2, fl = 0;
break;
case 'z': fu = 0, fo = 0.2, fr = 0, fl = 0.2;
break;
case 'c': fu = 0, fo = 0.2, fr = 0.2, fl = 0;
break;
default:
break;
}
glutPostOverlayRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(1500, 700);
glutInitWindowPosition(0, 0);
glutCreateWindow("Shai Goldenebrg");
initOpenGl();
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(keyFunc);
glutIdleFunc(display);
glutMainLoop();
return 0;
}
A smiling mouth is a Concave polygon. I recommend to use a GL_TRIANGLE_STRIP primitive to generate the mouth. e.g:
void mouth(int x, int y)
{
float th, s, c;
glBegin(GL_TRIANGLE_STRIP);
glColor3f(0, 0, 0);
for (int i = 240; i < 300; i++)
{
th = i * (3.1416 / 180);
c = cos(th);
s = sin(th);
glVertex2f(x + 90 * cos(th), y + 100 + 90 * sin(th));
glVertex2f(x + 110 * cos(th), y + 100 + 110 * sin(th));
}
glEnd();
}
void face()
{
// [...]
eye(165, 230);
eye(315, 230);
mouth(240, 150);
}
So I just added ortho projection to my rendering and everything stopped rendering... If I remove it, it works again. This is my matrix code:
#include <stdlib.h>
#include <stdlib.h>
#include <math.h>
matrix4x4 init_matrix4x4() {
matrix4x4 m = calloc(16, sizeof(float));
m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0;
m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0;
m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0;
m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1;
return m;
}
void translate_matrix4x4(matrix4x4* matrix, float x, float y, float z) {
matrix4x4 m = (*matrix);
m[12] = m[0] * x + m[4] * y + m[8] * z + m[12];
m[13] = m[1] * x + m[5] * y + m[9] * z + m[13];
m[14] = m[2] * x + m[6] * y + m[10] * z + m[14];
m[15] = m[3] * x + m[7] * y + m[11] * z + m[15];
}
void ortho_matrix4x4(matrix4x4* matrix, float left, float right, float bottom, float top, float near, float far) {
matrix4x4 m = (*matrix);
m[0] = 2 / (right-left);
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = 2 / (top - bottom);
m[6] = 0;
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = 1 / (far - near);
m[11] = 0;
m[12] = (left + right) / (left - right);
m[13] = (top + bottom) / (bottom - top);
m[14] = near / (near - far);
m[15] = 1;
}
void mat4_identity(matrix4x4* matrix) {
matrix4x4 out = (*matrix);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
}
void mat4_lookAtf(matrix4x4* matrix, float eye[3], float center[3], float up[3]) {
matrix4x4 out = (*matrix);
float x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
eyex = eye[0],
eyey = eye[1],
eyez = eye[2],
upx = up[0],
upy = up[1],
upz = up[2],
centerx = center[0],
centery = center[1],
centerz = center[2];
if (fabs(eyex - centerx) < 0.000001 &&
fabs(eyey - centery) < 0.000001 &&
fabs(eyez - centerz) < 0.000001) {
mat4_identity(&out);
return;
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / sqrt/*f*/(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
out[0] = x0;
out[1] = y0;
out[2] = z0;
out[3] = 0;
out[4] = x1;
out[5] = y1;
out[6] = z1;
out[7] = 0;
out[8] = x2;
out[9] = y2;
out[10] = z2;
out[11] = 0;
out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
out[15] = 1;
};
And here is the main.c , where I render things:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include "include/matrix.h"
#include "include/io.h"
const int WIDTH = 640;
const int HEIGHT = 480;
// called when user resizes window
void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
}
// called when we receive input
void processInput(GLFWwindow *window) {
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, 1);
}
GLuint get_checker_texture() {
unsigned char texDat[64];
for (int i = 0; i < 64; ++i)
texDat[i] = ((i + (i / 8)) % 2) * 128 + 127;
//upload to GPU texture
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 8, 8, 0, GL_RED, GL_UNSIGNED_BYTE, texDat);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
return tex;
}
//void render_box(renderable* this, unsigned int vbo, unsigned int vao, unsigned int ebo) {
// draw_texture(this->texture, this->x, this->y, this->z, vbo, vao, ebo);
//}
int main(int argc, char* argv[]) {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // only on MACOS
#endif
// creating the window
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL App", NULL, NULL);
if (window == NULL) {
printf("Failed to create GLFW window");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// hook on window resize
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
printf("Failed to initialize GLAD");
return -1;
}
printf("OpenGL %d.%d\n", GLVersion.major, GLVersion.minor);
glEnable(GL_DEPTH_TEST);
glViewport(0, 0, WIDTH, HEIGHT);
unsigned int tex = get_checker_texture();
const char* vertex_shader_src = read_file("res/shaders/textured_and_positioned.vs.glsl");
unsigned int vertex_shader;
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_shader_src, NULL);
glCompileShader(vertex_shader);
int success;
char infoLog[512];
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vertex_shader, 512, NULL, infoLog);
printf("%s\n", infoLog);
}
const char* fragment_shader_src = read_file("res/shaders/textured_and_positioned.fs.glsl");
unsigned int fragment_shader;
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_shader_src, NULL);
glCompileShader(fragment_shader);
int success0;
char infoLog0[512];
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success0);
if (!success0) {
glGetShaderInfoLog(fragment_shader, 512, NULL, infoLog0);
printf("%s\n", infoLog0);
}
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertex_shader);
glAttachShader(shaderProgram, fragment_shader);
glLinkProgram(shaderProgram);
unsigned uniform_sampler_ourTexture = glGetUniformLocation(shaderProgram, "ourTexture");
unsigned uniform_mat4_model = glGetUniformLocation(shaderProgram, "model");
unsigned uniform_mat4_view = glGetUniformLocation(shaderProgram, "view");
unsigned uniform_mat4_perspective = glGetUniformLocation(shaderProgram, "perspective");
int success1;
char infoLog1[512];
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success1);
if(!success1) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog1);
printf("%s\n", infoLog1);
}
float vertices[] = {
// positions // colors // texture coords
0.1f, 0.1f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.1f, -0.1f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.1f, -0.1f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.1f, 0.1f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0 // top left
};
unsigned elements[] = {
0, 1, 2, // triangle
2, 3, 0 // triangle
};
unsigned int vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
matrix4x4 model = init_matrix4x4();
matrix4x4 view = init_matrix4x4();
translate_matrix4x4(&view, 0.0f, 0.0f, 0.0f);
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
matrix4x4 perspective = calloc(16, sizeof(float));
ortho_matrix4x4(&perspective, 0.0f, 640.0f, 0.0f, 480.0f, 0.1f, 100.0f);
unsigned int vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// positions
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(0 * sizeof(float)));
glEnableVertexAttribArray(0);
// colors
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// texture coords
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
unsigned int ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
glUseProgram(shaderProgram);
glUniformMatrix4fv(uniform_mat4_view, 1, GL_FALSE, view);
glUniformMatrix4fv(uniform_mat4_perspective, 1, GL_FALSE, perspective);
// render loop
while(!glfwWindowShouldClose(window)) {
processInput(window);
// render here
glClearColor(
0, 0, 0, 0
);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glUniform1i(uniform_sampler_ourTexture, 0);
translate_matrix4x4(&model, x, y, z);
glUniformMatrix4fv(uniform_mat4_model, 1, GL_FALSE, model);
//x += 0.0001f;
//y += 0.0001f;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
Here is the vertex shader:
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexCoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 perspective;
out vec3 ourColor;
out vec2 TexCoord;
void main()
{
gl_Position = perspective * view * model * vec4(aPos, 1.0);
ourColor = aColor;
TexCoord = aTexCoord;
}
Here is the fragment shader:
#version 330 core
out vec4 FragColor;
in vec3 ourColor;
in vec2 TexCoord;
uniform sampler2D ourTexture;
void main()
{
FragColor = vec4(vec3(texture(ourTexture, TexCoord).r), 1.);
}
Now, if I remove the perspective value from the shader, which is the ortho matrix, the checkered texture is rendered as it should.
What is wrong here?
Is it my shader or is it the matrix ortho function?
Your matrices are stored in row-major, submit them to the uniforms without transposing and do calculations left-associative in the shader.
You can either
store in column major order
or
transpose upon loading into the uniform
or
switch to left-associative multiplication in the shader
Each to the same effect.
I have an openGL program thats using GLUT and I'm stuck with moving it from the top left corner to bottom right when i resize the window. I'm trying to get a ratio down and i cant figure it out.
#include <stdio.h>
#include <stdlib.h>
#include <GLUT/glut.h>
//global variables
GLsizei wh = 500, ww = 500;
double height;
double width;
double top = 500;
double bottom = 450;
int right = 50;
int left = 0;
double ratiowidth = 500/500;
double ratioheight = 500/500;
void myinit(){
glClearColor (0.0, 0.0, 0.0, 0.0);
}
void reshape(int w, int h){
if(h == 0){
h = 1;
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, (GLsizei) w, 0, (GLsizei)h);
glViewport(0,0,w,h);
glMatrixMode(GL_MODELVIEW);
int difference = h - wh;
int difference2 = w - ww;
left = left + difference2;
right = right + difference2;
wh = (GLsizei)h;
ww = (GLsizei)w;
height = h;
width = w;
}
void mouse(int button, int state, int x, int y){
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
top = height;
bottom = height - 50;
right = 50;
left = 0;
ratiowidth = width/height;
ratioheight = height/width;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){
exit(0);
}
}
void display(){
glClear (GL_COLOR_BUFFER_BIT);
glColor3i (rand(), rand(), rand());
glBegin(GL_POLYGON);
glVertex3f (left,top,0.0);
glVertex3f (right, top, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (left, bottom, 0.0);
glEnd();
if(bottom == 0 || bottom < 0)
bottom = 0;
else{
left = left + ratiowidth;
right = right + ratiowidth;
top = top - ratioheight;
bottom = bottom - ratioheight;
}
glutSwapBuffers();
usleep(10000);
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(ww, wh);
glutInitWindowPosition(100,100);
glutCreateWindow("moving Square");
myinit();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
glBegin(GL_POLYGON);
glVertex3f (left,top,0.0);
glVertex3f (right, top, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (left, bottom, 0.0);
glEnd();
Careful with your winding order. glFrontFace() defaults to GL_CCW. Perhaps you meant this:
glBegin(GL_POLYGON);
glVertex3f (left, bottom, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (right, top, 0.0);
glVertex3f (left,top,0.0);
glEnd();
EDIT: This is what I think you were trying to do:
#include <GL/glut.h>
struct State
{
double x; // in units
double y;
double xvel; // in units per second
double yvel;
};
State curState = { 0 };
void myinit()
{
curState.xvel = 100;
curState.yvel = 100;
}
void Integrate( State* state, double dt )
{
state->x += state->xvel * dt;
state->y += state->yvel * dt;
}
double GetSeconds()
{
return glutGet(GLUT_ELAPSED_TIME) / 1000.0f;
}
void reshape(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, (GLsizei)w, 0, (GLsizei)h);
}
void mouse(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
curState.x = 0;
curState.y = 0;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_UP)
{
exit(0);
}
}
void display()
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
float w = 20;
float h = 20;
float x = curState.x;
float y = curState.y;
glColor3ub(rand()%255, rand()%255, rand()%255);
glBegin(GL_QUADS);
glVertex2f( x - w/2, y - h/2 );
glVertex2f( x + w/2, y - h/2 );
glVertex2f( x + w/2, y + h/2 );
glVertex2f( x - w/2, y + h/2 );
glEnd();
static double lastTime = GetSeconds();
double curTime = GetSeconds();
Integrate( &curState, curTime - lastTime );
lastTime = curTime;
glutSwapBuffers();
}
void timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(16, timer, 0);
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100,100);
glutCreateWindow("moving Square");
myinit();
glutReshapeFunc(reshape);
glutTimerFunc(0, timer, 0);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
Be aware that there are probably some C++-isms in there :)
this is my draw() function written in C, using vertex arrays:
void draw(float x1, float x2, float y1, float y2)
{
glPushMatrix();
glScalef(1.0 / (x2 - x1), 1.0 / (y2 - y1), 1.0);
glTranslatef(-x1, -y1, 0.0);
glColor3f(1.0, 1.0, 1.0);
if( pts.size > 0 )
{
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer( 2, GL_FLOAT, 0, (float*)pts.data );
glDrawArrays( GL_LINE_STRIP, 0, pts.size / 2 );
glDisableClientState( GL_VERTEX_ARRAY );
}
glPopMatrix();
};
before calling draw(), pts get's updated inside the update() function:
void update(double (* func)(double x), float x1, float x2, int N)
{
double x, dx = (double)1.0/(double)N;
vector_cleanup( &pts );
m = 0;
for(x = x1; x < x2; x += dx)
{
vector_resize( &pts, pts.size + 2 );
*(float*)vector_get( &pts, pts.size-2 ) = (float)x;
*(float*)vector_get( &pts, pts.size-1 ) = (float)func3(x);
m++;
}
}
I hope that by converting this code to use VBO, my graphics performance will increase.
EDIT: func3() can be anything, e.g. sin(x) or just some linear mapping. All I'm currently trying to do is, to find out how quickly I can plot a bunch of points.
Using GLEW for extension wrangling:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <GL/glew.h>
#include <GL/glut.h>
typedef struct vector /*dynamic vector of void* pointers. This one is used only by the deflate compressor*/
{
void* data;
size_t size; /*in groups of bytes depending on type*/
size_t allocsize; /*in bytes*/
unsigned typesize; /*sizeof the type you store in data*/
} vector;
static unsigned vector_resize(vector* p, size_t size) /*returns 1 if success, 0 if failure ==> nothing done*/
{
if(size * p->typesize > p->allocsize)
{
size_t newsize = size * p->typesize * 2;
void* data = realloc(p->data, newsize);
if(data)
{
p->allocsize = newsize;
p->data = data;
p->size = size;
}
else return 0;
}
else p->size = size;
return 1;
}
static void vector_cleanup(void* p)
{
((vector*)p)->size = ((vector*)p)->allocsize = 0;
free(((vector*)p)->data);
((vector*)p)->data = NULL;
}
static void vector_init(vector* p, unsigned typesize)
{
p->data = NULL;
p->size = p->allocsize = 0;
p->typesize = typesize;
}
static void* vector_get(vector* p, size_t index)
{
return &((char*)p->data)[index * p->typesize];
}
/* function to calculate each data point */
float func(float x)
{
return (float)sin(x);
}
GLuint vbo = 0;
GLsizei vertcount = 0;
void update(float (* func)(float x), float x1, float x2, int N)
{
float x, dx = 1.0f/N;
vector pts;
vector_init( &pts, sizeof( float ) );
for(x = x1; x < x2; x += dx)
{
vector_resize( &pts, pts.size + 2 );
*(float*)vector_get( &pts, pts.size-2 ) = x;
*(float*)vector_get( &pts, pts.size-1 ) = func(x);
}
vertcount = (GLsizei)( pts.size / 2 );
glBindBuffer( GL_ARRAY_BUFFER, vbo );
glBufferData( GL_ARRAY_BUFFER, pts.size * pts.typesize, pts.data, GL_DYNAMIC_DRAW );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
vector_cleanup( &pts );
}
/* plotting function - very slow */
void draw(float x1, float x2, float y1, float y2)
{
glPushMatrix();
glScalef( 1.0f / (x2 - x1), 1.0f / (y2 - y1), 1.0f );
glTranslatef( -x1, -y1, 0.0f );
glColor3f( 1.0f, 1.0f, 1.0f );
glBindBuffer( GL_ARRAY_BUFFER, vbo );
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer( 2, GL_FLOAT, 0, 0 );
glDrawArrays( GL_LINE_STRIP, 0, vertcount );
glDisableClientState( GL_VERTEX_ARRAY );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glPopMatrix();
};
/* Redrawing func */
float xmin = -10, xmax = 10, ymin = -5, ymax = 5;
void redraw(void)
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// -x, +x, -y, +y, number points
draw(xmin, xmax, ymin, ymax);
glutSwapBuffers();
};
/* Idle proc. Redisplays, if called. */
int nPoints = 3000;
void idle(void)
{
// shift 'xmin' & 'xmax' by one.
xmin++;
xmax++;
update(func, xmin, xmax, nPoints);
glutPostRedisplay();
};
/* Key press processing */
void key(unsigned char c, int x, int y)
{
if(c == 27) exit(0);
};
/* Window reashape */
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
};
/* Main function */
int main(int argc, char **argv)
{
GLenum err;
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("Graph plotter");
glutReshapeWindow(1024, 800);
// init GLEW and output some GL info
err = glewInit();
printf("GL_VERSION : %s\n", glGetString(GL_VERSION) );
printf("GL_VENDOR : %s\n", glGetString(GL_VENDOR) );
printf("GL_RENDERER : %s\n", glGetString(GL_RENDERER) );
if( GLEW_OK != err )
{
printf("glewInit failed: %s", glewGetErrorString(err));
return EXIT_FAILURE;
}
if( !glewIsSupported("GL_VERSION_1_5") )
{
printf("OpenGL version 1.5 or greater required.\n");
return EXIT_FAILURE;
}
glGenBuffers( 1, &vbo );
/* Register GLUT callbacks. */
glutDisplayFunc(redraw);
glutKeyboardFunc(key);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
/* Init the GL state */
glLineWidth(2.0);
/* Main loop */
glutMainLoop();
return 0;
}
When I try to resize my glut window, the screen goes blank.
This is the code for the reshape callback funciton:
void Resize(int width, int height)
{
CurrentWidth = width;
CurrentHeight = height;
glViewport(0, 0, (GLsizei)CurrentWidth, (GLsizei)CurrentHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, CurrentWidth, CurrentHeight, 0, NearPlane, FarPlane);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glutPostRedisplay();
}
I am pretty new to the opengl world but from what I have learned this is supposed to work.
And this is all of the code put together:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <gl/glut.h>
#include "Utils.h"
int LEFT = 0;
int RIGHT = 0;
int UP = 0;
int DOWN = 0;
int CurrentWidth = 800,
CurrentHeight = 800,
WindowHandle = 0;
float NearPlane = 1.0f,
FarPlane = 100.0f;
float lightX,
lightY;
void Initialize(int, char*[]);
void InitWindow(int, char*[]);
void Idle(void);
void Resize(int, int);
void KeyPressed(unsigned char, int, int);
void SpecialPressed(int, int, int);
void SpecialReleased(int, int, int);
void Update(void);
void Render(void);
void FillZBuffer(void);
void ClearAlpha(void);
void RenderLightAlpha(float);
void GeometryPass(void);
void Draw(void);
int main (int argc, char* argv[])
{
Initialize(argc, argv);
glutMainLoop();
exit(EXIT_SUCCESS);
}
void Initialize(int argc, char* argv[])
{
InitWindow(argc, argv);
fprintf(
stdout,
"INFO: OpenGL Version: %s\n",
glGetString(GL_VERSION)
);
lightX = 300.0f;
lightY = 300.0f;
}
void InitWindow(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitContextVersion(3, 3);
glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE);
glutSetOption(
GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS
);
glutInitWindowSize (CurrentWidth, CurrentHeight);
glutInitWindowPosition (100, 100);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA);
WindowHandle = glutCreateWindow ("Shadows");
if(WindowHandle < 1) {
fprintf(
stderr,
"ERROR: Could not create a new rendering window.\n"
);
exit(EXIT_FAILURE);
}
glutDisplayFunc(Render);
glutReshapeFunc(Resize);
glutIdleFunc(Idle);
glutKeyboardFunc(KeyPressed);
glutSpecialFunc(SpecialPressed);
glutSpecialUpFunc(SpecialReleased);
}
void Update()
{
int speed = 10;
if (LEFT)
{
lightX -= speed;
}
if (RIGHT)
{
lightX += speed;
}
if (UP)
{
lightY -= speed;
}
if (DOWN)
{
lightY += speed;
}
}
void Draw()
{
float x = 200;
float y = 200;
float w = 100;
float h = 100;
float depth = 0.0f;
// floor
glColor4f(0.5f, 0.5f, 0.5f, 1.0f);
depth = -10.0f;
glBegin(GL_QUADS);
{
glVertex3f(0, 0, depth);
glVertex3f((float)CurrentWidth, 0, depth);
glVertex3f((float)CurrentWidth, (float)CurrentHeight, depth);
glVertex3f(0, (float)CurrentHeight, depth);
}
glEnd();
// square
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
depth = -5.0;
glBegin(GL_QUADS);
{
glVertex3f( x, y, depth);
glVertex3f( x + w, y, depth);
glVertex3f(x + w, y + h, depth);
glVertex3f(x, y + h, depth);
}
glEnd();
}
void Render()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_CULL_FACE);
Update();
FillZBuffer();
ClearAlpha();
RenderLightAlpha(1.0f);
GeometryPass();
glutSwapBuffers();
glutPostRedisplay();
}
void FillZBuffer()
{
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glDepthMask(GL_TRUE);
Draw();
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_FALSE);
}
void ClearAlpha()
{
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
glColor4f(0.0f, 0.0f, 0.0f, 0.0f);
glBegin (GL_QUADS);
{
glVertex2f(0, 0);
glVertex2f((float)CurrentWidth, 0);
glVertex2f((float)CurrentWidth, (float)CurrentHeight);
glVertex2f(0, (float)CurrentHeight);
}
glEnd ();
}
void RenderLightAlpha(float intensity)
{
float depth = -1.0f;
float radius = 300.0f;
float angle;
int numSubdivisions = 32;
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glBegin(GL_TRIANGLE_FAN);
{
glColor4f(0.0f, 0.0f, 0.0f, intensity);
glVertex3f(lightX, lightY, depth);
// Set edge colour for rest of shape
glColor4f(0.0f, 0.0f, 0.0f, 0.0f);
for (angle = 0; angle <= (float)PI * 2; angle += (((float)PI * 2) / numSubdivisions))
{
glVertex3f( radius*(float)cos(angle) + lightX, radius*(float)sin(angle) + lightY, depth);
}
glVertex3f(lightX + radius, lightY, depth);
}
glEnd();
}
void GeometryPass()
{
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_BLEND);
glBlendFunc(GL_DST_ALPHA, GL_ONE);
Draw();
}
void Idle()
{
glutPostRedisplay();
}
void Resize(int width, int height)
{
CurrentWidth = width;
CurrentHeight = height;
glViewport(0, 0, (GLsizei)CurrentWidth, (GLsizei)CurrentHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, CurrentWidth, CurrentHeight, 0, NearPlane, FarPlane);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glutPostRedisplay();
}
void KeyPressed(unsigned char key, int x, int y)
{
UNREFERENCED_PARAMETER(x);
UNREFERENCED_PARAMETER(y);
// escape key
if (key == 27)
{
exit(0);
}
}
void SpecialPressed(int keyCode, int x, int y)
{
UNREFERENCED_PARAMETER(x);
UNREFERENCED_PARAMETER(y);
if (keyCode == GLUT_KEY_LEFT)
{
LEFT = 1;
}
else if (keyCode == GLUT_KEY_RIGHT)
{
RIGHT = 1;
}
else if (keyCode == GLUT_KEY_UP)
{
UP = 1;
}
else if (keyCode == GLUT_KEY_DOWN)
{
DOWN = 1;
}
}
void SpecialReleased(int keyCode, int x, int y)
{
UNREFERENCED_PARAMETER(x);
UNREFERENCED_PARAMETER(y);
if (keyCode == GLUT_KEY_LEFT)
{
LEFT = 0;
}
else if (keyCode == GLUT_KEY_RIGHT)
{
RIGHT = 0;
}
else if (keyCode == GLUT_KEY_UP)
{
UP = 0;
}
else if (keyCode == GLUT_KEY_DOWN)
{
DOWN = 0;
}
}
Let me know if you need anymore information.
In the FillZBuffer function the depth mask is disabled at the end and only re-enabled at the beginning of the same function. So when Render is called again, the call to clear the depth buffer bit does nothing because the depth mask is disabled.
To fix this the depth mask must be re-enabled before the call to clear the depth buffer bit.
So this is what Render should look like.
void Render()
{
glDepthMask(GL_TRUE); // insert this line
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_CULL_FACE);
Update();
FillZBuffer();
ClearAlpha();
RenderLightAlpha(1.0f);
GeometryPass();
glutSwapBuffers();
glutPostRedisplay();
}