Opengl tga texture

I am trying to load a tga texture in opengl. I have an example that I am using but the problem I have with it is that it fails to load the file. I have added the tga file in the resource files folder and the code is below. When I say fail to load I mean it outputs it to the screen using this code

cout << "Error opening file" << endl;

not that there is a code error.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <windows.h>	   // Standard header for MS Windows applications
#include <GL/gl.h>		   // Open Graphics Library (OpenGL) header
#include <GL/glut.h>	   // The GL Utility Toolkit (GLUT) Header
 
#define KEY_ESCAPE 27
#define g_rotation_speed 0.2
float g_rotation;
 
 
using namespace std;
 
/************************************************************************************
 *  TGA CLASS
 ************************************************************************************/
class TGA
{
  public:
 
	bool Load(const char *filename);
	void Release();
	void Draw();
 
  private:
	char *imageData;
 
 
	struct tga_header
	{
		unsigned char idLength;
		unsigned char colorMapType;
		unsigned char imageTypeCode;
		unsigned char colorMapSpec[5];
		unsigned short xOrigin;
		unsigned short yOrigin;	
		unsigned short width;
		unsigned short height;
		unsigned char bpp;
		unsigned char imageDesc;
	};
	tga_header tgaheader;
};
 
 
void TGA::Draw()
{
	glPixelStorei (GL_UNPACK_ROW_LENGTH, this->tgaheader.width);
 
	if (this->tgaheader.bpp == 32)
	{
		glPixelStorei(GL_UNPACK_ALIGNMENT, 2); 
		glDrawPixels(this->tgaheader.width, this->tgaheader.height, GL_RGBA, GL_UNSIGNED_BYTE, this->imageData);
	}
	if (this->tgaheader.bpp == 24)
	{
		glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 
		glDrawPixels(this->tgaheader.width, this->tgaheader.height, GL_RGB, GL_UNSIGNED_BYTE, this->imageData);
	}
}
 
void TGA::Release()
{
	free(imageData);		// Free image data from memory
}
 
bool TGA::Load(const char* filename)
{
	fstream filestr;
 
	filestr.open (filename, ios::in | ios::binary);								// Open file
	if (filestr.is_open())														// Do the following actions, if file is opened
	{
		// read TGA header
		filestr.read((char*) &tgaheader , sizeof(struct tga_header));			// Read tga header. For more information: see tga.h and link above
		printf("image type: %i \n", tgaheader.imageTypeCode);	
 
		// read pixel data
		int imageSize = tgaheader.width * tgaheader.height * tgaheader.bpp;		// Calculate image size
 
		this->imageData = (char*) malloc(imageSize);							// Reserve space in the memory to store our image data
		filestr.read((char*) this->imageData, imageSize);						// Read image data from file, into the reserved memory place
 
 
		/*
		 * TGA is stored in BGR (Blue-Green-Red) format,
		 * we need to convert this to Red-Green-Blue (RGB).
		 * The following section does BGR to RGB conversion
		 */
 
		if (tgaheader.bpp == 24)
		{
			for (int i = 0; i < imageSize; i+=3)
			{	
				char c = this->imageData[i];
				this->imageData[i] = this->imageData[i+2];
				this->imageData[i+2] = c;
			}
		}
		else
		if (tgaheader.bpp == 32)
		{
			for (int i = 0; i < imageSize; i+=4)
			{	
				// 32 bits per pixel   =  4 byte per pixel			
				char c = this->imageData[i];
				this->imageData[i] = this->imageData[i+2];
				this->imageData[i+2] = c;
			}
		}
 
		filestr.close();
	}
	else
	{
		cout << "Error opening file" << endl;
		return -1;
	}
 
	return 0;
}
 
 
/************************************************************************************
 *  Rest of code
 ************************************************************************************/
 
 
typedef struct {
    int width;
	int height;
	char* title;
 
	float field_of_view_angle;
	float z_near;
	float z_far;
} glutWindow;
glutWindow win;
 
 
TGA g_image;
 
void display() 
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);		// Clear Screen and Depth Buffer
	glLoadIdentity();
	gluLookAt( 4,2,0, 0,0,0, 0,1,0);					    // Define a viewing transformation
	g_image.Draw();											// Draw image to the screen
	glutSwapBuffers();
}
 
 
void initialize () 
{
    glMatrixMode(GL_PROJECTION);												// select projection matrix
    glViewport(0, 0, win.width, win.height);									// set the viewport
    glMatrixMode(GL_PROJECTION);												// set matrix mode
    glLoadIdentity();															// reset projection matrix
    GLfloat aspect = (GLfloat) win.width / win.height;
	gluPerspective(win.field_of_view_angle, aspect, win.z_near, win.z_far);		// set up a perspective projection matrix
    glMatrixMode(GL_MODELVIEW);													// specify which matrix is the current matrix
    glShadeModel( GL_SMOOTH );
    glClearDepth( 1.0f );														// specify the clear value for the depth buffer
    glEnable( GL_DEPTH_TEST );
    glDepthFunc( GL_LEQUAL );
    glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );						// specify implementation-specific hints
 
	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.0, 0.0, 0.0, 1.0);
 
}
 
 
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 = "OpenGL/GLUT TGA Loader";
	win.field_of_view_angle = 45;
	win.z_near = 1.0f;
	win.z_far = 500.0f;
 
	g_image.Load("Resource Files/image.tga");
 
	// initialize and run program
	glutInit(&argc, argv);                                      // GLUT initialization
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );  // Display Mode
	glutInitWindowSize(win.width,win.height);					// set window size
	glutCreateWindow(win.title);								// create Window
	glutDisplayFunc(display);									// register Display Function
	glutIdleFunc( display );									// register Idle Function
    glutKeyboardFunc( keyboard );								// register Keyboard Handler
	initialize();
	glutMainLoop();												// run GLUT mainloop
	return 0;
}

Open in new window

tango2009Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jose ParrotGraphics ExpertCommented:
Your code is correct.
Please note that the line 211 in the source code must point to a valid TGA file.
Probably you don't have neither a directory "Resource Files" nor a file "image.tga" there.
If you are using Visual C++, put a tga file in the same directory as the source code and change the source code at line 211 properly.

Jose
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tango2009Author Commented:
I want to use this texture around a teapot that I have drawn, how do I get this texture to apply to the teapot.
0
Member_2_5069294Commented:
As JoseParrot says, the problem is the path of the file.  It's a relative path so the program will try to open it relative to the directory where the program runs.  The current directory probably isn't the directory where "Resource Files/image.tga" actually is.

Try specifying the entire path

g_image.Load ("C:/Resource Files/image.tga");

Open in new window

I've assumed you put the 'Resource Files' directory in the root of the C: drive, substitute the actual path.

Alternatively, put the file in the correct folder relative to where the program runs.  If you're using Dev Studio, this defaults to the directory where the source and other project files are stored.  You can change it in the Project Settings, its on the Debug tab, called 'Working Directory' (at least it is in my version of Dev Studio).
0
tango2009Author Commented:
I have loaded the texture now. I have drawn a teapot using

glutSolidTeapot (0.80);

How do I map this texture to the teapot?
0
Jose ParrotGraphics ExpertCommented:
The image isn't applied as a texture, as per your code. It was simply loaded, as a pure 2D image.
On should enable texture, the same way you have enabled lightning. So, in this particular subject, your code lacks so enablement.

Let me suggest to take a look at the Silicon Graphics' code at http://www.opengl.org/resources/code/samples/redbook/texgen.c
which is applicable to your needs.

Jose
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Game Programming

From novice to tech pro — start learning today.