vec3 motion_blur(sampler2D colortex, ivec2 FragCoord) {
    vec2 Texcoord = FragCoord * resolutionInv;
    float Depth = texture(depthtex0, Texcoord).r;

    if (Depth >= 1.0) {
        return textureLod(colortex, Texcoord, 0).rgb;
    }

    vec2 PrevCoord = toPrevScreenPos(Texcoord, Depth, false);
    vec2 Velocity = (Texcoord - PrevCoord) * resolution;

    float VelocityLength = length(Velocity);
    if (VelocityLength < 0.5) {
        return textureLod(colortex, Texcoord, 0).rgb;
    }

    Velocity = normalize(Velocity) * min(VelocityLength * MOTION_BLUR_STRENGTH, 0.5);

    const int SAMPLES = 8;
    vec3 Color = vec3(0.0);
    float Weight = 0.0;

    for (int i = 0; i < SAMPLES; i++) {
        float T = (float(i) / float(SAMPLES - 1)) * 2.0 - 1.0;
        vec2 SampleCoord = Texcoord + Velocity * T * resolutionInv;

        SampleCoord = clamp(SampleCoord, 0.0, 1.0);

        float SampleDepth = texture(depthtex0, SampleCoord).r;
        float DepthDiff = abs(Depth - SampleDepth) / max(Depth, SampleDepth);

        float SampleWeight = 1.0 - DepthDiff * 4.0;
        SampleWeight = max(SampleWeight, 0.0);
        SampleWeight *= 1.0 - abs(T) * 0.5;

        Color += textureLod(colortex, SampleCoord, 0).rgb * SampleWeight;
        Weight += SampleWeight;
    }

    if (Weight > 0.0) {
        Color /= Weight;
    } else {
        Color = textureLod(colortex, Texcoord, 0).rgb;
    }

    return Color;
}
