Search code examples
opengl-es-2.0framebuffer

I'm having issues with rendering depth


I'm using GLES2 to make graphics, because I intend to make a mobile application, so it has different things from classic opengl, in the part of creating a framebuffer, I looked for how to do it, and I made a simple one, but I had a depth problem

enter image description here

I saw some more examples and I saw that I should add a texture for the depth, I tried to add it but it doesn't work, the texture is black, I'll leave the code snippet where I create the framebuffer

//texture

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

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_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 600, 600, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

glBindTexture(GL_TEXTURE_2D, 0);

//depth texture

/*glGenTextures(1, &this->FBO_depth);
glBindTexture(GL_TEXTURE_2D, FBO_depth);

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_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 600, 600, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);

glBindTexture(GL_TEXTURE_2D, 0);*/

//frame buffer

glGenFramebuffers(1, &FBO);
glBindFramebuffer(GL_FRAMEBUFFER, FBO);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, FBO_Texture, 0);
//glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, FBO_depth, 0);

glBindFramebuffer(GL_FRAMEBUFFER, 0);

Solution

  • The internalFormat, format and type arguments of glTexImage2D have to match and have follow special rules. If the format is GL_DEPTH_COMPONENT, then the type cannot be GL_UNSIGNED_BYTE. Try GL_FLOAT or GL_UNSIGNED_INT:

    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 600, 600, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 600, 600, 0,
                 GL_DEPTH_COMPONENT, GL_FLOAT, NULL);