vec3 ssr(vec3 RVec, vec3 ViewPos, vec3 ScreenPos, float LightmapSky, bool IsHand) {
    vec3 Offset = normalize(view_screen(ViewPos + RVec, true) - ScreenPos);
    vec3 Len = (step(0, Offset) - ScreenPos) / Offset;
    float MinLen = min(Len.x, min(Len.y, Len.z)) / SSR_STEPS;
    Offset *= MinLen;

    float Noise = dither(gl_FragCoord.xy);

    vec3 ExpectedPos = ScreenPos + Offset * Noise;
    for (int i = 1; i <= SSR_STEPS; i++) {
        float RealDepth = texture(depthtex1, ExpectedPos.xy).x;
        if (RealDepth < 0.56) {
            break;
        }
        if (ExpectedPos.z > RealDepth) {
            // Depth based rejection
            if (ExpectedPos.z - RealDepth > abs(Offset.z) * 3) break;

            // Binary refinement
            for (int i = 1; i <= 4; i++) {
                Offset /= 2;
                vec3 EPos1 = ExpectedPos - Offset;
                float RDepth1 = texture(depthtex1, EPos1.xy).x;
                if (EPos1.z > RDepth1) {
                    ExpectedPos = EPos1;
                }
            }

            vec3 TerrainColor = texture(colortex0, ExpectedPos.xy).rgb;
            vec3 StartPos = view_player(ViewPos);
            vec3 EndPos = view_player(screen_view(ExpectedPos, true));
            vec3 RefColor = do_vl(StartPos, EndPos, view_player(RVec), TerrainColor, 0, 3);

            float Dist = length(EndPos) / far;
            vec3 SkyColor = get_sky(RVec, false, 1);
            return get_border_fog(Dist, RefColor, SkyColor);
        }
        ExpectedPos += Offset;
    }
    if (LightmapSky < 0.1) return vec3(0);

    vec3 StartPos = view_player(ViewPos);
    vec3 EndPos = view_player(RVec);
    vec3 SkyColor = get_sky(RVec, false, EndPos.y);
    return do_vl(StartPos, vec3(0, 10000, 0), EndPos, SkyColor, 0, 3) * LightmapSky;
}

vec3 calc_reflections(vec3 ViewPos, vec3 ViewPosN, vec3 ScreenPos, vec3 Normal, vec3 ReflectionBlendFactor, float LightmapSky, bool IsHand) {
    vec3 RVec = reflect(ViewPosN, Normal);
    vec3 RColor = ssr(RVec, ViewPos, ScreenPos, LightmapSky, IsHand);

    return RColor * ReflectionBlendFactor;
}
