I'm trying to texture a model but all I get is the model rendered totally in black. i use SOIL2 library to load the image into the memory and the following code shows Load function in my Texture class.
bool Texture::Load(std::string texturePath)
{
int channels = 0;
unsigned char* image = SOIL_load_image(texturePath.c_str(), &mWidth, &mHeight, &channels, SOIL_LOAD_AUTO);
if (image == nullptr)
{
std::cout << "Failed to load image " << texturePath;
return false;
}
int format = GL_RGB;
if (channels == 4)
{
format = GL_RGBA;
}
glGenTextures(1, &mTextureID);
glBindTexture(GL_TEXTURE_2D, mTextureID);
glGenerateMipmap(GL_TEXTURE_2D);
glTextureParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, format, mWidth, mHeight, 0, format, GL_UNSIGNED_BYTE, image);
// Free data
SOIL_free_image_data(image);
return true;
}
When I tried to debug the code I found out that the image pointer is pointing to an empty array as the following image I don't know if this is the problem or not but I found it weird and I'm pretty sure that the image is loaded successfully because mWidth and mHeight have their correct values.
My vertex shader :
#version 330 core
layout(location=0) in vec3 position ;
layout(location=1) in vec2 UVCoord ;
layout(location=2) in vec3 normal ;
uniform mat4 uWorldTransform ;
uniform mat4 uView ;
uniform mat4 uProjection ;
out vec2 textCoord ;
void main()
{
gl_Position = uProjection * uView * uWorldTransform * vec4(position, 1.0) ;
textCoord = UVCoord ;
}
and my fragment shader
#version 330 core
in vec2 textCoord ;
out vec4 color ;
uniform sampler2D myTexture ;
void main()
{
color = texture(myTexture , textCoord) ;
}
My rendering code:
void Renderer::Draw()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
std::vector<Actor*> actors = mGame->GetActors();
for (auto act : actors)
{
if (act->GetDrawable())
{
glm::mat4 worldTransform = act->GetWorldTransform();
Shader* shader = mShaders[act->GetMesh()->GetShaderName()];
VertexArrayObject* vao = act->GetMesh()->GetVAO();
Texture* text = act->GetTexture();
shader->Bind();
shader->SetMatrix4Uniform("uWorldTransform", worldTransform);
shader->SetMatrix4Uniform("uView", mView);
shader->SetMatrix4Uniform("uProjection", mProjection);
if (text)
{
text->Bind();
}
vao->Bind();
glDrawElements(GL_TRIANGLES, vao->GetEBOsize(), GL_UNSIGNED_INT, nullptr);
}
}
glfwSwapBuffers(mGame->GetWindow());
}
This is the result I get on my screen:
Call glGenerateMipmap()
after image upload (glTexImage2D()
), otherwise it won't do anything useful since there isn't any image data in the texture yet to generate mipmaps from.
Or disable mip sampling by setting GL_TEXTURE_MIN_FILTER
to GL_LINEAR
/GL_NEAREST
.
Also, be careful with GL_RGB
& the default GL_UNPACK_ALIGNMENT
of 4
. 1
is what you usually want.