#version 400 compatibility

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

    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.

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

/*DRAWBUFFERS:36*/
layout(location = 0) out vec4 lightmapData;
layout(location = 1) out vec3 filterNormals;

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

const int noiseTextureResolution = 256;

// AO AND LIGHTMAP FILTER SETUP

in vec2 coord;

flat in mat2x3 lightColor;
flat in vec3 sky_color;

uniform sampler2D colortex0;
uniform sampler2D colortex1;
uniform sampler2D depthtex1;

uniform sampler2D noisetex;

uniform int frameCounter;

uniform float aspectRatio;
uniform float far, near;

uniform mat4 gbufferProjection;

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

#include "/lib/frag/bluenoise.glsl"


/* ------ ambient occlusion and gi ------ */
#include "/lib/light/ao.glsl"

void main() {
    vec4 sceneColor   = stex(colortex0);
    float sceneDepth = stex(depthtex1).x;

    lightmapData    = vec4(0.0);
    filterNormals   = vec3(0.0);

    #ifdef lightmapSmoothingEnabled
    if (landMask(sceneDepth)) {
        vec4 tex1           = stex(colortex1);
        lightmapData.xyz    = vec3(decode2x8(tex1.z), sceneColor.a);
        filterNormals       = decodeNormal(tex1.xy) * 0.5 + 0.5;
    }
    #endif

    #ifdef ambientOcclusionEnabled
        vec2 ao_coord   = (coord)*2.0;

        if (clamp(ao_coord, -0.003, 1.003) == ao_coord) {
            vec2 coord  = ao_coord;
            float d     = depthMax3x3(depthtex1, ao_coord, pixelSize*sqrt(2.0));

            if (landMask(d)) {
                float sceneDepth = stex(depthtex1).x;
                vec4 tex1       = stex(colortex1);

                vec3 viewpos    = screenToViewSpace(vec3(coord, sceneDepth));

                vec3 sceneNormal = decodeNormal(tex1.xy);
                vec3 viewnormal = normalize(mat3(gbufferModelView) * sceneNormal);

                float ao    = calculate_dbao(depthtex1, sceneDepth, coord, ditherBluenoise());
                //float ao    = calculate_ssao(depthtex1, viewpos, viewnormal, ditherBluenoise());

                lightmapData.w  = ao;
            } else {
                lightmapData.w  = 1.0;
            }
        }
    #endif

    lightmapData    = clamp16F(lightmapData);
    filterNormals   = clamp16F(filterNormals);
}