
in vec2 uv;
in vec2 uvn;

out vec4 C;

uniform int commands_cnt;
uniform int input_tex;

vec4 textureAspect(
    sampler2D tex, 
    vec2 u, 
    vec2 targetRes,
    int _aspect,
    vec2 pos,
    vec2 sz
){
    vec2 inputRes = textureSize(tex, 0).xy;
//    inputRes.x /= 0.3;

    float inputRatio = (inputRes.x/inputRes.y);
    float targetRatio = (targetRes.x/targetRes.y);
    float ratio = inputRatio / targetRatio;

    #define ASPECT_MODE_FIT
    #define ASPECT_MODE_FIT_CENTER
    #define ASPECT_MODE_COVER
    #define ASPECT_MODE_COVER_CENTER

    int mode = _aspect;
//    const int mode = 3;

    if(mode == 0){
        if(ratio > 1.){
            u.y -= ( 1. - 1./ratio)*0.5;
            u.y *= ratio;
        } else {
            u.x -= (1. - ratio)*0.5;
            u.x /= ratio;
        }
    } else if (mode == 1){
        if(ratio > 1.){
            u.y *= ratio;
        } else {
            u.x /= ratio;
        }
    } else if (mode == 2){
        if(ratio > 1.){
            u.x /= ratio;
        } else {
            u.y *= ratio;
        }
    } else if (mode == 3){
        if(ratio > 1.){
            // haha
            u.x += ( 1.- 1/ratio)*0.5;
            u.x /= ratio;
        } else {
            u.y -= (1. - 1./ratio)*0.5;
            u.y *= ratio;
        }
    }


    vec4 c = texture(tex,u);
    if(
        any(greaterThan(u,vec2(1))) ||
        any(lessThan(u,vec2(0))) 
    ){
        c -= c;
    }
//    u = fract(u);
    return c;
}

struct CompObject{
    int tex_idx;
    int _aspect;
    vec2 pos;
    vec2 sz;
};
//
uniform CompObject* composite_commands;
// indices

void main() {
    vec2 u = uvn;
//    C.xyz = u.xyx;
    C.rgb = texture(textures[input_tex], u).rgb;
//    if(ivec2(1,1) == ivec2(U.xy)){
//        print(composite_commands[0].tex_idx);
//        print(composite_commands[0].pos);
//        print(composite_commands[0].sz);
//        print(composite_commands[1].tex_idx);
//    }
    vec2 targetRes = textureSize(textures[input_tex], 0).xy;
//    if(ivec2(1,1) == ivec2(U.xy)){
//        print(composite_commands[0].tex_idx);
//        print(composite_commands[0].pos);
//        print(composite_commands[0].sz);
//        print(composite_commands[1].tex_idx);
//    }
    for(int i = 0; i < commands_cnt; i++){
        CompObject comp_obj = composite_commands[i];
        
        if(dbg_frag(vec2(100))){
            print(comp_obj._aspect);
            print(comp_obj.pos);
        }
        
        sampler2D samp = textures[comp_obj.tex_idx];

        vec2 tex_sz = textureSize(samp,0).xy;
        C.rgb += textureAspect(samp, u, targetRes, comp_obj._aspect, comp_obj.pos, comp_obj.sz).rgb;
    }
    
    C.w = 1.0;
}
