xem / W

A micro WebGL2 framework with a ton of features
https://xem.github.io/W
331 stars 23 forks source link

Normalize the normal in the fragment shader #2

Closed stasm closed 3 years ago

stasm commented 3 years ago

The normals are computed in the vertex shader, after which they're interpolated between vertices for each rasterized fragment. This interpolation can change the magnitude of the per-fragment normal, so it's best to normalize normals in the fragment shader.

xem commented 3 years ago

Thanks! I read that's recommended indeed, and I understand what it means mathematically, so I will accept your PR, though i can't figure out what's rhe risk if we don't do it? Slightly deformed shading? Something else? Thanks :)

stasm commented 3 years ago

Good question. My understanding is that you risk having slightly incorrect shading, yes, in particular on fragments far away from any vertex. The nDotL thing in the fragment shader is meant to measure the angle between the fragment's normal and the light direction. dot(a, b) = cos(angle between a and b), but only when a and b are normalized. If they're not, you need to divide by the product of their magnitudes:

xem commented 3 years ago

thanks :D