- Home /
Displace and show normals in fragment shader
Hi,
I'm using the unity's fragment shader to display normals (can be found here), and i want to displace the mesh (a plane) before showing normals. I got a result where the mesh was displaced but the normals were not updated.
How this can be achieved?
Here is the code :
v2f vert (appdata_base v)
{
float d = tex2Dlod(_DispTex, float4(v.texcoord.xy,0,0)).r * _DispAmount;
v2f o;
v.vertex.xyz += v.normal * d;
o.vertex = UnityObjectToClipPos(v.vertex);
v.normal.xyz += v.normal * d;
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.color.xyz = float3(-v.normal.x*0.5+0.5,v.normal.y*0.5+0.5,v.normal.z*0.5+0.5);
return o;
}
And the result :
Answer by Namey5 · Apr 21, 2018 at 11:03 PM
The thing is;
v.normal.xyz += v.normal * d;
doesn't actually do anything.
v.vertex.xyz += v.normal * d;
works because v.vertex is a position, however v.normal is a direction.
There's no real way to recalculate normals in the vertex shader. It's unfortunate, but we need access to the adjacent verticies in order to calculate the normals. However, because of the way vertex shaders are, we can't actually do that.
Your closest bet is to use a geometry shader, but these are moderately complex and also annoyingly enough do the opposite of vertex shaders; i.e. we can access multiple verticies, but because of this we can't interpolate between them, meaning we get flat, unsmooth normals.