Loaded 2D texture is not binding itself to a QUAD - c++

I've loaded a texture's ID into the tex variable, but when I bind the texture with this ID just before drawing a QUAD (seen in code below inside the renderScene function surrounded by the xxxxxxxxx... comments), no texture is getting applied to the QUAD; it remains colorless. No error messages either.
I've included all the texture-related things I've written in my program.
What else do I need to add/change?
#include<windows.h>
#include <GL/glut.h>
#include<iostream>
#include <stdlib.h>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
// (...)
GLuint loadBMP_custom(const char * imagepath);
GLuint tex = loadBMP_custom("texture.bmp");
GLuint loadBMP_custom( const char * imagepath )
{
GLuint texture;
int width, height;
unsigned char * data;
FILE * file;
file = fopen( imagepath, "rb" );
if ( file == NULL ) return 0;
width = 256;
height = 256;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
for(int i = 0; i < width * height ; ++i)
{
int index = i*3;
unsigned char B,R;
B = data[index];
R = data[index+2];
data[index] = R;
data[index+2] = B;
}
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );
return texture;
}
// (...)
void renderScene(void)
{
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Reset transformations
glLoadIdentity();
// Set the camera
gluLookAt( posX, 1.0f, posZ,
posX+vlx, posY+vly, posZ+vlz,
0.0f, 1.0f, 0.0f);
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glTexCoord2f (0.0, 0.0);
glVertex3f(-100.0f, -0.02f, -100.0f);
glTexCoord2f (0.0, 1.0);
glVertex3f(-100.0f, -0.02f, 100.0f);
glTexCoord2f (1.0, 1.0);
glVertex3f( 100.0f, -0.02f, 100.0f);
glTexCoord2f (1.0, 0.0);
glVertex3f( 100.0f, -0.02f, -100.0f);
glEnd();
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// [Also display 3D blocks in space besides the above QUAD, which serves as ground]
glFlush();
glutSwapBuffers();
}
//(...)
int main(int argc, char **argv)
{
// (...)
glEnable (GL_TEXTURE_2D) ;
glutMainLoop();
return 1;
}

As mentioned in the comments, your method to load a BMP file is incorrect: even if you know how big the image is (256x256), you would still need to skip ahead to the pixel data part (usually 54 bytes, which is the usual size of the header).
So now you could write your own importer by reading the official spec over here: https://en.wikipedia.org/wiki/BMP_file_format
...Or also find many implementations on the web such as the one mentioned in this question: C++: Read bitmap wrong
Unless you find some easy-to-plug header(s)-only library, I would personally go against using a library to specifically deal with BMP files since it introduces extra dependencies for something quite easy to roll on your own (and at the same time, learn how to implement a simple file loader).

Related

Texture doesn't work - OpenGL

