I am trying to render 3d model to display world space normals bumped by normal map. I am having trouble to correctly apply bump map to have all ‘edges’ point proper directions. I marked some points on render of my current result to explain what I mean:
-
Correct, pointing Y, green
-
Correct, pointing X, red
-
Wrong, pointing -Z, I would expect blue edge to be on the other side of rectangle
-
Correct, pointing X, red
-
Wrong, pointing -Y, I would expect green edge to be on the other side of rectangle
-
Correct, pointing Z, blue
I am using a default unity cube as a model. I tried to use transformations I found here:
and here
https://gamedev.stackexchange.com/questions/11474/rotating-a-vector-by-another-vector-in-shader
My shader:
Shader "Custom/ShowNormals2"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float4 tangent : TANGENT;
float4 normal : NORMAL;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 tangent : TANGENT;
float4 normal : NORMAL;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.normal = float4(UnityObjectToWorldNormal(v.normal),0);
o.tangent = float4(UnityObjectToWorldNormal(v.tangent),0);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float3 normalT = UnpackNormal(tex2D(_MainTex, i.uv));
// Build orthonormal basis.
float3 N = normalize(i.normal);
float3 T = normalize(i.tangent - dot(i.tangent, N) * N);
float3 B = cross(N, T);
float3x3 TBN = float3x3(T, B, N);
// Transform from tangent space to world space.
float3 bumpedNormalW = mul(normalT, TBN);
return float4(bumpedNormalW, 1);
}
ENDCG
}
}
}