title: Normal map lighting is different depending on the direction
body: <p>I am trying to use a normal map instead of the vertex normals and I can't figure out which step I'm doing wrong. I want to transform the light direction into tangent space and do the calculation from there.
  First, I transform the vector normals and tangents into viewspace.</p>
  
  <pre><code>vec3 norm_viewsp = mat3(view) * normalize(norm);
  vec3 tangent_viewsp = mat3(view) * normalize(tangent);
  vec3 bitangent_viewsp = cross(tangent_viewsp, norm_viewsp);
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Xs3N4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Xs3N4.png" alt="Tangents in viewspace"></a></p>
  
  <p>Next, I build the matrix which should perform the transformation from viewspace to tangent space and use it to calculate the distance to the light in tangent space.</p>
  
  <pre><code>mat3 tbn = transpose(mat3(tangent_viewsp, bitangent_viewsp, norm_viewsp));
  vec3 light_dir = light_pos - pos.xyz;
  vec3 light_dir_viewsp = mat3(view) * light_dir;
  
  v_light_dir_tansp = tbn * light_dir_viewsp;
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/clEUd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/clEUd.png" alt="Light directions in tangent space"></a></p>
  
  <p>In the fragment shader I then sample the normal from the normal map and multiply it with the light direction.</p>
  
  <pre><code>vec3 norm = texture(normal_map, v_tex_pos).rgb * 2.0 - 1.0;
  float diffuse = dot(normalize(norm), normalize(v_light_dir_tansp));
  </code></pre>
  
  <p>The normal map definitely loads correctly.</p>
  
  <p><a href="https://i.stack.imgur.com/GXt8E.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GXt8E.png" alt="Normal map"></a></p>
  
  <p>In the result the top left corner is too dark and the bottom left too bright.<br>
  I think the problem lies somewhere with the light direction but I can't spot the mistake.</p>
  
  <p><a href="https://i.stack.imgur.com/Eca85.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Eca85.png" alt="Result"></a></p>
  
  <p>Nore that in the above pictures the values are between -1 and 1, that's why e.g. the normal map looks too dark.</p>
  
  <p><a href="https://gist.github.com/anonymous/7c0421a6c23a45d2e9d7ecfe44eaa59f" rel="noreferrer">The full shader code</a></p>
  
  <p>Edit: The light is in the center of the model.
  Lighting works fine if using the vertex normals.
  Doing the calculations in view space instead of tangent space makes no difference.</p>