#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:0236*/
layout(location = 0) out vec4 scene;
layout(location = 1) out vec3 indirectData;
layout(location = 2) out vec4 lightmapData;
layout(location = 3) out vec3 filterNormals;

#include "/lib/head.glsl"
#include "/lib/util/encoders.glsl"
#include "/lib/util/colorspace.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 usampler2D 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
#define FUTIL_MAT16
#include "/lib/fUtil.glsl"

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

#define noBRDF
#include "/lib/frag/labPBR.glsl"

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

    scene           = makeDrawbuffer(vec4(linearToAP1Albedo(sceneColor.rgb), sceneColor.a));

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

    uvec4 sceneData = stex(colortex1);

    if (landMask(sceneDepth)) {
        vec2 d1             = unpack2x16(sceneData.y);

        vec3 sceneNormal    = decodeNormal(unpack2x16(sceneData.x));

        filterNormals       = sceneNormal * 0.5 + 0.5;

        lightmapData.xyz    = vec3(decode2x8(d1.x), sceneColor.a);

        vec4 specularData = unpack4x8(sceneData.z);

        materialLAB matLAB = decodeSpecularTexture(specularData);

        int matID           = decodeMatID16(d1.y);
        indirectData.z      = float(matID == 5);
        indirectData.z     += float(matID == 6) * 0.25;
        indirectData.z      = max(indirectData.z, matLAB.emission);
    }

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