I don't know why but my code doesn't run any texture. Can someone tell me how to fix it ?
I'm using a function to load the texture and return the GLuint to a variable and set this variable in the object.
#include <windows.h>
#include <gl/glut.h>
#include <stdlib.h>
#include <stdio.h>
float _angle = 0.0;
int zoomX = 0, zoomY=0;
GLuint texturaGrama;
GLfloat angle, fAspect, rotX, rotY, obsZ;
GLuint LoadTexture( const char * filename, int width, int height ){
GLuint texture;
unsigned char * data;
FILE * 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 );
for(int i = 0; i < width * height ; ++i)
{
int index = i*3;
unsigned char B,R;
B = data[index];
R = data[index+2];
data[index] = R;
data[index+2] = B;
}
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );
return texture;
}
void Desenha(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
// Grama
glPushMatrix();
glColor3f(0.0, 1.0, 0.0);
glTranslatef(0,0,-6);
glRotatef(_angle, 0.0, 1.0, 0.0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texturaGrama);
glBegin(GL_QUADS);
glTexCoord2f(0.0f,0.0f); glVertex3f(-50,-1.5,50);
glTexCoord2f(1.0f,0.0f); glVertex3f(-50,-1.5,-50);
glTexCoord2f(1.0f,1.0f); glVertex3f(50,-1.5,-50);
glTexCoord2f(0.0f,0.0f); glVertex3f(50,-1.5,50);
glEnd();
glDisable(GL_TEXTURE_2D);
}
void PosicionaObservador(void)
{
// Especifica sistema de coordenadas do modelo
glMatrixMode(GL_MODELVIEW);
// Inicializa sistema de coordenadas do modelo
glLoadIdentity();
DefineIluminacao();
// Especifica posição do observador e do alvo
glTranslatef(zoomX,zoomY,-obsZ);
glRotatef(rotX,1,0,0);
glRotatef(rotY,0,1,0);
}
void Inicializa (void)
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
texturaGrama = LoadTexture("grass.bmp", 256, 256);
angle=50;
rotX = 30;
rotY = 0;
obsZ = 10;
}
static void resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
PosicionaObservador();
}
int main(void)
{
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutInitWindowPosition(50,50);
glutCreateWindow("Casa Sinistra");
glutDisplayFunc(Desenha);
glEnable(GL_DEPTH_TEST);
glutSpecialFunc(MovimentoTela);
glutReshapeFunc(resize);
Inicializa();
glutMainLoop();
}
I have tried many other libs but none of them works. I'm running this code in CodeBlocks with Windows 10. The code runs but the texture doesn't appear. It's happening because of Windows ?
I need to add any library?
The GLUT library has to be initilized by glutInit.
Initialize glut at the begin of the program, before you use any instruction of the library:
int main(int argc, char** argv)
{
glutInit(&argc, argv); // <------------
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutInitWindowPosition(50,50);
glutCreateWindow("Casa Sinistra");
.....
Since you are using a double buffered window
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
you have to call glutSwapBuffers at the end of the rendering loop (last statement in the loop), to perform a buffer swap for the current window:
void Desenha(void)
{
......
glutSwapBuffers();
}
By the way there is a mistake in your texture coordinates, because the uv coordinate (0, 0) is twice (glTexCoord2f(0.0f,0.0f)).

error: 'my_texture' does not name a type

I was trying to make simple texturing, but heres an error appeared:
error: 'my_texture' does not name a type
Here there place where it appears(right after LoadTexture method):
GLuint my_texture;
my_texture = LoadTexture( "grass.bmp" );
Here's my code. Whats wrong?
#include <iostream>
#include <GL/gl.h>
#include <GL/glut.h>
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free, rand */
using namespace std;
float _angle = 0.5f;
GLuint LoadTexture( const char * filename )
{
GLuint texture;
int width, height;
unsigned char * data;
FILE * file;
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
width = 1024;
height = 512;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
for(int i = 0; i < width * height ; ++i)
{
int index = i*3;
unsigned char B,R;
B = data[index];
R = data[index+2];
data[index] = R;
data[index+2] = B;
}
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );
return texture;
}
GLuint my_texture;
my_texture = LoadTexture( "grass.bmp" );
void render(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity ();
gluPerspective(90.0, 640.0f/480.0f, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity ();
gluLookAt(1, 1, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
glPushMatrix();
glRotatef(_angle, 0.0f,0.0f,1.0f);
glColor3f(0.0f,0.7f,0.0f);
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 );
glVertex3f( -0.5, 0.5 , 0 );
glVertex3f( 0.5 , 0.5, 0 );
glVertex3f( 0.5, -0.5, 0 );
glVertex3f( -0.5, -0.5, 0 );
glEnd();
glPopMatrix();
_angle +=0.03f;
// check OpenGL error
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR) {
cerr << "OpenGL error: " << err << endl;
}
glutSwapBuffers();
glutPostRedisplay();
}
void init(){
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(640, 480);
glutCreateWindow("test");
glClearColor(0.2,0.2,0.2,0.0);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glutDisplayFunc(render);
glutMainLoop();
}
int main(int argc, char * argv[]) {
glutInit(&argc, argv);
init();
return 0;
}
These two lines appear outside of a function. You may only declare variables there, you can not put statements directly in this scope. Try:
GLuint my_texture = LoadTexture( "grass.bmp" );

OpenGL offscreen rendered texture not displaying on screen

