Search code examples
openglglslopengl-3

How to get flat normals on a cube


I am using OpenGL without the deprecated features and my light calculation is done on fragment shader. So, I am doing smooth shading.

My problem, is that when I am drawing a cube, I need flat normals. By flat normals I mean that every fragment generated in a face has the same normal.

My solution to this so far is to generate different vertices for each face. So, instead of having 8 vertices, now I have 24(6*4) vertices.

But this seems wrong to me, replicating the vertexes. Is there a better way to get flat normals?

Update: I am using OpenGL version 3.3.0, I do not have support for OpenGL 4 yet.


Solution

  • If you do the lighting in camera-space, you can use dFdx/dFdy to calculate the normal of the face from the camera-space position of the vertex.

    So the fragment shader would look a little like this.

    varying vec3 v_PositionCS; // Position of the vertex in camera/eye-space (passed in from the vertex shader)
    
        void main()
        { 
          // Calculate the face normal in camera space
          vec3 normalCs = normalize(cross(dFdx(v_PositionCS), dFdy(v_PositionCS)));
    
          // Perform lighting 
          ...
          ...
        }