Solved

Opengl tga texture

Posted on 2011-02-15
5
1,151 Views
Last Modified: 2012-05-11
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

0
Comment
Question by:tango2009
  • 2
  • 2
5 Comments
 
LVL 18

Accepted Solution

by:
JoseParrot earned 250 total points
ID: 34901619
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
 

Author Comment

by:tango2009
ID: 34905104
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
 
LVL 12

Assisted Solution

by:satsumo
satsumo earned 250 total points
ID: 34909965
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
 

Author Comment

by:tango2009
ID: 34910754
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
 
LVL 18

Expert Comment

by:JoseParrot
ID: 34913320
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Query Syntax 17 50
Object Oriented Programming, C#, referencing, scoping. 13 83
Assignment from incompatible pointer type? 2 34
$_GET call between URL 3 37
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
In this post we will learn different types of Android Layout and some basics of an Android App.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question