Cubemaps.html (30155B)
1 <div id="content"> 2 <h1 id="content-title">Cubemaps</h1> 3 <h1 id="content-url" style='display:none;'>Advanced-OpenGL/Cubemaps</h1> 4 <p> 5 We've been using 2D textures for a while now, but there are more texture types we haven't explored yet and in this chapter we'll discuss a texture type that is a combination of multiple textures mapped into one: a <def>cube map</def>. 6 </p> 7 8 <p> 9 A cubemap is a texture that contains 6 individual 2D textures that each form one side of a cube: a textured cube. You may be wondering what the point is of such a cube? Why bother combining 6 individual textures into a single entity instead of just using 6 individual textures? Well, cube maps have the useful property that they can be indexed/sampled using a direction vector. Imagine we have a 1x1x1 unit cube with the origin of a direction vector residing at its center. Sampling a texture value from the cube map with an orange direction vector looks a bit like this: 10 </p> 11 12 <img src="/img/advanced/cubemaps_sampling.png" class="clean" alt="Indexing/Sampling from a cubemap in OpenGL"/> 13 14 <note> 15 The magnitude of the direction vector doesn't matter. As long as a direction is supplied, OpenGL retrieves the corresponding texels that the direction hits (eventually) and returns the properly sampled texture value. 16 </note> 17 18 <p> 19 If we imagine we have a cube shape that we attach such a cubemap to, this direction vector would be similar to the (interpolated) local vertex position of the cube. This way we can sample the cubemap using the cube's actual position vectors as long as the cube is centered on the origin. We thus consider all vertex positions of the cube to be its texture coordinates when sampling a cubemap. The result is a texture coordinate that accesses the proper individual <def>face</def> texture of the cubemap. 20 </p> 21 22 <h2>Creating a cubemap</h2> 23 <p> 24 A cubemap is a texture like any other texture, so to create one we generate a texture and bind it to the proper texture target before we do any further texture operations. This time binding it to <var>GL_TEXTURE_CUBE_MAP</var>: 25 </p> 26 27 <pre class="cpp"><code> 28 unsigned int textureID; 29 <function id='50'>glGenTextures</function>(1, &textureID); 30 <function id='48'>glBindTexture</function>(GL_TEXTURE_CUBE_MAP, textureID); 31 </code></pre> 32 33 <p> 34 Because a cubemap contains 6 textures, one for each face, we have to call <fun><function id='52'>glTexImage2D</function></fun> six times with their parameters set similarly to the previous chapters. This time however, we have to set the texture <em>target</em> parameter to match a specific face of the cubemap, telling OpenGL which side of the cubemap we're creating a texture for. This means we have to call <fun><function id='52'>glTexImage2D</function></fun> once for each face of the cubemap. 35 </p> 36 37 <p> 38 Since we have 6 faces OpenGL gives us 6 special texture targets for targeting a face of the cubemap: 39 </p> 40 41 <table> 42 <tr> 43 <th>Texture target</th> 44 <th>Orientation</th> 45 </tr> 46 <tr> 47 <td><code>GL_TEXTURE_CUBE_MAP_POSITIVE_X</code></td> 48 <td>Right</td> 49 </tr> 50 <tr> 51 <td><code>GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code></td> 52 <td>Left</td> 53 </tr> 54 <tr> 55 <td><code>GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code></td> 56 <td>Top</td> 57 </tr> 58 <tr> 59 <td><code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code></td> 60 <td>Bottom</td> 61 </tr> 62 <tr> 63 <td><code>GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code></td> 64 <td>Back</td> 65 </tr> 66 <tr> 67 <td><code>GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code></td> 68 <td>Front</td> 69 </tr> 70 </table> 71 72 <p> 73 Like many of OpenGL's enums, their behind-the-scenes <fun>int</fun> value is linearly incremented, so if we were to have an array or vector of texture locations we could loop over them by starting with <var>GL_TEXTURE_CUBE_MAP_POSITIVE_X</var> and incrementing the enum by 1 each iteration, effectively looping through all the texture targets: 74 </p> 75 76 <pre><code> 77 int width, height, nrChannels; 78 unsigned char *data; 79 for(unsigned int i = 0; i < textures_faces.size(); i++) 80 { 81 data = stbi_load(textures_faces[i].c_str(), &width, &height, &nrChannels, 0); 82 <function id='52'>glTexImage2D</function>( 83 GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 84 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data 85 ); 86 } 87 </code></pre> 88 89 <p> 90 Here we have a <fun>vector</fun> called <var>textures_faces</var> that contain the locations of all the textures required for the cubemap in the order as given in the table. This generates a texture for each face of the currently bound cubemap. 91 </p> 92 93 <p> 94 Because a cubemap is a texture like any other texture, we will also specify its wrapping and filtering methods: 95 </p> 96 97 <pre><code> 98 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 99 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 100 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 101 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 102 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); 103 </code></pre> 104 105 <p> 106 Don't be scared by the <var>GL_TEXTURE_WRAP_R</var>, this simply sets the wrapping method for the texture's <code>R</code> coordinate which corresponds to the texture's 3rd dimension (like <code>z</code> for positions). We set the wrapping method to <var>GL_CLAMP_TO_EDGE</var> since texture coordinates that are exactly between two faces may not hit an exact face (due to some hardware limitations) so by using <var>GL_CLAMP_TO_EDGE</var> OpenGL always returns their edge values whenever we sample between faces. 107 </p> 108 109 <p> 110 Then before drawing the objects that will use the cubemap, we activate the corresponding texture unit and bind the cubemap before rendering; not much of a difference compared to normal 2D textures. 111 </p> 112 113 <p> 114 Within the fragment shader we also have to use a different sampler of the type <code>samplerCube</code> that we sample from using the <fun>texture</fun> function, but this time using a <code>vec3</code> direction vector instead of a <code>vec2</code>. An example of fragment shader using a cubemap looks like this: 115 </p> 116 117 <pre><code> 118 in vec3 textureDir; // direction vector representing a 3D texture coordinate 119 uniform samplerCube cubemap; // cubemap texture sampler 120 121 void main() 122 { 123 FragColor = texture(cubemap, textureDir); 124 } 125 </code></pre> 126 127 128 <p> 129 That is still great and all, but why bother? Well, it just so happens that there are quite a few interesting techniques that are a lot easier to implement with a cubemap. One of those techniques is creating a <def>skybox</def>. 130 </p> 131 132 <h1>Skybox</h1> 133 <p> 134 A skybox is a (large) cube that encompasses the entire scene and contains 6 images of a surrounding environment, giving the player the illusion that the environment he's in is actually much larger than it actually is. Some examples of skyboxes used in videogames are images of mountains, of clouds, or of a starry night sky. An example of a skybox, using starry night sky images, can be seen in the following screenshot of the third elder scrolls game: 135 </p> 136 137 <img src="/img/advanced/cubemaps_morrowind.jpg" alt="Image of morrowind with a skybox"/> 138 139 <p> 140 You probably guessed by now that skyboxes like this suit cubemaps perfectly: we have a cube that has 6 faces and needs to be textured per face. In the previous image they used several images of a night sky to give the illusion the player is in some large universe while he's actually inside a tiny little box. 141 </p> 142 143 <p> 144 There are usually enough resources online where you could find skyboxes like that. These skybox images usually have the following pattern: 145 </p> 146 147 <img src="/img/advanced/cubemaps_skybox.png" class="clean" alt="Image of a skybox for a cubemap in OpenGL"/> 148 149 <p> 150 If you would fold those 6 sides into a cube you'd get the completely textured cube that simulates a large landscape. Some resources provide the skybox in a format like that in which case you'd have to manually extract the 6 face images, but in most cases they're provided as 6 single texture images. 151 </p> 152 153 <p> 154 This particular (high-quality) skybox is what we'll use for our scene and can be downloaded <a href="/img/textures/skybox.zip" target="_blank">here</a>. 155 </p> 156 157 <h2>Loading a skybox</h2> 158 <p> 159 Since a skybox is by itself just a cubemap, loading a skybox isn't too different from what we've seen at the start of this chapter. To load the skybox we're going to use the following function that accepts a <fun>vector</fun> of 6 texture locations: 160 </p> 161 162 <pre><code> 163 unsigned int loadCubemap(vector<std::string> faces) 164 { 165 unsigned int textureID; 166 <function id='50'>glGenTextures</function>(1, &textureID); 167 <function id='48'>glBindTexture</function>(GL_TEXTURE_CUBE_MAP, textureID); 168 169 int width, height, nrChannels; 170 for (unsigned int i = 0; i < faces.size(); i++) 171 { 172 unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0); 173 if (data) 174 { 175 <function id='52'>glTexImage2D</function>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 176 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data 177 ); 178 stbi_image_free(data); 179 } 180 else 181 { 182 std::cout << "Cubemap tex failed to load at path: " << faces[i] << std::endl; 183 stbi_image_free(data); 184 } 185 } 186 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 187 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 188 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 189 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 190 <function id='15'>glTexParameter</function>i(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); 191 192 return textureID; 193 } 194 </code></pre> 195 196 <p> 197 The function itself shouldn't be too surprising. It is basically all the cubemap code we've seen in the previous section, but combined in a single manageable function. 198 </p> 199 200 <p> 201 Now, before we call this function we'll load the appropriate texture paths in a vector in the order as specified by the cubemap enums: 202 </p> 203 204 <pre><code> 205 vector<std::string> faces; 206 { 207 "right.jpg", 208 "left.jpg", 209 "top.jpg", 210 "bottom.jpg", 211 "front.jpg", 212 "back.jpg" 213 }; 214 unsigned int cubemapTexture = loadCubemap(faces); 215 </code></pre> 216 217 <p> 218 We loaded the skybox as a cubemap with <var>cubemapTexture</var> as its id. We can now finally bind it to a cube to replace that lame clear color we've been using all this time. 219 </p> 220 221 <h2>Displaying a skybox</h2> 222 <p> 223 Because a skybox is drawn on a cube we'll need another VAO, VBO and a fresh set of vertices like any other 3D object. You can get its vertex data <a href="/code_viewer.php?code=advanced/cubemaps_skybox_data" target="_blank">here</a>. 224 </p> 225 226 <p> 227 A cubemap used to texture a 3D cube can be sampled using the local positions of the cube as its texture coordinates. When a cube is centered on the origin (0,0,0) each of its position vectors is also a direction vector from the origin. This direction vector is exactly what we need to get the corresponding texture value at that specific cube's position. For this reason we only need to supply position vectors and don't need texture coordinates. 228 </p> 229 230 <p> 231 To render the skybox we'll need a new set of shaders which aren't too complicated. Because we only have one vertex attribute the vertex shader is quite simple: 232 </p> 233 234 <pre><code> 235 #version 330 core 236 layout (location = 0) in vec3 aPos; 237 238 out vec3 TexCoords; 239 240 uniform mat4 projection; 241 uniform mat4 view; 242 243 void main() 244 { 245 TexCoords = aPos; 246 gl_Position = projection * view * vec4(aPos, 1.0); 247 } 248 </code></pre> 249 250 <p> 251 The interesting part of this vertex shader is that we set the incoming local position vector as the outcoming texture coordinate for (interpolated) use in the fragment shader. The fragment shader then takes these as input to sample a <code>samplerCube</code>: 252 </p> 253 254 <pre><code> 255 #version 330 core 256 out vec4 FragColor; 257 258 in vec3 TexCoords; 259 260 uniform samplerCube skybox; 261 262 void main() 263 { 264 FragColor = texture(skybox, TexCoords); 265 } 266 </code></pre> 267 268 <p> 269 The fragment shader is relatively straightforward. We take the vertex attribute's interpolated position vector as the texture's direction vector and use it to sample the texture values from the cubemap. 270 </p> 271 272 <p> 273 Rendering the skybox is easy now that we have a cubemap texture, we simply bind the cubemap texture and the <var>skybox</var> sampler is automatically filled with the skybox cubemap. To draw the skybox we're going to draw it as the first object in the scene and disable depth writing. This way the skybox will always be drawn at the background of all the other objects since the unit cube is most likely smaller than the rest of the scene. 274 </p> 275 276 <pre><code> 277 <function id='65'>glDepthMask</function>(GL_FALSE); 278 skyboxShader.use(); 279 // ... set view and projection matrix 280 <function id='27'>glBindVertexArray</function>(skyboxVAO); 281 <function id='48'>glBindTexture</function>(GL_TEXTURE_CUBE_MAP, cubemapTexture); 282 <function id='1'>glDrawArrays</function>(GL_TRIANGLES, 0, 36); 283 <function id='65'>glDepthMask</function>(GL_TRUE); 284 // ... draw rest of the scene 285 </code></pre> 286 287 <p> 288 If you run this you will get into difficulties though. We want the skybox to be centered around the player so that no matter how far the player moves, the skybox won't get any closer, giving the impression the surrounding environment is extremely large. The current view matrix however transforms all the skybox's positions by rotating, scaling and translating them, so if the player moves, the cubemap moves as well! We want to remove the translation part of the view matrix so only rotation will affect the skybox's position vectors. 289 </p> 290 291 <p> 292 You may remember from the <a href="https://learnopengl.com/Lighting/Basic-Lighting" target="_blank">basic lighting</a> chapter that we can remove the translation section of transformation matrices by taking the upper-left 3x3 matrix of the 4x4 matrix. We can achieve this by converting the view matrix to a 3x3 matrix (removing translation) and converting it back to a 4x4 matrix: 293 </p> 294 295 <pre><code> 296 glm::mat4 view = glm::mat4(glm::mat3(camera.GetViewMatrix())); 297 </code></pre> 298 299 <p> 300 This removes any translation, but keeps all rotation transformations so the user can still look around the scene. 301 </p> 302 303 <p> 304 The result is a scene that instantly looks enormous due to our skybox. If you'd fly around the basic container you immediately get a sense of scale which dramatically improves the realism of the scene. The result looks something like this: 305 </p> 306 307 <img src="/img/advanced/cubemaps_skybox_result.png" class="clean" alt="Image of a skybox in an OpenGL scene"/> 308 309 <p> 310 Try experimenting with different skyboxes and see how they can have an enormous impact on the look and feel of your scene. 311 </p> 312 313 <h2>An optimization</h2> 314 <p> 315 Right now we've rendered the skybox first before we rendered all the other objects in the scene. This works great, but isn't too efficient. If we render the skybox first we're running the fragment shader for each pixel on the screen even though only a small part of the skybox will eventually be visible; fragments that could have easily been discarded using <def>early depth testing</def> saving us valuable bandwidth. 316 </p> 317 318 <p> 319 So to give us a slight performance boost we're going to render the skybox last. This way, the depth buffer is completely filled with all the scene's depth values so we only have to render the skybox's fragments wherever the early depth test passes, greatly reducing the number of fragment shader calls. The problem is that the skybox will most likely render on top of all other objects since it's only a 1x1x1 cube, succeeding most depth tests. Simply rendering it without depth testing is not a solution since the skybox will then still overwrite all the other objects in the scene as it's rendered last. We need to trick the depth buffer into believing that the skybox has the maximum depth value of <code>1.0</code> so that it fails the depth test wherever there's a different object in front of it. 320 </p> 321 322 <p> 323 In the <a href="https://learnopengl.com/Getting-started/Coordinate-Systems" target="_blank">coordinate systems</a> chapter we said that <em>perspective division</em> is performed after the vertex shader has run, dividing the <var>gl_Position</var>'s <code>xyz</code> coordinates by its <code>w</code> component. We also know from the <a href="https://learnopengl.com/Advanced-OpenGL/Depth-testing" target="_blank">depth testing</a> chapter that the <code>z</code> component of the resulting division is equal to that vertex's depth value. Using this information we can set the <code>z</code> component of the output position equal to its <code>w</code> component which will result in a <code>z</code> component that is always equal to <code>1.0</code>, because when the perspective division is applied its <code>z</code> component translates to <code>w</code> / <code>w</code> = <code>1.0</code>: 324 </p> 325 326 <pre><code> 327 void main() 328 { 329 TexCoords = aPos; 330 vec4 pos = projection * view * vec4(aPos, 1.0); 331 gl_Position = pos.xyww; 332 } 333 </code></pre> 334 335 <p> 336 The resulting <em>normalized device coordinates</em> will then always have a <code>z</code> value equal to <code>1.0</code>: the maximum depth value. The skybox will as a result only be rendered wherever there are no objects visible (only then it will pass the depth test, everything else is in front of the skybox). 337 </p> 338 339 <p> 340 We do have to change the depth function a little by setting it to <var>GL_LEQUAL</var> instead of the default <var>GL_LESS</var>. The depth buffer will be filled with values of <code>1.0</code> for the skybox, so we need to make sure the skybox passes the depth tests with values <em>less than or equal</em> to the depth buffer instead of <em>less than</em>. 341 </p> 342 343 <p> 344 You can find the more optimized version of the source code <a href="/code_viewer_gh.php?code=src/4.advanced_opengl/6.1.cubemaps_skybox/cubemaps_skybox.cpp" target="_blank">here</a>. 345 </p> 346 347 <h1>Environment mapping</h1> 348 <p> 349 We now have the entire surrounding environment mapped in a single texture object and we could use that information for more than just a skybox. Using a cubemap with an environment, we could give objects reflective or refractive properties. Techniques that use an environment cubemap like this are called <def>environment mapping</def> techniques and the two most popular ones are <def>reflection</def> and <def>refraction</def>. 350 </p> 351 352 <h2>Reflection</h2> 353 <p> 354 Reflection is the property that an object (or part of an object) <def>reflects</def> its surrounding environment e.g. the object's colors are more or less equal to its environment based on the angle of the viewer. A mirror for example is a reflective object: it reflects its surroundings based on the viewer's angle. 355 </p> 356 357 <p> 358 The basics of reflection are not that difficult. The following image shows how we can calculate a <def>reflection vector</def> and use that vector to sample from a cubemap: 359 </p> 360 361 <img src="/img/advanced/cubemaps_reflection_theory.png" class="clean" alt="Image of how to calculate reflection."/> 362 363 <p> 364 We calculate a reflection vector \(\color{green}{\bar{R}}\) around the object's normal vector \(\color{red}{\bar{N}}\) based on the view direction vector \(\color{gray}{\bar{I}}\). We can calculate this reflection vector using GLSL's built-in <fun>reflect</fun> function. The resulting vector \(\color{green}{\bar{R}}\) is then used as a direction vector to index/sample the cubemap, returning a color value of the environment. The resulting effect is that the object seems to reflect the skybox. 365 </p> 366 367 <p> 368 Since we already have a skybox setup in our scene, creating reflections isn't too difficult. We'll change the fragment shader used by the container to give the container reflective properties: 369 </p> 370 371 <pre><code> 372 #version 330 core 373 out vec4 FragColor; 374 375 in vec3 Normal; 376 in vec3 Position; 377 378 uniform vec3 cameraPos; 379 uniform samplerCube skybox; 380 381 void main() 382 { 383 vec3 I = normalize(Position - cameraPos); 384 vec3 R = reflect(I, normalize(Normal)); 385 FragColor = vec4(texture(skybox, R).rgb, 1.0); 386 } 387 </code></pre> 388 389 <p> 390 We first calculate the view/camera direction vector <var>I</var> and use this to calculate the reflect vector <var>R</var> which we then use to sample from the skybox cubemap. Note that we have the fragment's interpolated <var>Normal</var> and <var>Position</var> variable again so we'll need to adjust the vertex shader as well: 391 </p> 392 393 <pre><code> 394 #version 330 core 395 layout (location = 0) in vec3 aPos; 396 layout (location = 1) in vec3 aNormal; 397 398 out vec3 Normal; 399 out vec3 Position; 400 401 uniform mat4 model; 402 uniform mat4 view; 403 uniform mat4 projection; 404 405 void main() 406 { 407 Normal = mat3(transpose(inverse(model))) * aNormal; 408 Position = vec3(model * vec4(aPos, 1.0)); 409 gl_Position = projection * view * vec4(Position, 1.0); 410 } 411 </code></pre> 412 413 <p> 414 We're using normal vectors so we'll want to transform them with a normal matrix again. The <var>Position</var> output vector is a world-space position vector. This <var>Position</var> output of the vertex shader is used to calculate the view direction vector in the fragment shader. 415 </p> 416 417 <p> 418 Because we're using normals you'll want to update the <a href="/code_viewer.php?code=lighting/basic_lighting_vertex_data" target="_blank">vertex data</a> and update the attribute pointers as well. Also make sure to set the <var>cameraPos</var> uniform. 419 </p> 420 421 <p> 422 Then we also want to bind the cubemap texture before rendering the container: 423 </p> 424 425 <pre class="cpp"><code> 426 <function id='27'>glBindVertexArray</function>(cubeVAO); 427 <function id='48'>glBindTexture</function>(GL_TEXTURE_CUBE_MAP, skyboxTexture); 428 <function id='1'>glDrawArrays</function>(GL_TRIANGLES, 0, 36); 429 </code></pre> 430 431 <p> 432 Compiling and running your code gives you a container that acts like a perfect mirror. The surrounding skybox is perfectly reflected on the container: 433 </p> 434 435 <img src="/img/advanced/cubemaps_reflection.png" class="clean" alt="Image of a cube reflecting a skybox via cubemaps via environment mapping."/> 436 437 <p> 438 You can find the full source code <a href="/code_viewer_gh.php?code=src/4.advanced_opengl/6.2.cubemaps_environment_mapping/cubemaps_environment_mapping.cpp" target="_blank">here</a>. 439 </p> 440 441 <p> 442 When reflection is applied to an entire object (like the container) the object looks as if it has a high reflective material like steel or chrome. If we were to load a more interesting object (like the backpack model from the <a href="https://learnopengl.com/Model-Loading/Model" target="_blank">model loading</a> chapters) we'd get the effect that the object looks to be entirely made out of chrome: 443 </p> 444 445 <img src="/img/advanced/cubemaps_reflection_nanosuit.png" alt="Image of a Backpack model reflecting a skybox via cubemaps via environment mapping."/> 446 447 <p> 448 This looks quite awesome, but in reality most models aren't all completely reflective. We could for instance introduce <def>reflection maps</def> that give the models another extra level of detail. Just like diffuse and specular maps, reflection maps are texture images that we can sample to determine the reflectivity of a fragment. Using these reflection maps we can determine which parts of the model show reflection and by what intensity. <!--In the exercise of this chapter it's up to you to introduce reflection maps in the model loader we created earlier, significantly boosting the detail of the 3D object.--> 449 </p> 450 451 <h2>Refraction</h2> 452 <p> 453 Another form of environment mapping is called <def>refraction</def> and is similar to reflection. Refraction is the change in direction of light due to the change of the material the light flows through. Refraction is what we commonly see with water-like surfaces where the light doesn't enter straight through, but bends a little. It's like looking at your arm when it's halfway in the water. 454 </p> 455 456 <p> 457 Refraction is described by <a href="http://en.wikipedia.org/wiki/Snell%27s_law" target="_blank">Snell's law</a> that with environment maps looks a bit like this: 458 </p> 459 460 <img src="/img/advanced/cubemaps_refraction_theory.png" class="clean" alt="Image explaining refraction of light for use with cubemaps."/> 461 462 <p> 463 Again, we have a view vector \(\color{gray}{\bar{I}}\), a normal vector \(\color{red}{\bar{N}}\) and this time a resulting refraction vector \(\color{green}{\bar{R}}\). As you can see, the direction of the view vector is slightly bend. This resulting bended vector \(\color{green}{\bar{R}}\) is then used to sample from the cubemap. 464 </p> 465 466 <p> 467 Refraction is fairly easy to implement using GLSL's built-in <fun>refract</fun> function that expects a normal vector, a view direction, and a ratio between both materials' <def>refractive indices</def>. 468 </p> 469 470 <p> 471 The refractive index determines the amount light distorts/bends in a material where each material has its own refractive index. A list of the most common refractive indices are given in the following table: 472 </p> 473 474 <table> 475 <tr> 476 <th>Material</th> 477 <th>Refractive index</th> 478 </tr> 479 <tr> 480 <td>Air</td> 481 <td>1.00</td> 482 </tr> 483 <tr> 484 <td>Water</td> 485 <td>1.33</td> 486 </tr> 487 <tr> 488 <td>Ice</td> 489 <td>1.309</td> 490 </tr> 491 <tr> 492 <td>Glass</td> 493 <td>1.52</td> 494 </tr> 495 <tr> 496 <td>Diamond</td> 497 <td>2.42</td> 498 </tr> 499 </table> 500 501 <p> 502 We use these refractive indices to calculate the ratio between both materials the light passes through. In our case, the light/view ray goes from <em>air</em> to <em>glass</em> (if we assume the object is made of glass) so the ratio becomes \(\frac{1.00}{1.52} = 0.658\). 503 </p> 504 505 <p> 506 We already have the cubemap bound, supplied the vertex data with normals, and set the camera position as a uniform. The only thing we have to change is the fragment shader: 507 </p> 508 509 <pre><code> 510 void main() 511 { 512 float ratio = 1.00 / 1.52; 513 vec3 I = normalize(Position - cameraPos); 514 vec3 R = refract(I, normalize(Normal), ratio); 515 FragColor = vec4(texture(skybox, R).rgb, 1.0); 516 } 517 </code></pre> 518 519 <p> 520 By changing the refractive indices you can create completely different visual results. Compiling the application and running the results on the container object is not so interesting though as it doesn't really show the effect refraction has aside that it acts as a magnifying glass right now. Using the same shaders on the loaded 3D model however does show us the effect we're looking for: a glass-like object. 521 </p> 522 523 <img src="/img/advanced/cubemaps_refraction.png" alt="Image of environment maps using refraction in OpenGL"/> 524 525 <p> 526 You can imagine that with the right combination of lighting, reflection, refraction and vertex movement, you can create pretty neat water graphics. Do note that for physically accurate results we should refract the light <strong>again</strong> when it leaves the object; now we simply used single-sided refraction which is fine for most purposes. 527 </p> 528 529 <h2>Dynamic environment maps</h2> 530 <p> 531 Right now we've been using a static combination of images as the skybox, which looks great, but it doesn't include the actual 3D scene with possibly moving objects. We didn't really notice this so far, because we only used a single object. If we had a mirror-like objects with multiple surrounding objects, only the skybox would be visible in the mirror as if it was the only object in the scene. 532 </p> 533 534 <p> 535 Using framebuffers it is possible to create a texture of the scene for all 6 different angles from the object in question and store those in a cubemap each frame. We can then use this (dynamically generated) cubemap to create realistic reflection and refractive surfaces that include all other objects. This is called <def>dynamic environment mapping</def>, because we dynamically create a cubemap of an object's surroundings and use that as its environment map. 536 </p> 537 538 <p> 539 While it looks great, it has one enormous disadvantage: we have to render the scene 6 times per object using an environment map, which is an enormous performance penalty on your application. Modern applications try to use the skybox as much as possible and where possible pre-render cubemaps wherever they can to still sort-of create dynamic environment maps. While dynamic environment mapping is a great technique, it requires a lot of clever tricks and hacks to get it working in an actual rendering application without too many performance drops. 540 </p> 541 542 543 544 <!--<h2>Exercises</h2> 545 <ul> 546 <li>Try to introduce reflection maps into the model loader we created in the <a href="https://learnopengl.com/Model-Loading/Assimp" target="_blank">model loading</a> chapters. You can find the upgraded nanosuit model with reflection maps included <a href="/objects/nanosuit_reflection.zip" target="_blank">here</a>. There are a few things to note though:</li> 547 <ul> 548 <li>Assimp doesn't really seem to like reflection maps in most object formats so we cheated a little by storing the reflection maps as <em>ambient maps</em>. You can then load the reflection maps by specifying <var>aiTextureType_AMBIENT</var> as the texture type when loading materials.</li> 549 <li>I sort of hastily created reflection map textures from the specular texture images, so the reflection maps won't map exactly to the model in some places :).</li> 550 <li>Since the model loader by itself already takes up 3 texture units in the shader, you'll have to bind the skybox to a 4th texture unit since we'll also sample from the skybox in the same shader.</li> 551 </ul> 552 <li>If you did things right it'll look something like <a href="/img/advanced/cubemaps_reflection_map.png" target="_blank">this</a>. 553 </li> 554 </ul> 555 --> 556 557 </div> 558