/*
====================================================================================================

    Copyright (C) 2020 RRe36

    All Rights Reserved unless otherwise explicitly stated.


    By downloading this you have agreed to the license and terms of use.
    These can be found inside the included license-file
    or here: https://rre36.com/copyright-license

    Violating these terms may be penalized with actions according to the Digital Millennium
    Copyright Act (DMCA), the Information Society Directive and/or similar laws
    depending on your country.

====================================================================================================
*/

#include "/lib/head.glsl"
#include "/lib/util/colorspace.glsl"
#include "/lib/util/encoders.glsl"

in mat2x2 coord;

in vec4 tint;

flat in int matID;

flat in vec3 normal;

flat in mat2x3 lightColor;

uniform sampler2D gcolor;


/* ------ includes ------ */
#define FUTIL_LIGHTMAP
#include "/lib/fUtil.glsl"


float bayer2e(vec2 a){
    a = floor(a);
    return fract( dot(a, vec2(.5, a.y * .75)) );
}
#define bayer4e(a)   (bayer2e( .5*(a))*.25+bayer2e(a))

#define m vec3(31,63,31)
float encode3x8(vec3 a){
    float dither = bayer4e(gl_FragCoord.xy);
    a += (dither-.5) / m;
    a = saturate(a);
    ivec3 b = ivec3(a*m);
    return float( b.r|(b.g<<5)|(b.b<<11) ) / 65535.;
}
#undef m

void main() {
    vec4 sceneColor   = texture(gcolor, coord[0]);
    if (sceneColor.a<0.02) discard;
        sceneColor.rgb *= tint.rgb;

    sceneColor.rgb    = toLinear(sceneColor.rgb);
    sceneColor.rgb  = linearToAP1Albedo(sceneColor.rgb);

    vec3 hue    = normalize(sceneColor.rgb);


    /* ------ lighting ------ */

    float skyOcclusion  = cube(coord[1].y);
    float ao            = sqr(tint.a);

    vec3 indirectLight = lightColor[0];
        indirectLight  += vec3(0.5, 0.7, 1.0) * 0.01 * minLightLuma;
        indirectLight  *= ao;

    vec3 result     = indirectLight;
        result     += getBlocklightMap(lightColor[1], coord[1].x)*ao;

    sceneColor.rgb *= result;


    /*DRAWBUFFERS:312*/
    gl_FragData[0]  = makeDrawbuffer(sceneColor.rgb, saturate(sceneColor.a));
    gl_FragData[1]  = vec4(encodeNormal(normal), encode2x8(coord[1]), 1.0);
    gl_FragData[2]  = vec4(encodeMatID16(matID), encode3x8(hue), 0.0, 1.0);
}