precision highp float;
precision highp int;

const float depth_scale = 1.0;

uniform float uFrames;
uniform sampler2D tBase;
uniform sampler2D tGeometry;

out vec4 color_out;

in vec2 uv_frame1;
in vec2 xy_frame1;
flat in  vec2 frame1;
flat in  vec3 frame1_normal;
in vec2 uv_frame2;
in vec2 xy_frame2;
flat in  vec2 frame2;
flat in  vec3 frame2_normal;
in vec2 uv_frame3;
in vec2 xy_frame3;
flat in  vec2 frame3;
flat in  vec3 frame3_normal;
in vec4 quad_blend_weights;

vec2 recalculateUV(vec2 uv_f, vec2 frame, vec2 xy_f, vec2 frame_size, float d_scale, sampler2D depthTexture)
{
    //clamp for parallax sampling
    uv_f = clamp(uv_f, 0.0, 1.0);
    vec2 uv_quad = frame_size * (frame + uv_f);
    //paralax
    float n_depth = texture(depthTexture, uv_quad).a;
    uv_f = xy_f * (0.5-n_depth) * d_scale + uv_f;
    //clamp parallax offset
    uv_f = clamp(uv_f, 0.0, 1.0);
    uv_f =  frame_size * (frame + uv_f);
    //clamped full UV
    return clamp(uv_f, 0.0, 1.0);
}

vec4 blenderColors(vec2 uv_1, vec2 uv_2, vec2 uv_3, vec4 grid_weights, sampler2D atlasTexture)
{
    vec4 quad_a, quad_b, quad_c;

    quad_a = texture(atlasTexture, uv_1);
    quad_b = texture(atlasTexture, uv_2);
    quad_c = texture(atlasTexture, uv_3);
    return quad_a * grid_weights.x + quad_b * grid_weights.y + quad_c * grid_weights.z;
}

void main()
{
    vec2 quad_size = vec2(1.0) / uFrames;
    vec2 uv_f1 = recalculateUV(uv_frame1, frame1, xy_frame1, quad_size, depth_scale, tGeometry);
    vec2 uv_f2 = recalculateUV(uv_frame2, frame2, xy_frame2, quad_size, depth_scale, tGeometry);
    vec2 uv_f3 = recalculateUV(uv_frame3, frame3, xy_frame3, quad_size, depth_scale, tGeometry);

    vec4 baseTex = blenderColors(uv_f1, uv_f2, uv_f3, quad_blend_weights, tBase);

    //    vec4 ormTex = blenderColors(uv_f1, uv_f2, uv_f3, quad_blend_weights, imposterTextureOrm);
    //
    //    vec3 normalTex = blendedNormals(
    //    uv_f1, frame1_normal,
    //    uv_f2, frame2_normal,
    //    uv_f3, frame3_normal,
    //    TANGENT, BINORMAL,
    //    quad_blend_weights, imposterTextureNormal
    //    );
    //
    //    ALBEDO = baseTex.rgb * albedo.rgb;
    //    NORMAL =normalTex.xyz;
    //
    //    METALLIC = ormTex.b * metallic;
    //    SPECULAR = specular;
    //    ROUGHNESS = ormTex.g * roughness;


    color_out = baseTex;
    //    color_out = vec4(1.0);
}
