Search code examples
openglglsltexture-mapping

OpenGL cubemap reflections flipping with moving camera


I am testing a basic cubemap implementation and it works fine except one last detail. When I move my camera the cubemap flips on the up/down axis.

As I move the camera, notice my view matrix when the flipping happens:

------
 0.01,  0.13, -0.99,  0.00
 0.00,  0.99,  0.13,  0.00
 1.00, -0.00,  0.01,  0.00
-1.86, -0.28, -6.34,  1.00
------ 

Gives the following picture:

enter image description here

------   
-0.01,  0.13, -0.99,  0.00
 0.00,  0.99,  0.13,  0.00
 1.00,  0.00, -0.01,  0.00
-1.95, -0.28, -6.31,  1.00
------

Gives the following picture: enter image description here

Note that sign change of 0.01 in column 1 and 3. What does this tell me?

For the normal calculations in GLSL I do the following:

Vertex shader:

mat4 model_view = view * m;
position_eye = vec3(model_view * vec4(vertex_position, 1.0));
mat3 normal_matrix = mat3(transpose(inverse(model_view)));
normal_eye = normalize(normal_matrix * vertex_normal);

Fragment shader:

 vec3 func_cubemap_reflect()
 {
   vec3 incident_eye = normalize(position_eye);
   vec3 normal = normalize(normal_eye);
   vec3 reflected = reflect(incident_eye, normal);

   // convert from eye to world space
   reflected = vec3(inverse(view) * vec4(reflected, 0.0));
   return texture (cube_texture, reflected).rgb;
  }

Any idea how to debug this or resolve it so the reflection are always the "correct way"?


Solution

  • I'd guess that you're losing precision somewhere in your calculations, possibly the matrix inversion.

    Some options:

    • Try setting highp in your shaders?
    • If your GLSL version supports it, you can try defining the view/model_view matrices as dmat4 (also for better precision).