Framebuffers.html (31063B)
1 <div id="content"> 2 <h1 id="content-title">Framebuffers</h1> 3 <h1 id="content-url" style='display:none;'>Advanced-OpenGL/Framebuffers</h1> 4 <p> 5 So far we've used several types of screen buffers: a color buffer for writing color values, a depth buffer to write and test depth information, and finally a stencil buffer that allows us to discard certain fragments based on some condition. The combination of these buffers is stored somewhere in GPU memory and is called a <def>framebuffer</def>. OpenGL gives us the flexibility to define our own framebuffers and thus define our own color (and optionally a depth and stencil) buffer. 6 </p> 7 8 <p> 9 The rendering operations we've done so far were all done on top of the render buffers attached to the <def>default framebuffer</def>. The default framebuffer is created and configured when you create your window (GLFW does this for us). By creating our own framebuffer we can get an additional target to render to. 10 </p> 11 12 <p> 13 The application of framebuffers may not immediately make sense, but rendering your scene to a different framebuffer allows us to use that result to create mirrors in a scene, or do cool post-processing effects for example. First we'll discuss how they actually work and then we'll use them by implementing those cool post-processing effects. 14 </p> 15 16 <h2>Creating a framebuffer</h2> 17 <p> 18 Just like any other object in OpenGL we can create a framebuffer object (abbreviated to FBO) by using a function called <fun><function id='76'>glGenFramebuffers</function></fun>: 19 </p> 20 21 <pre class="cpp"><code> 22 unsigned int fbo; 23 <function id='76'>glGenFramebuffers</function>(1, &fbo); 24 </code></pre> 25 26 <p> 27 This pattern of object creation and usage is something we've seen dozens of times now so their usage functions are similar to all the other object's we've seen: first we create a framebuffer object, bind it as the active framebuffer, do some operations, and unbind the framebuffer. To bind the framebuffer we use <fun><function id='77'>glBindFramebuffer</function></fun>: 28 </p> 29 30 <pre><code> 31 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, fbo); 32 </code></pre> 33 34 <p> 35 By binding to the <var>GL_FRAMEBUFFER</var> target all the next <em>read</em> and <em>write</em> framebuffer operations will affect the currently bound framebuffer. It is also possible to bind a framebuffer to a read or write target specifically by binding to <var>GL_READ_FRAMEBUFFER</var> or <var>GL_DRAW_FRAMEBUFFER</var> respectively. The framebuffer bound to <var>GL_READ_FRAMEBUFFER</var> is then used for all read operations like <fun><function id='78'>glReadPixels</function></fun> and the framebuffer bound to <var>GL_DRAW_FRAMEBUFFER</var> is used as the destination for rendering, clearing and other write operations. Most of the times you won't need to make this distinction though and you generally bind to both with <var>GL_FRAMEBUFFER</var>. 36 </p> 37 38 <p> 39 Unfortunately, we can't use our framebuffer yet because it is not <def>complete</def>. For a framebuffer to be complete the following requirements have to be satisfied: 40 </p> 41 42 <ul> 43 <li>We have to attach at least one buffer (color, depth or stencil buffer).</li> 44 <li>There should be at least one color attachment.</li> 45 <li>All attachments should be complete as well (reserved memory).</li> 46 <li>Each buffer should have the same number of samples.</li> 47 </ul> 48 49 <p> 50 Don't worry if you don't know what samples are, we'll get to those in a <a href="https://learnopengl.com/Advanced-OpenGL/Anti-Aliasing" target="_blank">later</a> chapter. 51 </p> 52 53 <p> 54 From the requirements it should be clear that we need to create some kind of attachment for the framebuffer and attach this attachment to the framebuffer. After we've completed all requirements we can check if we actually successfully completed the framebuffer by calling <fun><function id='79'>glCheckFramebufferStatus</function></fun> with <var>GL_FRAMEBUFFER</var>. It then checks the currently bound framebuffer and returns any of <a href="https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/%67lCheckFramebufferStatus.xhtml" target="_blank">these</a> values found in the specification. If it returns <var>GL_FRAMEBUFFER_COMPLETE</var> we're good to go: 55 </p> 56 57 <pre><code> 58 if(<function id='79'>glCheckFramebufferStatus</function>(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) 59 // execute victory dance 60 </code></pre> 61 62 <p> 63 All subsequent rendering operations will now render to the attachments of the currently bound framebuffer. Since our framebuffer is not the default framebuffer, the rendering commands will have no impact on the visual output of your window. For this reason it is called <def>off-screen rendering</def> when rendering to a different framebuffer. If you want all rendering operations to have a visual impact again on the main window we need to make the default framebuffer active by binding to <code>0</code>: 64 </p> 65 66 <pre class="cpp"><code> 67 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, 0); 68 </code></pre> 69 70 <p> 71 When we're done with all framebuffer operations, do not forget to delete the framebuffer object: 72 </p> 73 74 <pre class="cpp"><code> 75 <function id='80'>glDeleteFramebuffers</function>(1, &fbo); 76 </code></pre> 77 78 <p> 79 Now before the completeness check is executed we need to attach one or more attachments to the framebuffer. An <def>attachment</def> is a memory location that can act as a buffer for the framebuffer, think of it as an image. When creating an attachment we have two options to take: textures or <def>renderbuffer</def> objects. 80 </p> 81 82 <h3>Texture attachments</h3> 83 <p> 84 When attaching a texture to a framebuffer, all rendering commands will write to the texture as if it was a normal color/depth or stencil buffer. The advantage of using textures is that the render output is stored inside the texture image that we can then easily use in our shaders. 85 </p> 86 87 <p> 88 Creating a texture for a framebuffer is roughly the same as creating a normal texture: 89 </p> 90 91 <pre class="cpp"><code> 92 unsigned int texture; 93 <function id='50'>glGenTextures</function>(1, &texture); 94 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D, texture); 95 96 <function id='52'>glTexImage2D</function>(GL_TEXTURE_2D, 0, GL_RGB, 800, 600, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); 97 98 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 99 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 100 </code></pre> 101 102 <p> 103 The main differences here is that we set the dimensions equal to the screen size (although this is not required) and we pass <code>NULL</code> as the texture's <code>data</code> parameter. For this texture, we're only allocating memory and not actually filling it. Filling the texture will happen as soon as we render to the framebuffer. Also note that we do not care about any of the wrapping methods or mipmapping since we won't be needing those in most cases. 104 </p> 105 106 <note> 107 If you want to render your whole screen to a texture of a smaller or larger size you need to call <fun><function id='22'>glViewport</function></fun> again (before rendering to your framebuffer) with the new dimensions of your texture, otherwise render commands will only fill part of the texture. 108 </note> 109 110 <p> 111 Now that we've created a texture, the last thing we need to do is actually attach it to the framebuffer: 112 </p> 113 114 <pre class="cpp"><code> 115 <function id='81'>glFramebufferTexture2D</function>(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); 116 </code></pre> 117 118 <p> 119 The <fun><function id='81'>glFrameBufferTexture2D</function></fun> function has the following parameters: 120 </p> 121 122 <ul> 123 <li><code>target</code>: the framebuffer type we're targeting (draw, read or both).</li> 124 <li><code>attachment</code>: the type of attachment we're going to attach. Right now we're attaching a color attachment. Note that the <code>0</code> at the end suggests we can attach more than 1 color attachment. We'll get to that in a later chapter.</li> 125 <li><code>textarget</code>: the type of the texture you want to attach.</li> 126 <li><code>texture</code>: the actual texture to attach.</li> 127 <li><code>level</code>: the mipmap level. We keep this at <code>0</code>.</li> 128 </ul> 129 130 <p> 131 Next to the color attachments we can also attach a depth and a stencil texture to the framebuffer object. To attach a depth attachment we specify the attachment type as <var>GL_DEPTH_ATTACHMENT</var>. Note that the texture's <def>format</def> and <def>internalformat</def> type should then become <var>GL_DEPTH_COMPONENT</var> to reflect the depth buffer's storage format. To attach a stencil buffer you use <var>GL_STENCIL_ATTACHMENT</var> as the second argument and specify the texture's formats as <var>GL_STENCIL_INDEX</var>. 132 </p> 133 134 <p> 135 It is also possible to attach both a depth buffer and a stencil buffer as a single texture. Each 32 bit value of the texture then contains 24 bits of depth information and 8 bits of stencil information. To attach a depth and stencil buffer as one texture we use the <var>GL_DEPTH_STENCIL_ATTACHMENT</var> type and configure the texture's formats to contain combined depth and stencil values. An example of attaching a depth and stencil buffer as one texture to the framebuffer is given below: 136 </p> 137 138 139 <pre class="cpp"><code> 140 <function id='52'>glTexImage2D</function>( 141 GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, 800, 600, 0, 142 GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL 143 ); 144 145 <function id='81'>glFramebufferTexture2D</function>(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texture, 0); 146 </code></pre> 147 148 <h3>Renderbuffer object attachments</h3> 149 <p> 150 <def>Renderbuffer objects</def> were introduced to OpenGL after textures as a possible type of framebuffer attachment, Just like a texture image, a renderbuffer object is an actual buffer e.g. an array of bytes, integers, pixels or whatever. However, a renderbuffer object can not be directly read from. This gives it the added advantage that OpenGL can do a few memory optimizations that can give it a performance edge over textures for off-screen rendering to a framebuffer. 151 </p> 152 153 <p> 154 Renderbuffer objects store all the render data directly into their buffer without any conversions to texture-specific formats, making them faster as a writeable storage medium. You cannot read from them directly, but it is possible to read from them via the slow <fun><function id='78'>glReadPixels</function></fun>. This returns a specified area of pixels from the currently bound framebuffer, but not directly from the attachment itself. 155 </p> 156 157 <p> 158 Because their data is in a native format they are quite fast when writing data or copying data to other buffers. Operations like switching buffers are therefore quite fast when using renderbuffer objects. The <fun><function id='24'>glfwSwapBuffers</function></fun> function we've been using at the end of each frame may as well be implemented with renderbuffer objects: we simply write to a renderbuffer image, and swap to the other one at the end. Renderbuffer objects are perfect for these kind of operations. 159 </p> 160 161 <p> 162 Creating a renderbuffer object looks similar to the framebuffer's code: 163 </p> 164 165 <pre class="cpp"><code> 166 unsigned int rbo; 167 <function id='82'>glGenRenderbuffers</function>(1, &rbo); 168 </code></pre> 169 170 <p> 171 And similarly we want to bind the renderbuffer object so all subsequent renderbuffer operations affect the current <var>rbo</var>: 172 </p> 173 174 <pre><code> 175 <function id='83'>glBindRenderbuffer</function>(GL_RENDERBUFFER, rbo); 176 </code></pre> 177 178 <p> 179 Since renderbuffer objects are write-only they are often used as depth and stencil attachments, since most of the time we don't really need to read values from them, but we do care about depth and stencil testing. We <strong>need</strong> the depth and stencil values for testing, but don't need to <em>sample</em> these values so a renderbuffer object suits this perfectly. When we're not sampling from these buffers, a renderbuffer object is generally preferred. 180 </p> 181 182 <p> 183 Creating a depth and stencil renderbuffer object is done by calling the <fun><function id='88'>glRenderbufferStorage</function></fun> function: 184 </p> 185 186 <pre class="cpp"><code> 187 <function id='88'>glRenderbufferStorage</function>(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 800, 600); 188 </code></pre> 189 190 <p> 191 Creating a renderbuffer object is similar to texture objects, the difference being that this object is specifically designed to be used as a framebuffer attachment, instead of a general purpose data buffer like a texture. Here we've chosen <var>GL_DEPTH24_STENCIL8</var> as the internal format, which holds both the depth and stencil buffer with 24 and 8 bits respectively. 192 </p> 193 194 <p> 195 The last thing left to do is to actually attach the renderbuffer object: 196 </p> 197 198 <pre><code> 199 <function id='89'>glFramebufferRenderbuffer</function>(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); 200 </code></pre> 201 202 <p> 203 Renderbuffer objects can be more efficient for use in your off-screen render projects, but it is important to realize when to use renderbuffer objects and when to use textures. The general rule is that if you never need to sample data from a specific buffer, it is wise to use a renderbuffer object for that specific buffer. If you need to sample data from a specific buffer like colors or depth values, you should use a texture attachment instead. 204 </p> 205 206 <h2>Rendering to a texture</h2> 207 <p> 208 Now that we know how framebuffers (sort of) work it's time to put them to good use. We're going to render the scene into a color texture attached to a framebuffer object we created and then draw this texture over a simple quad that spans the whole screen. The visual output is then exactly the same as without a framebuffer, but this time it's all printed on top of a single quad. Now why is this useful? In the next section we'll see why. 209 </p> 210 211 <p> 212 First thing to do is to create an actual framebuffer object and bind it, this is all relatively straightforward: 213 </p> 214 215 <pre class="cpp"><code> 216 unsigned int framebuffer; 217 <function id='76'>glGenFramebuffers</function>(1, &framebuffer); 218 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, framebuffer); 219 </code></pre> 220 221 <p> 222 Next we create a texture image that we attach as a color attachment to the framebuffer. We set the texture's dimensions equal to the width and height of the window and keep its data uninitialized: 223 </p> 224 225 <pre><code> 226 // generate texture 227 unsigned int texColorBuffer; 228 <function id='50'>glGenTextures</function>(1, &texColorBuffer); 229 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D, texColorBuffer); 230 <function id='52'>glTexImage2D</function>(GL_TEXTURE_2D, 0, GL_RGB, 800, 600, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); 231 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); 232 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 233 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D, 0); 234 235 // attach it to currently bound framebuffer object 236 <function id='81'>glFramebufferTexture2D</function>(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColorBuffer, 0); 237 </code></pre> 238 239 <p> 240 We also want to make sure OpenGL is able to do depth testing (and optionally stencil testing) so we have to make sure to add a depth (and stencil) attachment to the framebuffer. Since we'll only be sampling the color buffer and not the other buffers we can create a renderbuffer object for this purpose. 241 </p> 242 243 <p> 244 Creating a renderbuffer object isn't too hard. The only thing we have to remember is that we're creating it as a depth <strong>and</strong> stencil attachment renderbuffer object. We set its <em>internal format</em> to <var>GL_DEPTH24_STENCIL8</var> which is enough precision for our purposes: 245 </p> 246 247 <pre class="cpp"><code> 248 unsigned int rbo; 249 <function id='82'>glGenRenderbuffers</function>(1, &rbo); 250 <function id='83'>glBindRenderbuffer</function>(GL_RENDERBUFFER, rbo); 251 <function id='88'>glRenderbufferStorage</function>(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 800, 600); 252 <function id='83'>glBindRenderbuffer</function>(GL_RENDERBUFFER, 0); 253 </code></pre> 254 255 <p> 256 Once we've allocated enough memory for the renderbuffer object we can unbind the renderbuffer. 257 </p> 258 259 <p> 260 Then, as a final step before we complete the framebuffer, we attach the renderbuffer object to the depth <strong>and</strong> stencil attachment of the framebuffer: 261 </p> 262 263 <pre><code> 264 <function id='89'>glFramebufferRenderbuffer</function>(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); 265 </code></pre> 266 267 <p> 268 Then we want to check if the framebuffer is complete and if it's not, we print an error message. 269 </p> 270 271 <pre class="cpp"><code> 272 if(<function id='79'>glCheckFramebufferStatus</function>(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) 273 std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; 274 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, 0); 275 </code></pre> 276 277 <p> 278 Be sure to unbind the framebuffer to make sure we're not accidentally rendering to the wrong framebuffer. 279 </p> 280 281 <p> 282 Now that the framebuffer is complete, all we need to do to render to the framebuffer's buffers instead of the default framebuffers is to simply bind the framebuffer object. All subsequent render commands will then influence the currently bound framebuffer. All the depth and stencil operations will also read from the currently bound framebuffer's depth and stencil attachments if they're available. If you were to omit a depth buffer for example, all depth testing operations will no longer work. 283 </p> 284 285 <p> 286 So, to draw the scene to a single texture we'll have to take the following steps: 287 </p> 288 289 <ol> 290 <li>Render the scene as usual with the new framebuffer bound as the active framebuffer.</li> 291 <li>Bind to the default framebuffer.</li> 292 <li>Draw a quad that spans the entire screen with the new framebuffer's color buffer as its texture.</li> 293 </ol> 294 295 <p> 296 We'll render the same scene we've used in the <a href="https://learnopengl.com/Advanced-OpenGL/Depth-testing" target="_blank">depth testing</a> chapter, but this time with the old-school <a href="https://learnopengl.com/img/textures/container.jpg" target="_blank">container</a> texture. 297 </p> 298 299 <p> 300 To render the quad we're going to create a fresh set of simple shaders. We're not going to include fancy matrix transformations since we'll be supplying the <a href="/code_viewer.php?code=advanced/framebuffers_quad_vertices" target="_blank">vertex coordinates as normalized device coordinates</a> so we can directly forward them as output of the vertex shader. The vertex shader looks like this: 301 </p> 302 303 <pre><code> 304 #version 330 core 305 layout (location = 0) in vec2 aPos; 306 layout (location = 1) in vec2 aTexCoords; 307 308 out vec2 TexCoords; 309 310 void main() 311 { 312 gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0); 313 TexCoords = aTexCoords; 314 } 315 </code></pre> 316 317 <p> 318 Nothing too fancy. The fragment shader is even more basic since the only thing we have to do is sample from a texture: 319 </p> 320 321 <pre><code> 322 #version 330 core 323 out vec4 FragColor; 324 325 in vec2 TexCoords; 326 327 uniform sampler2D screenTexture; 328 329 void main() 330 { 331 FragColor = texture(screenTexture, TexCoords); 332 } 333 </code></pre> 334 335 <p> 336 It is then up to you to create and configure a VAO for the screen quad. A single render iteration of the framebuffer procedure has the following structure: 337 </p> 338 339 <pre><code> 340 // first pass 341 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, framebuffer); 342 <function id='13'><function id='10'>glClear</function>Color</function>(0.1f, 0.1f, 0.1f, 1.0f); 343 <function id='10'>glClear</function>(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // we're not using the stencil buffer now 344 <function id='60'>glEnable</function>(GL_DEPTH_TEST); 345 DrawScene(); 346 347 // second pass 348 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, 0); // back to default 349 <function id='13'><function id='10'>glClear</function>Color</function>(1.0f, 1.0f, 1.0f, 1.0f); 350 <function id='10'>glClear</function>(GL_COLOR_BUFFER_BIT); 351 352 screenShader.use(); 353 <function id='27'>glBindVertexArray</function>(quadVAO); 354 glDisable(GL_DEPTH_TEST); 355 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D, textureColorbuffer); 356 <function id='1'>glDrawArrays</function>(GL_TRIANGLES, 0, 6); 357 </code></pre> 358 359 <p> 360 There are a few things to note. First, since each framebuffer we're using has its own set of buffers, we want to clear each of those buffers with the appropriate bits set by calling <fun><function id='10'>glClear</function></fun>. Second, when drawing the quad, we're disabling depth testing since we want to make sure the quad always renders in front of everything else; we'll have to enable depth testing again when we draw the normal scene though. 361 </p> 362 363 <p> 364 There are quite some steps that could go wrong here, so if you have no output, try to debug where possible and re-read the relevant sections of the chapter. If everything did work out successfully you'll get a visual result that looks like this: 365 </p> 366 367 <img src="/img/advanced/framebuffers_screen_texture.png" alt="An image of a 3D scene in OpenGL rendered to a texture via framebuffers"/> 368 369 <p> 370 The left shows the visual output, exactly the same as we've seen in the <a href="https://learnopengl.com/Advanced-OpenGL/Depth-testing" target="_blank">depth testing</a> chapter, but this time rendered on a simple quad. If we render the scene in wireframe it's obvious we've only drawn a single quad in the default framebuffer. 371 </p> 372 373 <p> 374 You can find the source code of the application <a href="/code_viewer_gh.php?code=src/4.advanced_opengl/5.1.framebuffers/framebuffers.cpp" target="_blank">here</a>. 375 </p> 376 377 <p> 378 So what was the use of this again? Well, because we can now freely access each of the pixels of the completely rendered scene as a single texture image, we can create some interesting effects in the fragment shader. 379 </p> 380 381 <h1>Post-processing</h1> 382 <p> 383 Now that the entire scene is rendered to a single texture we can create cool <def>post-processing</def> effects by manipulating the scene texture. In this section we'll show you some of the more popular post-processing effects and how you may create your own with some added creativity. 384 </p> 385 386 <p> 387 Let's start with one of the simplest post-processing effects. 388 </p> 389 390 <h3>Inversion</h3> 391 <p> 392 We have access to each of the colors of the render output so it's not so hard to return the inverse of these colors in the fragment shader. We can take the color of the screen texture and inverse it by subtracting it from <code>1.0</code>: 393 </p> 394 395 <pre><code> 396 void main() 397 { 398 FragColor = vec4(vec3(1.0 - texture(screenTexture, TexCoords)), 1.0); 399 } 400 </code></pre> 401 402 <p> 403 While inversion is a relatively simple post-processing effect it already creates funky results: 404 </p> 405 406 <img src="/img/advanced/framebuffers_inverse.png" class="clean" alt="Post-processing image of a 3D scene in OpenGL with inversed colors"/> 407 408 <p> 409 The entire scene now has all its colors inversed with a single line of code in the fragment shader. Pretty cool huh? 410 </p> 411 412 <h3>Grayscale</h3> 413 <p> 414 Another interesting effect is to remove all colors from the scene except the white, gray and black colors; effectively grayscaling the entire image. An easy way to do this is by taking all the color components and averaging their results: 415 </p> 416 417 <pre><code> 418 void main() 419 { 420 FragColor = texture(screenTexture, TexCoords); 421 float average = (FragColor.r + FragColor.g + FragColor.b) / 3.0; 422 FragColor = vec4(average, average, average, 1.0); 423 } 424 </code></pre> 425 426 <p> 427 This already creates pretty good results, but the human eye tends to be more sensitive to green colors and the least to blue. So to get the most physically accurate results we'll need to use weighted channels: 428 </p> 429 430 <pre><code> 431 void main() 432 { 433 FragColor = texture(screenTexture, TexCoords); 434 float average = 0.2126 * FragColor.r + 0.7152 * FragColor.g + 0.0722 * FragColor.b; 435 FragColor = vec4(average, average, average, 1.0); 436 } 437 </code></pre> 438 439 <img src="/img/advanced/framebuffers_grayscale.png" class="clean" alt="Post-processing image of a 3D scene in OpenGL with grayscale colors"/> 440 441 <p> 442 You probably won't notice the difference right away, but with more complicated scenes, such a weighted grayscaling effect tends to be more realistic. 443 </p> 444 445 <h2>Kernel effects</h2> 446 <p> 447 Another advantage about doing post-processing on a single texture image is that we can sample color values from other parts of the texture not specific to that fragment. We could for example take a small area around the current texture coordinate and sample multiple texture values around the current texture value. We can then create interesting effects by combining them in creative ways. 448 </p> 449 450 <p> 451 A <def>kernel</def> (or convolution matrix) is a small matrix-like array of values centered on the current pixel that multiplies surrounding pixel values by its kernel values and adds them all together to form a single value. We're adding a small offset to the texture coordinates in surrounding directions of the current pixel and combine the results based on the kernel. An example of a kernel is given below: 452 </p> 453 454 \[\begin{bmatrix}2 & 2 & 2 \\ 2 & -15 & 2 \\ 2 & 2 & 2 \end{bmatrix}\] 455 456 <p> 457 This kernel takes 8 surrounding pixel values and multiplies them by <code>2</code> and the current pixel by <code>-15</code>. This example kernel multiplies the surrounding pixels by several weights determined in the kernel and balances the result by multiplying the current pixel by a large negative weight. 458 </p> 459 460 <note> 461 Most kernels you'll find over the internet all sum up to <code>1</code> if you add all the weights together. If they don't add up to <code>1</code> it means that the resulting texture color ends up brighter or darker than the original texture value. 462 </note> 463 464 <p> 465 Kernels are an extremely useful tool for post-processing since they're quite easy to use and experiment with, and a lot of examples can be found online. We do have to slightly adapt the fragment shader a bit to actually support kernels. We make the assumption that each kernel we'll be using is a 3x3 kernel (which most kernels are): 466 </p> 467 468 <pre><code> 469 const float offset = 1.0 / 300.0; 470 471 void main() 472 { 473 vec2 offsets[9] = vec2[]( 474 vec2(-offset, offset), // top-left 475 vec2( 0.0f, offset), // top-center 476 vec2( offset, offset), // top-right 477 vec2(-offset, 0.0f), // center-left 478 vec2( 0.0f, 0.0f), // center-center 479 vec2( offset, 0.0f), // center-right 480 vec2(-offset, -offset), // bottom-left 481 vec2( 0.0f, -offset), // bottom-center 482 vec2( offset, -offset) // bottom-right 483 ); 484 485 float kernel[9] = float[]( 486 -1, -1, -1, 487 -1, 9, -1, 488 -1, -1, -1 489 ); 490 491 vec3 sampleTex[9]; 492 for(int i = 0; i < 9; i++) 493 { 494 sampleTex[i] = vec3(texture(screenTexture, TexCoords.st + offsets[i])); 495 } 496 vec3 col = vec3(0.0); 497 for(int i = 0; i < 9; i++) 498 col += sampleTex[i] * kernel[i]; 499 500 FragColor = vec4(col, 1.0); 501 } 502 </code></pre> 503 504 <p> 505 In the fragment shader we first create an array of 9 <code>vec2</code> offsets for each surrounding texture coordinate. The offset is a constant value that you could customize to your liking. Then we define the kernel, which in this case is a <def>sharpen</def> kernel that sharpens each color value by sampling all surrounding pixels in an interesting way. Lastly, we add each offset to the current texture coordinate when sampling and multiply these texture values with the weighted kernel values that we add together. 506 </p> 507 508 <p> 509 This particular sharpen kernel looks like this: 510 </p> 511 512 <img src="/img/advanced/framebuffers_sharpen.png" class="clean" alt="Post-processing image of a 3D scene in OpenGL with blurred colors"/> 513 514 <p> 515 This could be the base of some interesting effects where your player may be on a narcotic adventure. 516 </p> 517 518 519 <h3>Blur</h3> 520 <p> 521 A kernel that creates a <def>blur</def> effect is defined as follows: 522 </p> 523 524 \[\begin{bmatrix} 1 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 1 \end{bmatrix} / 16\] 525 526 <p> 527 Because all values add up to 16, directly returning the combined sampled colors would result in an extremely bright color so we have to divide each value of the kernel by <code>16</code>. The resulting kernel array then becomes: 528 </p> 529 530 <pre><code> 531 float kernel[9] = float[]( 532 1.0 / 16, 2.0 / 16, 1.0 / 16, 533 2.0 / 16, 4.0 / 16, 2.0 / 16, 534 1.0 / 16, 2.0 / 16, 1.0 / 16 535 ); 536 </code></pre> 537 538 <p> 539 By only changing the kernel array in the fragment shader we can completely change the post-processing effect. It now looks something like this: 540 </p> 541 542 <img src="/img/advanced/framebuffers_blur.png" class="clean" alt="Post-processing image of a 3D scene in OpenGL with sharpened colors"/> 543 544 545 <p> 546 Such a blur effect creates interesting possibilities. We could vary the blur amount over time to create the effect of someone being drunk, or increase the blur whenever the main character is not wearing glasses. Blurring can also be a useful tool for smoothing color values which we'll see use of in later chapters. 547 </p> 548 549 <p> 550 You can see that once we have such a little kernel implementation in place it is quite easy to create cool post-processing effects. Let's show you a last popular effect to finish this discussion. 551 </p> 552 553 <h3>Edge detection</h3> 554 <p> 555 Below you can find an <def>edge-detection</def> kernel that is similar to the sharpen kernel: 556 </p> 557 558 \[\begin{bmatrix} 1 & 1 & 1 \\ 1 & -8 & 1 \\ 1 & 1 & 1 \end{bmatrix}\] 559 560 <p> 561 This kernel highlights all edges and darkens the rest, which is pretty useful when we only care about edges in an image. 562 </p> 563 564 <img src="/img/advanced/framebuffers_edge_detection.png" class="clean" alt="Post-processing image of a 3D scene in OpenGL with edge detection filter"/> 565 566 <p> 567 It probably does not come as a surprise that kernels like this are used as image-manipulating tools/filters in tools like Photoshop. Because of a graphic card's ability to process fragments with extreme parallel capabilities, we can manipulate images on a per-pixel basis in real-time with relative ease. Image-editing tools therefore tend to use graphics cards for image-processing. 568 </p> 569 570 571 <h2>Exercises</h2> 572 <ul> 573 <li>Can you use framebuffers to create a rear-view mirror? For this you'll have to draw your scene twice: one with the camera rotated 180 degrees and the other as normal. Try to create a small quad at the top of your screen to apply the mirror texture on, something like <a href="/img/advanced/framebuffers_mirror.png" target="_blank">this</a>; <a href="/code_viewer_gh.php?code=src/4.advanced_opengl/5.2.framebuffers_exercise1/framebuffers_exercise1.cpp" target="_blank">solution</a>.</li> 574 <li>Play around with the kernel values and create your own interesting post-processing effects. Try searching the internet as well for other interesting kernels.</li> 575 </ul> 576 577 578 </div> 579