OpenGL ortho projection is broken - c

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.

Related

Freetype with opengl shows no text

I’m trying to add freetype text to my running program. The code below was adapted from EdoardoLuciani. No text is shown, though.
I checked if the the tff file is loaded correctly and that valid textures ids are generated. They are o.k.
The remaining of the program is running without problem, but no text is drawn.
Could you help me to find what's wrong, please?
Environment:
DELL XPS
GPU 1050
OpenGL 4.6
Win32
Language C
// Main program
...
initText()
...
// Drawing loop
...
{
drawText(10, 300, "Hello World!");
}
void initText()
{
// Extract glyphs textures
//
glUseProgram(textShader);
FT_Library ft;
FT_Init_FreeType(&ft);
FT_Face face;
FT_New_Face(ft, "arial.ttf", 0, &face);
FT_Set_Pixel_Sizes(face, 0, 48);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
for(int c = 0; c < 128; c++)
{
FT_Load_Char(face, c, FT_LOAD_RENDER);
//
// Extract glyph
//
GLuint texture;
glCreateTextures(GL_TEXTURE_2D,1, &texture);
glTextureStorage2D(texture, 1, GL_R8, face->glyph->bitmap.width, face->glyph->bitmap.rows);
glTextureSubImage2D(texture, 0, 0, 0, face->glyph->bitmap.width, face->glyph->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
//
// Save glyph to lookup table
//
Character ch;
ch.texture = texture;
ch.bearing[0] = face->glyph->bitmap.width;
ch.bearing[1] = face->glyph->bitmap.rows;
ch.size[0] = face->glyph->bitmap_left;
ch.size[1] = face->glyph->bitmap_top;
ch.advance = face->glyph->advance.x;
characters[c] = ch;
}
FT_Done_Face(face);
FT_Done_FreeType(ft);
//
// Create VAO
//
glCreateVertexArrays(1, &textVAO);
glBindVertexArray(textVAO);
//
// Create the unique VBO
//
glCreateBuffers(1, &VBO);
glNamedBufferStorage(VBO, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_STORAGE_BIT);
glVertexArrayVertexBuffer(textVAO, 0, VBO, 0, sizeof(GLfloat) * 4);
glVertexArrayAttribFormat(textVAO, 0, 4, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribBinding(textVAO, 0, 0);
glEnableVertexArrayAttrib(textVAO, 0);
//
// Send color to fragment shader
//
glUniform3f(6, 0.88f, 0.59f, 0.07f);
}
void drawText(float x, float y, float scale, char *text)
{
glEnable(GL_CULL_FACE);
glUseProgram(textShader);
glBindVertexArray(textVAO);
//
// Draw each character
//
char *c = text;
while(*c != 0)
{
Character ch = characters[(int)*c];
if(ch.bearing[0] != 0 && ch.bearing[1] != 0)
{
GLfloat xpos = x + ch.bearing[0] * scale;
GLfloat ypos = y - (ch.size[1] - ch.bearing[1]) * scale;
//
GLfloat w = ch.size[0] * scale;
GLfloat h = ch.size[1] * scale;
//
// Update VBO for each character
//
GLfloat vertices[6*4] =
{
xpos, ypos + h, 0.0f, 0.0f ,
xpos, ypos, 0.0f, 1.0f ,
xpos + w, ypos, 1.0f, 1.0f ,
xpos, ypos + h, 0.0f, 0.0f ,
xpos + w, ypos, 1.0f, 1.0f ,
xpos + w, ypos + h, 1.0f, 0.0f
};
glNamedBufferSubData(VBO, 0, sizeof(GLfloat)*6*4, vertices);
glBindTexture(GL_TEXTURE_2D, ch.texture);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
x += (ch.advance >> 6) * scale;
c++;
}
glDisable(GL_CULL_FACE);
}
The vertex shader:
#version 460 core
layout (location = 0) in vec4 vertex; // <vec2 pos, vec2 tex>
layout (location = 1) uniform mat4 projection;
out vec2 TexCoords;
void main()
{
gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);
TexCoords = vertex.zw;
}
The fragment shader:
#version 460 core
in vec2 TexCoords;
out vec4 color;
layout (binding = 0) uniform sampler2D text;
layout (location = 6) uniform vec3 textColor;
void main()
{
color = vec4(textColor, 1.0) * texture(text, TexCoords).r;
}

Broken perspective projection matrix in OpenGL

I've been working on the transformations tutorial from open.gl and am having trouble making my perspective projection matrix work. The tutorial uses GLM, but I chose to roll my own matrix math functions to try and learn the math a little better. Everything compiles fine (gcc -Wall), and my rotation and lookat matrix functions are working perfectly, but my perspective projection matrix causes a black screen with no OpenGL errors.
The projection matrix is (I think) supposed to be
/ cot(fovy/2)/aspect 0.0 0.0 0.0 \
| 0.0 cot(fovy/2) 0.0 0.0 |
| 0.0 0.0 (zfar + znear)/(znear - zfar) -1.0 |
\ 0.0 0.0 (2 * zfar * znear)/(znear - zfar) 0.0 /
Interestingly, I can provide the intended effect with the matrix
/ cot(fovy/2)/aspect 0.0 0.0 0.0 \
| 0.0 cot(fovy/2) 0.0 0.0 |
| 0.0 0.0 (zfar + znear)/(znear - zfar) -1.0 |
\ 0.0 0.0 0.4 1.0 /
Here are the necessary source files. You'll need GLFW3 and SOIL to compile the code -- I've been using gcc -Wall -Werror -std=c99 -lGL -lGLEW -lglfw -lm -lSOIL transform.c -o transform. I've tried to provide shorter (non-compiling) versions of the source below in case there are any glaring errors.
transform.c:
#include <math.h>
#define M_PI (3.14159265358979323846)
#include <stdio.h>
#include <stdlib.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <SOIL/SOIL.h>
typedef struct mat4_t {
float arr[16];
} mat4_t;
typedef struct vec3_t {
float arr[3];
} vec3_t;
/* forward declarations... */
/* return a 4x4 'lookat' matrix to be multiplied by model space coords */
mat4_t mat4mklook(const vec3_t eye, const vec3_t center, const vec3_t up) {
/* check out the OpenGL gluLookAt documentation for an explanation */
vec3_t f = vec3norm(vec3sub(center, eye));
vec3_t up_ = vec3norm(up);
vec3_t s = vec3cross(f, up_);
vec3_t u = vec3cross(s, f);
return (mat4_t) { {
s.arr[0], s.arr[1], s.arr[2], 0.0f,
u.arr[0], u.arr[1], u.arr[2], 0.0f,
-f.arr[0], -f.arr[1], -f.arr[2], 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
} };
}
/* return a 4x4 persp. projection matrix to be multiplied by camera coords */
mat4_t mat4mkproj(const float fovy, const float aspect, const float znear, const float zfar) {
float f = 1 / tan(fovy / 2.0f);
return (mat4_t){ {
f/aspect, 0.0f, 0.0f, 0.0f,
0.0f, f, 0.0f, 0.0f,
0.0f, 0.0f, (zfar+znear)/(znear-zfar), (2*zfar*znear)/(znear-zfar),
0.0f, 0.0f, -1.0f, 0.0f
} };
}
/* returns a 4x4 rotation matrix of magnitude 'th' about unit vector 'axis' */
mat4_t mat4mkrot(const vec3_t axis, const float th) {
const float uX = axis.arr[0];
const float uY = axis.arr[1];
const float uZ = axis.arr[2];
const float sinth = sin(th);
const float costh = cos(th);
return (mat4_t) { {
costh+pow(uX,2)*(1-costh), uX*uY*(1-costh)-uZ*sinth, uX*uZ*(1-costh)+uY*sinth, 0.0,
uY*uX*(1-costh)+uZ*sinth, costh+pow(uY,2)*(1-costh), uY*uZ*(1-costh)-uX*sinth, 0.0,
uZ*uX*(1-costh)-uY*sinth, uZ*uY*(1-costh)+uX*sinth, costh+pow(uZ,2)*(1-costh), 0.0,
0.0, 0.0, 0.0, 1.0
} };
}
/* returns the product of matrices 'a' and 'b' */
mat4_t mat4mult(const mat4_t a, const mat4_t b) {
mat4_t result;
for(int i = 0; i < 16; ++i) {
result.arr[i] = 0.0f;
for(int j = 0; j < 4; ++j) {
result.arr[i] += a.arr[i / 4 + j] * b.arr[i % 4 + j * 4];
}
}
return result;
}
/* returns the cross product of vectors 'a' and 'b' */
vec3_t vec3cross(const vec3_t a, const vec3_t b) {
return (vec3_t){ {
a.arr[1] * b.arr[2] - a.arr[2] * b.arr[1],
a.arr[2] * b.arr[0] - a.arr[0] * b.arr[2],
a.arr[0] * b.arr[1] - a.arr[1] * b.arr[0]
} };
}
/* returns a unit vector derived from vector 'v' */
vec3_t vec3norm(const vec3_t a) {
vec3_t result;
float mag;
if((mag = sqrt(pow(a.arr[0], 2) + pow(a.arr[1], 2) + pow(a.arr[2], 2))) == 0.0f) {
result = (vec3_t) {{0}};
} else {
for(int i = 0; i < 3; ++i) {
result.arr[i] = a.arr[i] / mag;
}
}
return result;
}
/* return the vector difference 'a' - 'b' */
vec3_t vec3sub(const vec3_t a, const vec3_t b) {
vec3_t result;
for(int i = 0; i < 3; ++i) {
result.arr[i] = a.arr[i] - b.arr[i];
}
return result;
}
/* returns the dot product of vectors 'a' and 'b' */
float vec3dot(const vec3_t a, const vec3_t b) {
return a.arr[0] * b.arr[0] +
a.arr[1] * b.arr[1] +
a.arr[2] * b.arr[2];
}
GLfloat vertices[] = {
/* position texture */
-0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, 0.0f, 1.0f
};
GLuint elements[] = {
0, 1, 2,
2, 3, 0
};
int main() {
glfwInit();
/* context settings */
/* window & context creation */
GLFWwindow * const window = glfwCreateWindow(800, 600, "OpenGL", NULL, NULL);
glfwMakeContextCurrent(window);
/* glew initialization -- generates harmless error */
glewExperimental = GL_TRUE;
glewInit();
glGetError();
/* vertex setup */
/* shader setup */
/* vertex attribute setup */
/* texture setup */
GLint modeluni;
{ /* matrix uniform setup */
modeluni = glGetUniformLocation(shaderProgram, "model");
mat4_t viewmat = mat4mklook((vec3_t){{1.2f, 1.2f, 1.2f}}, (vec3_t){{0.0f, 0.0f, 0.0f}}, (vec3_t){{0.0f, 0.0f, 1.0f}});
GLint viewuni = glGetUniformLocation(shaderProgram, "view");
glUniformMatrix4fv(viewuni, 1, GL_TRUE, viewmat.arr);
mat4_t projmat = mat4mkproj(M_PI / 4.0f, 800.0f / 600.0f, 1.0f, 10.0f);
GLint projuni = glGetUniformLocation(shaderProgram, "proj");
glUniformMatrix4fv(projuni, 1, GL_TRUE, projmat.arr);
}
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
while(!glfwWindowShouldClose(window)) {
const GLuint error = glGetError();
if(error) {
fprintf(stderr, "%d\n", error);
}
glClear(GL_COLOR_BUFFER_BIT);
mat4_t modmat = mat4mkrot((vec3_t){{0.0f, 0.0f, 1.0f}}, (glfwGetTime() / 2.0) * M_PI);
glUniformMatrix4fv(modeluni, 1, GL_TRUE, modmat.arr);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
/* delete opengl ids */
glfwTerminate();
return 0;
}
vert.glsl:
#version 330
in vec2 position;
in vec3 color;
in vec2 texcoord;
out vec3 Color;
out vec2 Texcoord;
uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;
void main() {
Color = color;
Texcoord = texcoord;
gl_Position = proj * view * model * vec4(position.x, position.y, 0.0, 1.0);
}
frag.glsl:
#version 330
in vec3 Color;
in vec2 Texcoord;
out vec4 outColor;
uniform sampler2D texKitten;
uniform sampler2D texPuppy;
void main() {
vec4 colKitten = texture(texKitten, Texcoord);
vec4 colPuppy = texture(texPuppy, Texcoord);
outColor = mix(colKitten, colPuppy, 0.5);
}

gluPerspective not seeing all the objects im drawing

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.

how to convert OpenGL code using vertex arrays into code using vertex buffer objects?

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;
}

Glut Reshape Function Not Working

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();
}

Resources