Reputation: 115
I am trying to put texture in my model, but when I try running my code I get the following error:
Exception thrown at 0x00007FFE262AE37C (ig9icd64.dll) in COMP371.exe: 0xC0000005: Access violation reading location 0x000001799C69D000.
Can someone please help me understand why I am getting this error?
Here is my code for my texture:
Texture::Texture(std::string texturePath)
{
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
unsigned char* data = stbi_load(texturePath.c_str(), &width, &height, &depth, 0);
if (data) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D); // Here is where the error is thrown
}
else {
std::cout << "Failed to load texture: " << texturePath << std::endl;
}
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(data);
}
Upvotes: 0
Views: 1092
Reputation: 162164
It's not glGenerateMipmap
that crashes, it's glTexImage2D
. And that happens because you're passing it invalid data and/or invalid format specification. The layout of data
must match the format and dimensions you pass to glTexImage2D
. The depth
value returned by stbi_load
for example tells you, how many components (each having 8 bits) there are. You must select the appropriate OpenGL image format from that:
if( 0 == depth || 4 < depth ){ throw std::runtime_error("invalid depth"); }
GLenum const fmt[] = {GL_RED, GL_RG, GL_RGB, GL_RGBA};
glTexImage2D(
GL_TEXTURE_2D, 0, fmt[depth-1],
width, height, 0,
fmt[depth-1], GL_UNSIGNED_BYTE, data);
Upvotes: 0