diff --git a/Frequently-asked-Questions--Common-Questions.md b/Frequently-asked-Questions--Common-Questions.md index 6e51694..a55ba44 100644 --- a/Frequently-asked-Questions--Common-Questions.md +++ b/Frequently-asked-Questions--Common-Questions.md @@ -111,3 +111,50 @@ The above code will draw a texture flipped in the X axis. All textures in OpenGL by default have the origin in the lower-left corner, while the screen origin is in the upper left. When you load a normal texture, raylib flips the image data for you, however this cannot be done with a render texture. The solution is to draw your render texture vertically flipped, see the above paragraph for how to do this. + +# How do I create a depth texture? + +By default `LoadRenderTexture()` uses a `RenderBuffer` for the depth texture, this is done for optimization (supposedly GPU can work faster if it knows that depth texture does not need to be read back). But a `RenderBuffer` is unsuitable to be drawn on the screen like a regular `Texture2D`. + +Here some code to load a `RenderTexture2D` that uses a `Texture2D`for the depth: + +```c +RenderTexture2D LoadRenderTextureWithDepthTexture(int width, int height) +{ + RenderTexture2D target = {0}; + + target.id = rlLoadFramebuffer(width, height); // Load an empty framebuffer + + if (target.id > 0) + { + rlEnableFramebuffer(target.id); + + // Create color texture (default to RGBA) + target.texture.id = rlLoadTexture(NULL, width, height, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1); + target.texture.width = width; + target.texture.height = height; + target.texture.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; + target.texture.mipmaps = 1; + + // Create depth texture + target.depth.id = rlLoadTextureDepth(width, height, false); + target.depth.width = width; + target.depth.height = height; + target.depth.format = 19; //DEPTH_COMPONENT_24BIT? + target.depth.mipmaps = 1; + + // Attach color texture and depth texture to FBO + rlFramebufferAttach(target.id, target.texture.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0); + rlFramebufferAttach(target.id, target.depth.id, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_TEXTURE2D, 0); + + // Check if fbo is complete with attachments (valid) + if (rlFramebufferComplete(target.id)) TRACELOG(LOG_INFO, "FBO: [ID %i] Framebuffer object created successfully", target.id); + + rlDisableFramebuffer(); + } + else TRACELOG(LOG_WARNING, "FBO: Framebuffer object can not be created"); + + return target; +} +``` +Now the `RenderTexture` depth texture can be drawn as a regular texture... but note that information contained is nor normalized!