I have to visualize the surface normals for a height field which is given as a texture. My job is only to implement a function vec3 normal(ivec2 tc)
in the fragment shader. First I have to use central differences to calculate the tangent
tx
in x-direction and ty
in y-direction for every point/pixel. Both tx and tx are vectors. Then I have to calculate n = tx x y (Cross product)
to get the normal. The normal n will be used as rgb for my pixel.
Following variables and function are given:
uniform sampler2D tex; // The height field, which contains the height in meters (float) for each point.
uniform ivec2 texSize; // The width and height of the field.
uniform float hMin; // Minimum height that occurs in the texture.
uniform float hMax; // Maximum height that occurs in the texture.
uniform float lengthScale; // Length of a single pixel in meters.
layout(location = 0) out vec4 fragColor;
in vec2 texCoords;
/**
* Fetches the height at a point.
*/
float fetch(ivec2 tc) {
return texelFetch(tex, tc, 0).r;
}
void main() {
vec4 color = vec4(0.1, 0.1, 0.1, 1);
ivec2 tc = ivec2(texCoords*texSize); // Integer (pixel) texture coordinates.
color.rgb = normal(tc);
fragColor = color;
}
...
So my question is: How can i compute the tangets tx and ty with central differences and the given variables/funtions? I know that the central difference is
f'(x)=(f(x+h)-f(x-h))/2h
for functions with 1 variable. But here I have 2 variables and also I dont know what exactly to use for h.
This is what I have tried, but it doesn’t have any effect on the texture:
vec3 normal( ivec2 tc ) {
vec3 n = vec3(0.0, 0.0, 0.0);
float txz = (fetch(ivec2(tc.x+texSize.x, tc.y))-fetch(ivec2(tc.x-texSize.x, tc.y)))/(2.0*texSize.x);
vec3 tx = vec3(tc.x, tc.y, txz);
float tyz = (fetch(ivec2(tc.x, tc.y+texSize.y))-fetch(ivec2(tc.x, tc.y-texSize.y)))/(2.0*texSize.y);
vec3 ty = vec3(tc.x, tc.y, tyz);
float nx = ty.y*tx.z-ty.z*tx.y;
float ny = ty.z*tx.x-ty.x*tx.z;
float nz = ty.x*tx.y-ty.y*tx.x;
n = vec3(nx, ny, nz);
return n;
}