Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL Texture Loading

Tags:

opengl

Evening everyone, I'm going around in circles here but I think I'm looking in the wrong places.

My question is how would I go about loading an image and applying it to a primative in openGL. For example loading a bmp or jpg and applying it to a glutsolidsphere.

Would the solution be limited to one platform or could it work across all?

Thanks for your help

like image 679
John Roer Avatar asked Jan 10 '10 02:01

John Roer


People also ask

What is OpenGL texture?

A texture is an OpenGL Object that contains one or more images that all have the same image format. A texture can be used in two ways: it can be the source of a texture access from a Shader, or it can be used as a render target.

How do you show textures in OpenGL?

in display() function : GLuint texture; texture = LoadTexture("bubble. png"); glBindTexture(GL_TEXTURE_2D, texture);

Does OpenGL require texture coordinates?

Texture coordinates do not depend on resolution but can be any floating point value, thus OpenGL has to figure out which texture pixel (also known as a texel ) to map the texture coordinate to. This becomes especially important if you have a very large object and a low resolution texture.


1 Answers

Well, if you want to, you can write your own bmp loader. Here is the specification and some code. Otherwise, I happen to have a tga loader here. Once you do that, it will return the data in an unsigned character array, otherwise known as GL_UNSIGNED_BYTE.

To make an OpenGL texture from this array, you first define a variable that will serve as a reference to that texture in OpenGL's memory.

GLuint textureid;

Then, you need to tell OpenGL to make space for a new texture:

glGenTextures(1, &textureid);

Then, you need to bind that texture as the currently used texture.

glBindTexture(GL_TEXTURE_2D, textureid);

Finally, you need to tell OpenGL where the data is for the current texture.

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, your_data);

Then, when you render a primitive, you apply it to the primitive by calling glBindTexture again:


glBindTexture(GL_TEXTURE_2D, textureid);
glBegin(GL_QUAD);
     glTexCoord2f(0.0, 0.0);
     glVertex3f(0.0, 0.0, 0.0);
     glTexCoord2f(1.0, 0.0);
     glVertex3f(1.0, 0.0, 0.0);
     glTexCoord2f(1.0, 1.0);
     glVertex3f(1.0, 1.0, 0.0);
     glTexCoord2f(0.0, 1.0);
     glVertex3f(0.0, 1.0, 0.0);
glEnd();

However, any time you apply the texture to a primitive, you need to have texture coordinate data along with vertex data, and glutSolidSphere does not generate texture coordinate data. To texture a sphere, either generate it yourself, or call texgen functions, or use shaders.

like image 177
Ned Bingham Avatar answered Jan 03 '23 12:01

Ned Bingham