Cubemap Reflections with OpenGL/GLSL

There haven’t been much updates lately but nonetheless, I have been busy! The mesh kernel now has a custom property system which among other things brings support for multiple UV sets and being able to choose if a vertex property – such as normals – is unique per vertex or can be different per face connected to a vertex. Another interesting feature is surrounding support: I’ve created a simple but powerful XML format that describes what an environment looks like in which the user object is placed. It specifies the geometry of the environment, a reflection texture, the position of the main light source (so real-time shadows can automatically adjust their direction to match it) and more. This makes creating a new surrounding so easy, I didn’t even bother to write any UI for it.

Having an environment made it possible to finally have support for a reflection term in the material shader. I haven’t added a Fresnel factor yet, but that’s the easy part. What drove me nuts was getting the cube map texture to work in GLSL! Let me explain…

To get some test data, I downloaded a couple of cube maps from Humus and read up on cube maps since it’s been at least 10 years since I last looked into it! If anyone is interested, the best sources I’ve found were:

The shader code itself is fairly simple, but for some reason, the textures were up-side down or not even that: completely flipped around! I was checking and re-checking the shader and it’s parameters for a couple of hours until I thought “hey, maybe the texture is wrong”. But that cannot be it, can it? It’s just a couple of simple texture uploads, nothing can go wrong there… or so I thought…

Incorrect vs correct cube map assignment
Incorrect vs correct cube map assignment

After googling for a while, I found the solution in a post on Stackoverflow. Apparently, the OpenGL cube map definition is based on the RenderMan standard and as a result, one actually has to flip most of the cube sides before upload. GL_TEXTURE_CUBE_MAP_POSITIVE_Y and GL_TEXTURE_CUBE_MAP_NEGATIVE_Y are fine, but all others have to be flipped both horizontally and vertically. After doing that, it works perfectly.

Next up: Adding a Fresnel term and multiple texture support. I’m still wondering if I should implement a shader permutation system or use an ubershader approach. Also have to check how soon I can move to Physical Based Rendering (PBR).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*