PDA

View Full Version : loading textures in constructors



Molerat
05-15-2004, 01:12 PM
I've a problem which seems very strange to me, but maybe it's just me beeing stange ....

I'm programming in C++ using the glut libary, and I've the following function to load my texture data from a raw image file:

GLuint loadTextureRAW(const char *filename, GLsizei width, GLsizei height)
{
GLuint texture;
char *data;
long size;

ifstream file(filename, ios::in | ios::binary | ios::ate);
size = file.tellg();
file.seekg(0, ios::beg);

data = new char[size];
file.read(data, size);
file.close();


glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);


glPixelStorei(GL_UNPACK_ALIGNMENT, 1);


glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_BYTE, data);

delete[] data;
return texture;
}

I call this function inside a constructor of a simple class like this

menuElement::menuElement(GLfloat vertex1[2], GLfloat vertex2[2], const char *textureFile,
GLsizei textureWidth, GLsizei textureHeight)
:textureAddress(loadTextureRAW(textureFile, textureWidth, textureHeight)) { ... }

with the following draw() method

void menuElement::draw() const
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textureAddress);

glColor3fv(color);
glBegin(GL_QUADS);
{
glTexCoord2f(0.0, 0.0); glVertex2fv(vertices[0]);
glTexCoord2f(1.0, 0.0); glVertex2fv(vertices[1]);
glTexCoord2f(1.0, 1.0); glVertex2fv(vertices[2]);
glTexCoord2f(0.0, 1.0); glVertex2fv(vertices[3]);
}
glEnd();
}

Now, there comes what I call strange:
If I create an object of that class inside my display function, it works like it should. But when I make such an object at global scope, my programm behaves like there aren't any textures, which in my case means, I just see a blue box.

Maybe someone in here can help me ....

Thanks, matthias

chowe6685
05-15-2004, 01:49 PM
you cannot make any gl calls before you have a valid rendering context. Thus the globally created objects have their constructors called before the RC is set up, and the texture fails