Hi everybody.
I’m an OpenGL beginner and I’m using texture for the first time.
I want to draw a simple QUADS (polygon) and use a jpg image as texture
Here is my code:
bool Background::initialize()
{
m_vertices.push_back(Vertex(-1.0f, -1.0f, -1.0f));
m_vertices.push_back(Vertex(1.0f, -1.0f, -1.0f));
m_vertices.push_back(Vertex(1.0f, 1.0f, -1.0f));
m_vertices.push_back(Vertex(-1.0f, 1.0f, -1.0f));
m_indices.push_back(0);
m_indices.push_back(1);
m_indices.push_back(2);
m_indices.push_back(3);
Color white = Color(1.0f,1.0f,1.0f,0.0f);
Color black = Color(0.0f,0.0f,0.0f,0.0f);
m_colors.push_back(white);
m_colors.push_back(white);
m_colors.push_back(white);
m_colors.push_back(white);
glGenBuffers(1, &m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 3 * m_vertices.size(), &m_vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &m_indexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * m_indices.size(), &m_indices[0], GL_STATIC_DRAW);
glGenBuffers(1, &m_colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 4 * m_colors.size(), &m_colors[0], GL_STATIC_DRAW);
m_texCoord.push_back(texCoords(0.0,0.0));
m_texCoord.push_back(texCoords(1.0, 0.0));
m_texCoord.push_back(texCoords(1.0, 1.0));
m_texCoord.push_back(texCoords(0.0, 1.0));
// Texture
//load texture
int width, height;
width = 599;
height = 337;
unsigned char *data = (unsigned char*)malloc(width * height * 3);
FILE *file;
file = fopen( "textures/back1.jpg", "rb" );
fread( data, width * height * 3, 1, file );
fclose( file );
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * m_texCoord.size() * 2, &m_texCoord[0], GL_STATIC_DRAW);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
return true;
}
void Background::render()
{
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glVertexPointer(3, GL_FLOAT, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer);
glColorPointer(4, GL_FLOAT, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
//glBindTexture(GL_TEXTURE_2D, m_texture);
//glTexCoordPointer(2,GL_FLOAT,0,0);
glDrawElements(GL_QUADS, (GLsizei) m_indices.size(), GL_UNSIGNED_INT, 0);
glDisable(GL_COLOR_ARRAY);
glDisable(GL_VERTEX_ARRAY);
}
I can see my square and some strange colors on it. How can I correctly apply my texture on the square?
tank you