I'm trying to ray march several depth images, but I get a black image right now.
The question is by how much should I march the ray, especially that statement t+=d ?
sampler2D _MainTex;
sampler2D _HistoryA;
sampler2D _HistoryB;
sampler2D _HistoryC;
float _dataDelta;
int _MaxIterations;
float _MaxDistance;
float _MinDistance;
uniform float4x4 inverseViewMatrix;
uniform float4x4 projMatrix;
uniform float4x4 invViewprojection;
float raymarching(float3 rayOrigin, float3 rayDirection, sampler2D textureToSample) {
float t = 0.01; // Distance Traveled from ray origin (ro) along the ray direction (rd)
float result = 0;
[unroll(100)] for (int i = 0; i < _MaxIterations; i++)
{
if (t > _MaxDistance)
{
break;
}
float3 p = rayOrigin + rayDirection * t; // This is our current position
float d = tex2D(textureToSample, p.xy);
if (p.z <= d) // We have hit something
{
result = t;
break;
}
t += d;
}
return result;
}
Ray GetCameraRay(float pixelDepth, float2 texCoords)
{
Ray o;
o.origin = mul(inverseViewMatrix, float4(0, 0, 0, 1)).xyz; // The CoP of the camera
float4 H = float4(texCoords.x * 2 - 1, (1 - texCoords.y) * 2 - 1, pixelDepth, 1);
float4 D = mul(H, invViewprojection);
float4 worldPos = D / D.w;
float3 wPos = float3(worldPos.x, worldPos.y, worldPos.z);
o.direction = normalize( wPos - o.origin);
return o;
}
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv.x = 1 - v.uv.x;
o.uv.y = v.uv.y;
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed source = tex2D(_MainTex, i.uv).r;
Ray rayA, rayB, rayC;
float history_pixelA = tex2D(_HistoryA, i.uv);
rayA = GetCameraRay(history_pixelA, i.uv);
float history_pixelB = tex2D(_HistoryB, i.uv);
rayB = GetCameraRay(history_pixelB, i.uv);
float history_pixelC = tex2D(_HistoryC, i.uv);
rayC = GetCameraRay(history_pixelC, i.uv);
float average = raymarching(rayA.origin, rayA.direction, _HistoryA);
average += raymarching(rayB.origin,rayB.direction, _HistoryB);
average += raymarching(rayC.origin, rayC.direction, _HistoryC);
average /= 3.0;
clip(_dataDelta / 256.0f - abs(source - average));
return source;
}