I'm trying to move my code over to modern Opengl, but am having trouble. Right now my code will draw a cube and it will put a texture on, but it will only attach the first texture to all of my face. I am also using SOIL to load my textures into my program. What am I doing wrong?
This is my code:
class Rectangle
{
public:
Rectangle();
Rectangle(float x, float y, float z, float width, float height, float depth, string frontFace, string backFace, string leftFace,
string RightFace, string topFace, string bottomFace);
void Draw();
private:
GLuint m_Textures[6];
string m_TextureNames[6];
GLfloat m_Vertices[72]; // v0,v1,v2,v3 (front)
// normal array
GLfloat m_Normals[72]; // v0,v1,v2,v3 (front)
// color array
GLfloat m_Colours[72]; // v0,v1,v2,v3 (front)
// index array of vertex array for glDrawElements() & glDrawRangeElement()
GLubyte m_Indices[36]; // front
GLfloat m_Texcoords[48];
};
Rectangle::Rectangle(float x, float y, float z, float width, float height, float depth, string topFace, string bottomFace, string frontFace,
string backFace, string leftFace, string rightFace)
{
m_CenterX = x;
m_CenterY = y;
m_CenterZ = z;
m_Width = width;
m_Height = height;
m_Depth = depth;
m_TextureNames[0] = topFace;
m_TextureNames[1] = bottomFace;
m_TextureNames[2] = frontFace;
m_TextureNames[3] = backFace;
m_TextureNames[4] = leftFace;
m_TextureNames[5] = rightFace;
m_ObjectType = Textured;
GLfloat tempVert[] = { // front
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// top
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
-1.0, 1.0, -1.0,
// back
1.0, -1.0, -1.0,
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
// bottom
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// left
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0,
// right
1.0, -1.0, 1.0,
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
};
// normal array
GLfloat tempNormals[] = { 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0,v1,v2,v3 (front)
1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0,v3,v4,v5 (right)
0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0,v5,v6,v1 (top)
-1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1,v6,v7,v2 (left)
0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7,v4,v3,v2 (bottom)
0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 }; // v4,v7,v6,v5 (back)
// color array
GLfloat tempColors[] = { 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, // v0,v1,v2,v3 (front)
1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, // v0,v3,v4,v5 (right)
1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, // v0,v5,v6,v1 (top)
1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, // v1,v6,v7,v2 (left)
0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, // v7,v4,v3,v2 (bottom)
0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1 }; // v4,v7,v6,v5 (back)
// index array of vertex array for glDrawElements() & glDrawRangeElement()
GLubyte tempIndices[] = { 0, 1, 2, 2, 3, 0, // front
4, 5, 6, 6, 7, 4, // right
8, 9,10, 10,11, 8, // top
12,13,14, 14,15,12, // left
16,17,18, 18,19,16, // bottom
20,21,22, 22,23,20 }; // back
GLfloat tempTexcoords[2*4*6] = {
// front
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
0.0, 1.0,
};
for (int i = 1; i < 6; i++)
memcpy(&tempTexcoords[i*4*2], &tempTexcoords[0], 2*4*sizeof(GLfloat));
copy(tempVert, tempVert + 72, m_Vertices);
copy(tempNormals, tempNormals + 72, m_Normals);
copy(tempColors, tempColors + 72, m_Colours);
copy(tempIndices, tempIndices + 36, m_Indices);
std::copy(tempTexcoords, tempTexcoords + 48, m_Texcoords);
LoadTexture(m_TextureNames);
}
void Rectangle::LoadTexture(string TextureName[6])
{
// Create texture index array.
glGenTextures(6, m_Textures);
for(int i = 0 ; i < 1 ; i++)
{
glBindTexture(GL_TEXTURE_2D, m_Textures[i]);
// Set our texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // NOTE the GL_NEAREST Here!
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // NOTE the GL_NEAREST Here!
std::string fileType;
fileType.append(m_TextureNames[i], m_TextureNames[i].size()-3,3);
if(fileType == "jpg")
{
m_Textures[i] = SOIL_load_OGL_texture // load an image file directly as a new OpenGL texture
(
m_TextureNames[i].c_str(),
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
);
// allocate a texture name
}
else
{
m_Textures[i] = SOIL_load_OGL_texture // load an image file directly as a new OpenGL texture
(
m_TextureNames[i].c_str(),
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
);
// allocate a texture name
}
}
}
// Function to draw Sphere.
void Rectangle::Draw()
{
// enable and specify pointers to vertex arrays
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glNormalPointer(GL_FLOAT, 0, m_Normals);
glTexCoordPointer(2, GL_FLOAT, 0, m_Texcoords);
glColorPointer(3, GL_FLOAT, 0, m_Colours);
glVertexPointer(3, GL_FLOAT, 0, m_Vertices);
for (int i=0;i<6;i++)
{
glPushMatrix();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_Textures[i]);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, m_Indices);
glPopMatrix();
}
glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}
Rectangle testRect;
// Drawing routine.
void drawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
testRect.Draw();
glutSwapBuffers();
}
// Initialization routine.
void setup(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
testRect = Rectangle(2, 0.0, 0.0, 1, 2, 1, "grass.bmp","grass.bmp", "grass.bmp", "launch.png", "launch.png", "launch.png");
// Turn on OpenGL texturing.
glEnable(GL_TEXTURE_2D);
glShadeModel (GL_SMOOTH);
}
The posted code has a few issues:
It's loading only one texture:
glGenTextures(6, m_Textures);
for(int i = 0 ; i < 1 ; i++)
{
glBindTexture(GL_TEXTURE_2D, m_Textures[i]);
...
If you want to load 6 textures, like the rest of the code suggests, you'll have to use 6 for the end value of the loop:
for(int i = 0 ; i < 6 ; i++)
It's creating texture ids twice, and sets parameters with the wrong texture bound. At the start of LoadTexture(), it generates 6 texture ids:
glGenTextures(6, m_Textures);
and then binds them, and makes glTexParameteri() to set various parameters on them. But then it calls SOIL_load_ogl_texture() with a flag asking it to create a new id again, and then stores that one away:
m_Textures[i] = SOIL_load_OGL_texture(
m_TextureNames[i].c_str(),
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
);
To fix this, you can omit the gGenTextures() call, and move the code to bind the texture and call glTexParameteri() after the SOIL_load_ogl_texture() call. Also, this uses a flag to generate mipmaps, but sets the texture filters to not use mipmapping.
In the draw function, it loops over the 6 faces, but then draws the entire cube each time:
for (int i=0;i<6;i++)
{
glPushMatrix();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_Textures[i]);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, m_Indices);
glPopMatrix();
}
The second argument to glDrawElements() specifies the number of vertices to be rendered. With the value 36, all vertices will be used (6 sides of the cube, with 2 triangles each, with 3 vertices each.
Also, the glPushMatrix()/glPopMatrix() serves absolutely no purpose. The draw loop should look something like this:
glActiveTexture(GL_TEXTURE0);
for (int i=0;i<6;i++)
{
glBindTexture(GL_TEXTURE_2D, m_Textures[i]);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, m_Indices + i * 6);
}
I don't see the depth test being enabled anywhere. Add this to setup():
glEnable(GL_DEPTH_TEST);
I do it a little differently that works, so maybe the issue is in the difference.
I would bind each texture to a different GL_Texture (GL_Texture0, GL_Texture1...) so that each texture has it's own data. I don't know how SOIL works, but in my case for the first texture after:
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
I would include a call:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture1Width, texture1Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bitmapData);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_Textures[0]);
And I would repeat this process for each of the 6 textures.
Then I would draw each face:
// First face
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_Textures[0]);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, m_Indices);
// Second face
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_Textures[1]);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, m_Indices);
And so on for each face.
EDIT:
I did some checking about SOIL, and it looks to me like (using SOIL) you would:
GLuint m_Textures[6];
int img_width, img_height;
glGenTextures(6, m_Textures);
// For each texture
unsigned char* img = SOIL_load_image(m_TextureNames[0].c_str(), &img_width, &img_height, NULL, 0); // or m_TextureNames[1].c_str() ...
glBindTexture(GL_TEXTURE_2D, m_Textures[0]); // or m_textures[1]...
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // NOTE the GL_NEAREST Here!
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); // NOTE the GL_NEAREST Here!
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
glActiveTexture(GL_TEXTURE0); // or GL_TEXTURE1....
glBindTexture(GL_TEXTURE_2D, m_Textures[0]); // or m_Textures[1]...
Related
I'm using opengl, glfw and glew. I want to rotate the tip of the spaceship without moving the whole spaceship when users press on the left and right arrow respectively. I've tried using gltransform glrotate, it does rotate but it also move my spaceship along. The output of the movement of spaces
objects objects::rotateSpaceship(GLFWwindow * window, objects & sp)
{
GLfloat spaceship_angle = sp.getAngle();
GLfloat newAngle = sp.getAngle() + 0.5;
sp.setAngle(newAngle);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
GLfloat spaceShipRightLine[] =
{
x, y + 80, 0,
x - 50, y - 50, 0
};
GLfloat spaceShipLeftLine[] = {
x, y + 80, 0,
x + 50, y - 50, 0
};
GLfloat spaceShipMiddleLine[] = {
sp.x - 30 ,sp.y,0,
sp.x + 35,sp.y,0
};
glPushMatrix();
glTranslatef(0.0, 0.01, 0.0); // 3. Translate to the object's position.
glRotatef(sp.getAngle(), 0.0, 0.0, 1.0); // 2. Rotate the object.
glTranslatef(0.0, 0.01, 0.0); // 1. Translate to the origin.
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, spaceShipRightLine);
glDrawArrays(GL_LINES, 0, 2);
glDisableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, spaceShipLeftLine);
glDrawArrays(GL_LINES, 0, 2);
glDisableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, spaceShipMiddleLine);
glDrawArrays(GL_LINES, 0, 2);
glDisableClientState(GL_VERTEX_ARRAY);
glPopMatrix();
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
glfwTerminate();
return sp;
}
Note, that drawing by glBegin/glEnd sequences and the fixed function matrix stack is deprecated since decades.
Read about Fixed Function Pipeline and see Vertex Specification and Shader for a state of the art way of rendering.
I want to rotate the tip of the spaceship without moving the whole spaceship [...]
First you have to define the pivot, which is the "tip" of the spaceship:
float pivot_x = sp.x;
float pivot_y = sp.y + 80.0f;
To rotate around a pivot you have to define a model matrix, which displaces by the inverted pivot, then rotate (glRotatef) and final transforms back by to the pivot (glTranslate):
glTranslatef(pivot_x, pivot_y, 0);
glRotatef(angle, 0, 0, 1);
glTranslatef(-pivot_x, -pivot_y, 0);
The final code may look like that:
float pivot_x = x;
float pivot_y = y + 80.0f;
glPushMatrix();
glTranslatef(pivot_x, pivot_y, 0 ); // 3. Translate to the object's position.
glRotatef(sp.getAngle(), 0.0, 0.0, 1.0); // 2. Rotate the object.
glTranslatef(-pivot_x, -pivot_y, 0.0); // 1. Translate to the origin.
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, spaceShipRightLine);
glDrawArrays(GL_LINES, 0, 2);
glDisableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, spaceShipLeftLine);
glDrawArrays(GL_LINES, 0, 2);
glDisableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, spaceShipMiddleLine);
glDrawArrays(GL_LINES, 0, 2);
glDisableClientState(GL_VERTEX_ARRAY);
glPopMatrix();
I separate moveable 3d object and non moveable 3d. I can generate 2 textures for non moveables : background color texture and background depth texture . I have no problem. The values are ok for both. I check the value with a gray gradient texture for the depth.
And I would like to write / fill the color buffer and the depth buffer in opengl with those texture but the depth doesn't work (the color buffer is fine on the screen).
My goal is to never recompute the non movable 3d objects when the camera doesn't move.
(rem : The depth buffer bits size is always in 16 bits)
This is my code for generate the depth texture :
U16 m_backgroundDepthBuffer[4096 * 4096]; // it's a member of my class
glReadPixels(0,0, width(), height(), GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, (void*)m_backgroundDepthBuffer);
// Allocate GPU-memory for the depth-texture.
glDeleteTextures(1, &m_backgroundDepthTextureId);
glGenTextures(1, &m_backgroundDepthTextureId);
glBindTexture(GL_TEXTURE_2D, m_backgroundDepthTextureId);
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_DEPTH_COMPONENT16,
width(), height(), 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, m_backgroundDepthBuffer);
This is my code for filling the color buffer :
void Application::Render()
{
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
// render background
Render::RenderImage(m_backgroundTextureId, 0,0, width(), height());
// for debug
// Render::RenderImage(m_backgroundDepthGrayTextureId, 0,0, width(), height());
// This is how I fill the depth buffer : it's work but slow
glDrawPixels(width(), height(), GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, (GLvoid*) m_backgroundDepthBuffer); //
// doesn't work
// Render::RenderDepth(m_backgroundDepthTextureId, 0,0, width(), height());
}
This is my Render::RenderImage() : it works
void Render::RenderImage(U32 tex, int x, int y, int w, int h, float anchorX, float anchorY)
{
glClear(GL_DEPTH_BUFFER_BIT);
GLboolean depth = glIsEnabled(GL_DEPTH_TEST);
if (depth)
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, s_width, s_height, 0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glColor3ub(255, 255, 255);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, tex);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
x -= (int)(anchorX * w);
y -= (int)(anchorY * h);
gVertices[0] = VECTOR3F(x, y, 0);
gVertices[1] = VECTOR3F(x + w - 1, y, 0);
gVertices[2] = VECTOR3F(x + w - 1, y + h - 1, 0);
gVertices[3] = VECTOR3F(x, y + h - 1, 0);
gTexCoords[0] = VECTOR2F(0, 1);
gTexCoords[1] = VECTOR2F(1, 1);
gTexCoords[2] = VECTOR2F(1, 0);
gTexCoords[3] = VECTOR2F(0, 0);
gIndexes[0] = 2;
gIndexes[1] = 1;
gIndexes[2] = 0;
gIndexes[3] = 0;
gIndexes[4] = 3;
gIndexes[5] = 2;
glVertexPointer(3, GL_FLOAT, 0, gVertices);
glTexCoordPointer(2, GL_FLOAT, 0, gTexCoords);
glDrawElements(GL_TRIANGLES, 3 * 2, GL_UNSIGNED_SHORT, gIndexes);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
if (depth)
glEnable(GL_DEPTH_TEST);
}
This is my Render::RenderDepth() : it doesn't work / I have a texture with depth = 0.0f instead to use the depth of each texel.
I want only to change the depth buffer and do nothing to the color buffer
Render::RenderDepth() is similar to Render::RenderImage() : I render 2 triangles
void Render::RenderDepth(U32 tex, int x, int y, int w, int h, float anchorX, float anchorY)
{
glClear(GL_DEPTH_BUFFER_BIT);
/*glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_FUNC, GL_ALWAYS);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_DEPTH_TEXTURE_MODE, GL_ALPHA);
*/
GLboolean depth = glIsEnabled(GL_DEPTH_TEST);
//if (depth)
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, s_width, s_height, 0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glColor3ub(255, 255, 255);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, tex);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
x -= (int)(anchorX * w);
y -= (int)(anchorY * h);
gVertices[0] = VECTOR3F(x, y, 0.0);
gVertices[1] = VECTOR3F(x + w - 1, y, 0.0);
gVertices[2] = VECTOR3F(x + w - 1, y + h - 1, 0.0);
gVertices[3] = VECTOR3F(x, y + h - 1, 0.0);
gTexCoords[0] = VECTOR2F(0, 1);
gTexCoords[1] = VECTOR2F(1, 1);
gTexCoords[2] = VECTOR2F(1, 0);
gTexCoords[3] = VECTOR2F(0, 0);
gIndexes[0] = 2;
gIndexes[1] = 1;
gIndexes[2] = 0;
gIndexes[3] = 0;
gIndexes[4] = 3;
gIndexes[5] = 2;
glVertexPointer(3, GL_FLOAT, 0, gVertices);
glTexCoordPointer(2, GL_FLOAT, 0, gTexCoords);
glDrawElements(GL_TRIANGLES, 3 * 2, GL_UNSIGNED_SHORT, gIndexes);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
I am new to OpenGL. I have the following code that I am using from a tutorial I followed, what it does is render a tile map. It does this successfully but my problem now is that I want to add a moveable object onto the window however it is not appearing.
#include "stdafx.h"
#include <string>
#include <windows.h>
#include <iostream>
#include <conio.h>
#include <sstream>
#include <math.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include "GL/freeglut.h"
#pragma comment(lib, "OpenGL32.lib")
// window size and update rate (60 fps)
int width = 700;
int height = 700;
int interval = 1000 / 60;
// ball
float ball_pos_x = width / 2;
float ball_pos_y = height / 2;
float ball_dir_x = -1.0f;
float ball_dir_y = 0.0f;
int ball_width = 20;
int ball_height = 20;
int ball_speed = 5;
GLuint texture; //the array for our texture
GLuint texture2; //the array for our second texture
void keyboard() {
if (GetAsyncKeyState(VK_LEFT)) ball_pos_x -= ball_speed;
if (GetAsyncKeyState(VK_RIGHT)) ball_pos_x += ball_speed;
if (GetAsyncKeyState(VK_UP)) ball_pos_y += ball_speed;
if (GetAsyncKeyState(VK_DOWN)) ball_pos_y -= ball_speed;
}
int cMap[30][30] = { //our map
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
};
void drawRect(float x, float y, float width, float height) {
glBegin(GL_QUADS);
glVertex2f(x, y);
glVertex2f(x + width, y);
glVertex2f(x + width, y + height);
glVertex2f(x, y + height);
glEnd();
}
GLuint LoadTexture( const char * filename, int width, int height )
{
GLuint texture;
unsigned char * data;
FILE * file;
//The following code will read in our RAW file
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
GL_MODULATE ); //set texture environment parameters
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR );
//Here we are setting the parameter to repeat the texture
//instead of clamping the texture
//to the edge of our shape.
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_REPEAT );
//Generate the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
GL_RGB, GL_UNSIGNED_BYTE, data);
free( data ); //free the texture
return texture; //return whether it was successfull
}
void FreeTexture( GLuint texture )
{
glDeleteTextures( 1, &texture );
}
void drawTiles (void) { //our function to draw the tiles
for (int i = 0; i < 10; i++) //loop through the height of the map
{
for (int j = 0; j < 10; j++) //loop through the width of the map
{
if (cMap[i][j] == 0) //if the map at this position contains a 0
{
glBindTexture( GL_TEXTURE_2D, texture ); //bind our grass texture to our shape
}
else //otherwise
{
glBindTexture( GL_TEXTURE_2D, texture2 ); //bind our dirt texture to our shape
}
glPushMatrix(); //push the matrix so that our translations only affect this tile
glTranslatef(j, -i, 0); //translate the tile to where it should belong
glBegin (GL_QUADS); //begin drawing our quads
glTexCoord2d(0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0); //with our vertices we have to assign a texcoord
glTexCoord2d(1.0, 0.0);
glVertex3f(1.0, 0.0, 0.0); //so that our texture has some points to draw to
glTexCoord2d(1.0, 1.0);
glVertex3f(1.0, 1.0, 0.0);
glTexCoord2d(0.0, 1.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glPopMatrix(); //pop the matrix
} //end first loop
} //end second loop
}
void draw() {
// clear (has to be done at the beginning)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity(); // ToDo: draw our scene
// draw ball
drawRect(ball_pos_x - ball_width / 2, ball_pos_y - ball_height / 2, ball_width, ball_height);
glEnable( GL_TEXTURE_2D );
glTranslatef(-5, 4, -20); //translate back a bit to view the map correctly
drawTiles(); //draw our tiles
// swap buffers (has to be done at the end)
glutSwapBuffers();
}
void UpdatePlayer(){
// hit by right racket?
if (ball_pos_x < ball_pos_x + ball_width &&
ball_pos_x > enemy_pos_x &&
ball_pos_y < enemy_pos_y + enemy_height &&
ball_pos_y > enemy_pos_y) {
ball_pos_x = ball_pos_x;
ball_pos_y = ball_pos_y;
}
}
void update(int value) { // Call update() again in 'interval' milliseconds
// input handling
keyboard();
UpdatePlayer();
glutTimerFunc(interval, update, 0);
// Redisplay frame
glutPostRedisplay();
}
void enable2D(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width, 0.0f, height, 0.0f, 1.0f);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
}
void reshape (int w, int h) {
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}
int _tmain(int argc, char** argv)
{
// initialize opengl (via glut)
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(width, height); glutCreateWindow("noobtuts.com Pong");
// Register callback functions
glutDisplayFunc(draw);
glutIdleFunc (draw);
glutReshapeFunc (reshape);
glutTimerFunc(interval, update, 0);
// setup scene to 2d mode and set draw color to white
enable2D(width, height);
glColor3f(1.0f, 1.0f, 1.0f);
//Load our texture
texture = LoadTexture("texture.raw", 256, 256);
texture2 = LoadTexture("texture2.raw", 256, 256);
glutMainLoop ();
//Free our texture
FreeTexture(texture);
FreeTexture(texture2);
return 0;
}
If I was to comment out in the main...
glutIdleFunc (draw);
glutReshapeFunc (reshape);
The tile map will disappear and my moveable square is visible and works...I just can't implement the two together successfully. Again i'm completely new to this so apologise if I am doing something really stupid Any ideas where I am going wrong?
Are you sure you want to draw the tile map with a perspective projection? It seems to me that you should be using an orthographic projection for both the tile map and the ball.
Change your reshape function to simply call enable2D(w, h). Then change your drawTiles function to draw using screen coordinates instead. That should work.
Some additional notes:
Don't forget to disable texturing when drawing your ball (you don't seem to be setting any texture for it, so it will just render with the last texture set).
You could also disable depth testing with glDisable(GL_DEPTH_TEST) since you don't really need it (and use glVertex2f for drawing the tile map instead of glVertex3f)
I'm using Deferred Shading method to render the scene, but I have a problem with a Skybox technique due to weird behaviour of Z-Buffer. I've created additional Framebuffer and attached 5 textures, one of which is being used as a depth buffer. First pass is a geometry pass, which fills the textures with needed data, second pass renders the final objects with textures and lightning applied to the main framebuffer, the last pass renders Skybox. The problem is Skybox being ignored (Z-Buffer check fails, so it is invisible).
When rendering a Skybox, I map the secondary framebuffer as a GL_READ_FRAMEBUFFER and main framebuffer (screen) as a GL_DRAW_FRAMEBUFFER, so the depth buffer of the secondary framebuffer can be used, then I set the depth function to GL_LEQUAL. And only if I change depth function to GL_GREATER (or GL_ALWAYS) the Skybox can be seen, however it is being rendered on top of the objects.
The Vertex Shader:
#version 330
layout (location = 0) in vec3 Position;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
out vec3 TexCoord0;
void main()
{
vec4 MVP_Pos = P * V * M * vec4(Position, 1.0);
gl_Position = MVP_Pos.xyww;
TexCoord0 = Position;
}
Model matrix is a product of translation of the Skybox to the camera coordinates.
glDepthFunction set to GL_LEQUAL:
glDepthFunction set to GL_GREATER:
Contents of the Z-Buffer:
UPDATE 1: I've tried to use glBlitFramebuffer like that:
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo); //Additional framebuffer
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glDepthMask(GL_TRUE);
glBlitFramebuffer(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
But it doesn't work. Main depth buffer contains array of black pixels.
UPDATE 2:
//FBO initialization
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
// Create gbuffer textures
glGenTextures(ARRAY_SIZE_IN_ELEMENTS(m_textures), m_textures);
glGenTextures(1, &m_depthTexture);
for (unsigned int i = 0; i < ARRAY_SIZE_IN_ELEMENTS(m_textures); i++) {
glBindTexture(GL_TEXTURE_2D, m_textures[i]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, WindowWidth, WindowHeight, 0, GL_RGB, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_textures[i], 0);
}
// depth buffer
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
glDrawBuffers(ARRAY_SIZE_IN_ELEMENTS(DrawBuffers), DrawBuffers);
GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (Status != GL_FRAMEBUFFER_COMPLETE) {
fprintf(stderr, "FB error, status: 0x%x\n", Status);
return false;
}
Skybox buffers:
GLfloat cube_vertices[] = {
// front
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// back
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
-1.0, 1.0, -1.0,
};
GLushort cube_elements[] = {
// front
0, 1, 2,
2, 3, 0,
// top
3, 2, 6,
6, 7, 3,
// back
7, 6, 5,
5, 4, 7,
// bottom
4, 5, 1,
1, 0, 4,
// left
4, 0, 3,
3, 7, 4,
// right
1, 5, 6,
6, 2, 1,
};
When rendering a Skybox, I map the secondary framebuffer as a
GL_READ_FRAMEBUFFER and main framebuffer (screen) as a
GL_DRAW_FRAMEBUFFER, so the depth buffer of the secondary framebuffer
can be used,
That is not how things work. The GL_READ_FRAMEBUFFER is not relevant for the depth test. It is used as the source for opeations like glReadPixels or glBlitFramebuffer. But for any kind of rendering, only the GL_DRAW_FRAMEBUFFER is relevant. This includes the depth test.
Unfortuanly, you can't mix user-defined render targets like render buffers or textures with window-system provided buffers, so you just can't render to the final screen while using the specific depth test. So you either have to do an additional render pass to an FBO using the custom depth buffer, and blit the result to the screen, or you can blit the contents of the custom depth buffer to the window-system provided one and render with that.
I found a solution. Additional framebuffer had 32 bits/pixel, but main framebuffer had only 24, that prevented glBlitFramebuffer from working. So the proper Framebuffer initialization would look like that:
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
NULL);
I'm trying implement tile mapping using openGL and C++.
I found this
tutorial/explanation which I thought was pretty good.
When I compile and run the code in visual studio 2010 it just opens a window and displays a white square.
Maybe my files aren't loading correctly. I've tried the .raw files the website uses as well as my own .png files.
#include <GL/gl.h>
#include <GL/glut.h>
#include <windows.h>
#include <stdio.h>
GLuint texture; //the array for our texture
GLuint texture2; //the array for our second texture
int cMap[10][10] = { //our map
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
};
//function to load the RAW file
GLuint LoadTexture( const char * filename, int width, int height )
{
GLuint texture;
unsigned char * data;
FILE * file;
//The following code will read in our RAW file
file = fopen( filename, “rb” );
if ( file == NULL ) return 0;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
glGenTextures( 1, &texture )
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
GL_MODULATE ); //set texture environment parameters
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR );
//Here we are setting the parameter to repeat the texture
instead of clamping the texture
//to the edge of our shape.
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_REPEAT );
//Generate the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
GL_RGB, GL_UNSIGNED_BYTE, data);
free( data ); //free the texture
return texture; //return whether it was successfull
}
void FreeTexture( GLuint texture )
{
glDeleteTextures( 1, &texture );
}
void drawTiles (void) { //our function to draw the tiles
for (int i = 0; i < 10; i++) //loop through the height of the map
{
for (int j = 0; j < 10; j++) //loop through the width of the map
{
if (cMap[i][j] == 0) //if the map at this position contains a 0
{
glBindTexture( GL_TEXTURE_2D, texture ); //bind our grass texture to our shape
}
else //otherwise
{
glBindTexture( GL_TEXTURE_2D, texture2 ); //bind our dirt texture to our shape
}
glPushMatrix(); //push the matrix so that our translations only affect
this tile
glTranslatef(j, -i, 0); //translate the tile to where it should belong
glBegin (GL_QUADS); //begin drawing our quads
glTexCoord2d(0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0); //with our vertices we have to assign a texcoord
glTexCoord2d(1.0, 0.0);
glVertex3f(1.0, 0.0, 0.0); //so that our texture has some points to draw to
glTexCoord2d(1.0, 1.0);
glVertex3f(1.0, 1.0, 0.0);
glTexCoord2d(0.0, 1.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glPopMatrix(); //pop the matrix
} //end first loop
} //end second loop
}
void display (void) {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glEnable( GL_TEXTURE_2D );
glTranslatef(-5, 4, -20); //translate back a bit to view the map correctly
drawTiles(); //draw our tiles
glutSwapBuffers();
}
void reshape (int w, int h) {
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}
int main (int argc, char **argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (“A basic OpenGL Window“);
glutDisplayFunc (display);
glutIdleFunc (display);
glutReshapeFunc (reshape);
//Load our texture
texture = LoadTexture(“texture.raw”, 256, 256);
texture2 = LoadTexture(“texture2.raw”, 256, 256);
glutMainLoop ();
//Free our texture
FreeTexture(texture);
FreeTexture(texture2);
return 0;
}
Make sure your working directory is what you're assuming it to be.
Or use absolute file names.
Otherwise fopen() will fail because it can't find the file.