I am having difficulty getting a offscreen rendered texture to to be displayed. I have checked round the web and other questions and am clearly missing something.
I am new to OpenGL so may well be making some naive errors. It is part of a routine to add post processing using a shader to modify the firestor/secondlife viewer project to an equifisheye projection. My test code is based around the GLEW and GLUT framework using OpenGL 1.3 as the viewer is designed to run on older platforms.
The approach is:
set up and initialise the FBO, Render buffers and textures to draw to.
initilise various default settings for drawing the glutCube and glutTeapot :)
The display function
a) using the default framebuffer draws a rotating cube (works fine)
b) the texture is then drawn to
OUTPUT: all black and not the rotating cube.
My code is:
GLuint buffer_fbo;
GLuint bufferColtexture;
GLuint depthBuffer_rb;
typedef struct {
int width;
int height;
char* title;
float field_of_view_angle;
float z_near;
float z_far;
} glutWindow;
glutWindow win;
//
void ShutDown(void)
{
glDeleteFramebuffersEXT(1, &buffer_fbo);
glDeleteRenderbuffersEXT(1, &depthBuffer_rb);
glDeleteTextures(1,&bufferColtexture);
}
float g_potrotation = 0;
float g_potrotation_speed = 0.2f;
float xrot =0;
float yrot = 0;
float zrot = 0;
GLenum g_Drawbuffers[2] = {GL_COLOR_ATTACHMENT0_EXT };
void setupFBO(void)
{
// *********** set up scene FBO including dept buffers and their textures ****************
glGenFramebuffersEXT(1, &buffer_fbo);
// set up render buffers for depth info
glGenRenderbuffersEXT(1, &depthBuffer_rb);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer_rb);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, win.width, win.height);
// Genrate texture to render to
glGenTextures(1, &bufferColtexture);
glBindTexture(GL_TEXTURE_2D, bufferColtexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, win.width, win.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// attach texture to render to to fbo
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, buffer_fbo);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, bufferColtexture, 0);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depthBuffer_rb);
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); // check frame buffer
if(status != GL_FRAMEBUFFER_COMPLETE_EXT)
{
printf("FRAMEBUFFER status error %i \n",status);
exit(1);
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // bind back to default
}
void initialise()
{
setupFBO();
// select projection matrix
glMatrixMode(GL_PROJECTION);
// set the viewport
glViewport(0, 0, win.width, win.height);
// set matrix mode
glMatrixMode(GL_PROJECTION);
// reset projection matrix
glLoadIdentity();
GLfloat aspect = (GLfloat) win.width / win.height;
// set up a perspective projection matrix
gluPerspective(win.field_of_view_angle, aspect, win.z_near, win.z_far);
// specify which matrix is the current matrix
glMatrixMode(GL_MODELVIEW);
glShadeModel( GL_SMOOTH );
// specify the clear value for the depth buffer
glClearDepth( 1.0f );
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
// specify implementation-specific hints
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
GLfloat amb_light[] = { 0.1, 0.1, 0.1, 1.0 };
GLfloat diffuse[] = { 0.6, 0.6, 0.6, 1 };
GLfloat specular[] = { 0.7, 0.7, 0.3, 1 };
glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light );
glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
glEnable( GL_LIGHT0 );
glEnable( GL_COLOR_MATERIAL );
glShadeModel( GL_SMOOTH );
glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE );
glDepthFunc( GL_LEQUAL );
glEnable( GL_DEPTH_TEST );
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glClearColor(0.5, 0.5, 0.5, 1.0);
}
void drawquad(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glDisable(GL_LIGHTING); // This was the cause of the problem, disable lighting worked!
glLoadIdentity(); // Reset The View
glTranslatef(0.0f,0.0f,-5.0f);
glTranslatef(0.0f,0.0f,-5.0f);
glRotatef(xrot,1.0f,0.0f,0.0f);
glRotatef(yrot,0.0f,1.0f,0.0f);
glRotatef(zrot,0.0f,0.0f,1.0f);
glBindTexture(GL_TEXTURE_2D, bufferColtexture);
glBegin(GL_QUADS);
// Front Face
glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f);
glEnd();
xrot+=0.3f;
yrot+=0.2f;
zrot+=0.4f;
glEnable(GL_LIGHTING); // now reenabling the lighting. after adding to fix code.
}
void display(void)
{
// set red background
// draw to fbo
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0);
// Clear Screen and Depth Buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
// set drawing a rotating cube as per default
glLoadIdentity();
// Define a viewing transformation
gluLookAt( 3,1,0, 0,0,0, 0,1,0);
// Push and pop the current matrix stack.
// This causes that translations and rotations on this matrix wont influence others.
glPushMatrix();
glColor3f(0,1,0);
glTranslatef(0,0,0);
glRotatef(g_potrotation,0,1,0);
glRotatef(90,0,1,0);
// Draw the solid cube
glutSolidCube(1);
glPopMatrix();
// draw teapot to fbo
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, buffer_fbo);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT,depthBuffer_rb);
// Clear Screen and Depth Buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Define a viewing transformation
gluLookAt( 4,2,0, 0,0,0, 0,1,0);
// Push and pop the current matrix stack.
// This causes that translations and rotations on this matrix wont influence others.
glPushMatrix();
glColor3f(1,0,0);
glTranslatef(0,0,0);
glRotatef(g_potrotation,0,1,0);
glRotatef(90,0,1,0);
// Draw the teapot
glutSolidTeapot(1);
glPopMatrix();
g_potrotation += g_potrotation_speed;
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0); // reset to default Frame and Render buffer
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT,0);
drawquad();
glutSwapBuffers();
}
// informs OpenGL that window size has changed.
void reshape(int width, int height)
{
}
void idle(void)
{
glutPostRedisplay();
}
int checkglewOK()
{
if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)
printf("Ready for GLSL\n");
else {
printf("Not totally ready :( \n");
exit(1);
};
}
void keyboard (unsigned char key, int mousePositionX, int mousePositionY)
{
switch (key)
{
case KEY_ESCAPE:
exit (0);
break;
default:
break;
}
}
int main(int argc, char** argv)
{
// set window values
win.width = 640;
win.height = 480;
win.title = "Shader Test";
win.field_of_view_angle = 45;
win.z_near = 1.0f;
win.z_far = 500.0f;
////////////////////////////////////////////////////////
// Initialise and Create Window
////////////////////////////////////////////////////////
glutInit(&argc, argv);
// set modes RGB-Alpha, doble bufferedd (prevent flickering)
// has a depth buffer to ensure that 3D object overlp OK
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); // set display mode
// define window size
glutInitWindowSize(win.width, win.height);
glutCreateWindow(win.title); // create the window
glewInit(); // Glew Init occurs after Create Window !!!
checkglewOK();
glutDisplayFunc(display); // register display function
//glutReshapeFunc(reshape); // register resize function
glutIdleFunc(idle); // register idel function
glutKeyboardFunc(keyboard);
initialise();
glutMainLoop(); // run glut main loop
ShutDown();
return EXIT_SUCCESS;
}

