Hello,
i'm trying to implement screen space reflection and I get the scene the ground and the mesh reflected too.
I don't know how to debug it nor how to fix it…
Here is my attmept:
bool intersectsDepthBuffer(float z, float minZ, float maxZ, float thickness)
{
float cb_strideZCutoff = 1.0f;
float depthScale = min(1.0f, z * cb_strideZCutoff);
z += thickness + lerp(0.0f, 2.0f, depthScale);
return (maxZ >= z) && (minZ - thickness <= z);
}
bool RayMarch(float3 originVS, float3 dirVS, inout int iterations, out float3 hitPointSS, out int hitLayer)
{
float resolution = 1.0;
float max_distance = 2.5;
int steps = 10;
float farZ = 1000;
float thickness = 5;
originVS = originVS + dirVS * resolution;
float sceneZMin = farZ;
hitLayer = -1;
float deltaT = max_distance / steps;
float t = 0.0f;
float3 raySS = float3(-1, -1, farZ);
bool outOfBounds = false;
for (int i = 0; i < steps; i++)
{
iterations++;
t += deltaT;
float4 rayVS = float4(originVS + dirVS * t, 1.0);
// convert to homogenous clip space
float4 rayHS = mul(proj, rayVS);
raySS.xy = rayHS.xy / rayHS.w;
raySS.z = rayHS.w;
sceneZMin = depth_tex.SampleLevel(depth_sampler, raySS.xy, 0).x;
//outOfBounds = (sceneZMin == 0.0f);
float sceneZMax = sceneZMin + thickness;
if (intersectsDepthBuffer(rayVS.z, sceneZMin, sceneZMax, thickness))
{
hitLayer = 1;
}
if (hitLayer >= 0)
{
break;
}
}
hitPointSS = float3(raySS.xy, sceneZMin);
return (raySS.z < sceneZMin) || (sceneZMin + thickness < raySS.z);
}
PS_Output main(PS_Input input)
{
PS_Output output;
float thickness = 2.5;
float2 tex_size;
color_tex.GetDimensions(tex_size.x, tex_size.y);
float2 tex_coord = float2(input.position.xy) / float2(tex_size);
float3 originVS = position_from_texture(tex_coord).xyz;
float4 originVS_xyzw = position_from_texture(tex_coord).xyzw;
float3 normalVS = normal_tex.Sample(normal_sampler, tex_coord).xyz;
float3 viewRayVS = normalize(originVS.xyz);
float3 directionVs = reflect(viewRayVS, normalVS);
float3 hitPointSS = float3(-1.0f, -1.0f, 0.0f);
int hitLayer = -1.0f;
bool missed = true;
int iterations = 0.0f;
float4 uv = float4(0.0);
if (directionVs.z > 0.0)
{
missed = RayMarch(originVS, directionVs, iterations, hitPointSS, hitLayer);
}
float alphaBlend = 0.0f;
if (missed)
{
hitPointSS.xy = float2(-1.0f, -1.0f);
uv.ba = float2(0);
uv.xy = input.tex_coords.xy;
output.color = uv;
return output;
}
else
{
const float reflectionSpecularFalloffExponent = 3.0;
float2 dCoords = smoothstep(0.2, 0.6, abs(float2(0.5, 0.5) - hitPointSS.xy));
float Metallic = 0.4f;
float screenEdgefactor = clamp(dCoords.x + dCoords.y), 0.0, 1.0);
float alphaBlend =
screenEdgefactor
*(hitPointSS.x < 0 || hitPointSS.x > 1 ? 0 : 1)
* (hitPointSS.y < 0 || hitPointSS.y > 1 ? 0 : 1);
float depth = depth_tex.SampleLevel(depth_sampler, hitPointSS.xy, 0).x;
//if ( depth < 0.999 )
//{
float visibility = clamp(alphaBlend, 0.0, 1.0);
uv.ba = float2(visibility);
uv.xy = hitPointSS.xy;
output.color = uv;
return output;
//}
}