# Thread: getting the normal with dFdx and dFdy

1. ## getting the normal with dFdx and dFdy

Hello,

I cant understand this way of get the normals. Let me show you a bit of code:

fragVertexEc = (_mv * vec4(vertex, 1.0)).xyz;
(_mv is the uniform mat4 modelView Matrix)

vec3 X = dFdx(fragVertexEc);
vec3 Y = dFdy(fragVertexEc);
vec3 normal=normalize(cross(X,Y));

what are doing here dFdx and dFdy gsgl commands?

Thanks

2. dFdx and dFdy return approximations to the derivatives of their arguments. Applying them to a position on a surface returns a tangent to that surface. As the cross-product of two vectors is perpendicular to both vectors, the cross-product of two tangents is normal to the surface.

However, because fragVertexEc is linearly interpolated across the triangle, the derivatives should be the same for all fragments, so performing the calculation for each fragment is inefficient.

3. Thanks for your response...To be more efficient....Could I calculate fragVertexEc in vertex shader and pass the result to the fragment shader?

4. Could I calculate fragVertexEc in vertex shader and pass the result to the fragment shader?

5. To be more efficient, you'd calculate the normal in the geometry shader, then pass it to the fragment shader using a flat-qualified output, e.g. "flat out vec3 normal".

If you wanted smooth shading, you'd calculate the normal for each vertex in the vertex shader then to the fragment shader using an unqualified output, e.g. "out vec3 normal". Note that you need to re-normalise the normal in the fragment shader.

6. To be more efficient, you'd calculate the normal in the geometry shader, then pass it to the fragment shader using a flat-qualified output, e.g. "flat out vec3 normal".
Unless of course the usual inefficiency associated with using a GS at all hurts more than a cross-product in the FS. That probably depends on how many fragments you're generating.

7. I found an interesting article explaining this topic

http://athile.net/library/blog/?tag=dfdx

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•