How can i use a texture .jpg image for an openGL background window in mac?

I want to set a background for an openGL window for mac. background will take a jpg or png file.
Here is my code..
GLuint texture; //the array for our texture
GLfloat angle = 0.0;
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 );
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
// // when texture area is small, bilinear filter the closest mipmap
// glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
// GL_LINEAR_MIPMAP_NEAREST );
// // when texture area is large, bilinear filter the original
// glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//
// // the texture wraps over at the edges (repeat)
// 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, 2, 2, 0,GL_RGB, GL_UNSIGNED_BYTE, data);
// select modulate to mix texture with color for shading
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_NEAREST );
// when texture area is large, bilinear filter the first mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// // the texture wraps over at the edges (repeat)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
// build our texture mipmaps
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,
GL_RGB, GL_UNSIGNED_BYTE, data );
free(data);
return texture; //return whether it was successful
}
void FreeTexture( GLuint texture ){
glDeleteTextures( 1, &texture );
}
void cube () {
glEnable(GL_TEXTURE_2D);
glBindTexture( GL_TEXTURE_2D, texture ); //bind the texture
glPushMatrix();
glRotatef( angle, 0.0f, 0.0f, 1.0f );
glBegin( GL_QUADS );
glTexCoord2d(0.0,0.0); glVertex2d(-1.0,-1.0);
glTexCoord2d(1.0,0.0); glVertex2d(+1.0,-1.0);
glTexCoord2d(1.0,1.0); glVertex2d(+1.0,+1.0);
glTexCoord2d(0.0,1.0); glVertex2d(-1.0,+1.0);
glEnd();
glPopMatrix();
glutSwapBuffers();
//glutSolidCube(2);
}
void display () {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
texture = LoadTexture( "/Users/macbook/MatrixEngineClientSample/Fighters/Sunset03.jpg", 256, 256 ); //load the texture
glEnable( GL_TEXTURE_2D ); //enable 2D texturing
// glEnable(GL_TEXTURE_GEN_S); //enable texture coordinate generation
// glEnable(GL_TEXTURE_GEN_T);
cube();
FreeTexture( texture );
//glutSwapBuffers();
//angle ++;
}
void reshape (int w, int h) {
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
//glLoadIdentity ();
gluPerspective (50, (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);
glutMainLoop ();
return 0;
}
EDIT
I want to see this image as a background of the openGL window...image is below..
but it showing this...
I consulted this Apple guide.
The problem is that the file is compressed AND has a header, and with your code you are even using part of the file header as an image source.
I would replace this code:
// 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 );
With something more similar to this:
CFURLRef urlRef = (CFURLRef)[NSURL fileURLWithPath:#"/Users/macbook/MatrixEngineClientSample/Fighters/Sunset03.jpg"];
CGImageSourceRef myImageSourceRef = CGImageSourceCreateWithURL(url, NULL);
CGImageRef myImageRef = CGImageSourceCreateImageAtIndex(myImageSourceRef, 0, NULL);
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(myImageRef));
unsigned char *data = CFDataGetBytePtr(data);
You may need to add Core Graphics and Core Foundation to the list of your linked frameworks.
PNG and JPG images (as with most other image formats) require some form of decompression/decoding, so loading them raw from a file wont produce expected results. It should work with bmp or uncompressed tga images after reading the file header though :/ . Anyway, here are a few image loading libraries that should make loading images easy:
SOIL
DevIL
FreeImage
GLI

texture disappears with gluSphere and glutPostRedisplay

I'm just starting with opengl. This is my first project, in fact.
I want to map some texture to a quadrilateral in the background and want to draw a sphere using gluSphere in the front and I want to animate this. So, I map the texture first, then draw the sphere in the display function and then call glutPostRedisplay. It does show the texture and the sphere correctly when display is first called. But, as soon as glutPostRedisplay is called, the texture disappears and only the sphere is drawn. I have given my code below. I apologize for using any bad opengl practices.
void display() {
glClear(GL_COLOR_BUFFER_BIT);
drawTex();
glPushMatrix();
glTranslatef(SIZE/2, SIZE/2, 0);
glutSolidSphere(15.0, 20, 20);
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
void LoadTextureRAW( const char * filename, int wrap ) {
GLuint texture;
int width, height;
unsigned char * data;
FILE * file;
// open texture data
file = fopen( filename, "rb" );
if ( file == NULL ) {
return;
}
// allocate buffer
width = 1073;
height = 918;
data = (unsigned char *)malloc( width * height * 3 );
// read texture data
fclose( file );
// select our current texture
glBindTexture( GL_TEXTURE_2D, 1 );
// select modulate to mix texture with color for shading
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
// when texture area is large, bilinear filter the first mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// if wrap is true, the texture wraps over at the edges (repeat)
// ... false, the texture ends at the edges (clamp)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap ? GL_REPEAT : GL_CLAMP );
// build our texture mipmaps
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,
GL_RGB, GL_UNSIGNED_BYTE, data );
// free buffer
free( data );
}
void drawTex() {
glBegin(GL_QUADS);
glTexCoord2d(0.0,0.0);
glVertex3d(0.0,SIZE/2, -SIZE);
glTexCoord2d(1.0,0.0);
glVertex3d(SIZE, SIZE/2, -SIZE);
glTexCoord2d(1.0,1.0);
glVertex3d(SIZE, SIZE/2, SIZE);
glTexCoord2d(0.0,1.0);
glVertex3d(0.0, SIZE/2, SIZE);
glEnd();
glFlush();
}
void map() {
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glEnable( GL_TEXTURE_2D );
LoadTextureRAW("background.bmp", true);
glBindTexture( GL_TEXTURE_2D, 1 );
drawTex();
}
void init() {
glClearColor(1, 1, 1, 1);
glClearDepth( SIZE );
glOrtho(0, SIZE, 0, SIZE, -SIZE, SIZE);
GLfloat mat_ambient[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 50.0 };
GLfloat light_position[] = { SIZE/2, 0, 1.0, 0.0 };
GLfloat model_ambient[] = { 0.5, 0.5, 0.5, 1.0 };
glClearColor(1.0, 1.0, 1.0, 1.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, model_ambient);
//glColor3f(0,0,0);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glRotatef(-40, 1, 0, 0);
glRotatef(-40, 0, 1, 0);
map();
}
Any help would be really appreciated.
A few notes: In the fixed function pipleine the light position must be set, after the view transformation (=camera) has been applied to the modelview matrix. In fact the whole code in init() actually belongs in the display function.
glClearDepth should be set to 1 unless you know, what you're doing (the clear depth works in NDC space and as a OpenGL beginner this is something "too advanced" for a starting. Just set it to 1 and be happy.
The map() function makes no sense. Textures are initialized one time and then only bound before rendering textured geometry.
Last but not least glutSolidSphere doesn't generate proper texture coordinates. But you need to give OpenGL texture coordinates. My suggestion: Ditch glutSolidSphere and do the geometry yourself. Like this: https://stackoverflow.com/a/5989676/524368