Monday, May 2, 2011

Cube Mapping

Environmental reflections can be very expensive to compute, luckily we can use a cube map accomplish this.  Cube maps are textures that help us map the environment on a 3D object like so:

Environmental reflections on a skull

Cube maps are just an array of 6 textures but instead of considering them layers of the same image (like for a volume texture) we will consider them to be the faces of the cube. The cube is centered and axis aligned with the coordinate system, because of that for a centered axis aligned cube with all values either 1 or -1 will have the same texture coordinates as position coordinates. When we will sample such a texture, we won't send a 2D vector but a 3D one representing the direction we are looking at in the cube, this is how we will decide what pixel to display.


Returning the pixel
The vector does not need to be normalized, this is because we are only interested in the vectors direction and not it's magnitude, if we double the length of the vector above, it will hit the cube in exactly the same pixel.

To create a cube map you have to render the scene using a top-down view angle of 90 and aspect ratio 1. This will generate a square image, after that rotate 90 degrees and repeat for all faces of the cube. You can either generate them using your game (even in real time) or use another application, I recommend  taking a look at Terragen because it creates very realistic environments, it's cheap and also has a free version that you can use for non commercial applications. A cube map can look something like this (they are placed in the same image here but you should have 6 different images, one for every cube face):

Classic cube map example
After you will generate the 6 images you can either load each one and create the cube map in code, or go the nice way and create a DDS image. To create that image open up DirectX Texture Tool (free) or any other editor that supports this format. Create a new cube map texture, select each face (from the view menu) and load the images onto those textures (File -> open onto this surface in DX Texture tool). You can also select a surface format (Format->Change surface format in DX Texture tool) to a compressed format to reduce the size of the file.

If you don't want to create cube maps right now but you need one just go to this link and download the images from there.

1 comment:

  1. I dont know if you will read this but I was just wondering what the directX texture tool you were talking about is and if you have a link or an exe that I can have
    -Chears

    ReplyDelete