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

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

const int shadowMapResolution   = 3072;     //[512 1024 1536 2048 2560 3072 3584 4096 6144 8192 16384]
const float shadowDistance      = 128.0;

const bool shadowHardwareFiltering = false;

// SKYBOX PRECOMPUTATION FOR LATER PASSES
// AO AND LIGHTMAP FILTER SETUP

const int noiseTextureResolution = 256;

in vec2 coord;

flat in vec3 airIlluminance;
flat in mat2x3 airIllumMod;

uniform sampler2D colortex0;
uniform usampler2D colortex1;
uniform sampler2D colortex2;
uniform sampler2D depthtex1;

uniform sampler2D noisetex;

uniform sampler2D shadowtex0;
uniform sampler2D shadowtex1;
uniform sampler2D shadowcolor0;

uniform int frameCounter;

uniform float aspectRatio;
uniform float eyeAltitude;
uniform float far, near;

uniform vec2 viewSize, pixelSize;
uniform vec2 taaOffset;

uniform vec3 lightvec, lightvecView;
uniform vec3 upvec, upvecView;
uniform vec3 sunvec, sunvecView;
uniform vec3 moonvec, moonvecView;

uniform vec4 daytime;

uniform mat4 gbufferModelView, gbufferModelViewInverse;
uniform mat4 gbufferProjection, gbufferProjectionInverse;
uniform mat4 shadowModelView, shadowModelViewInverse;
uniform mat4 shadowProjection, shadowProjectionInverse;


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

#include "/lib/util/transforms.glsl"

#include "/lib/atmos/phase.glsl"
#include "/lib/atmos/air/atmosphere.glsl"
#include "/lib/atmos/project.glsl"

/* ------ ssrt prepass ------ */

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

#include "/lib/light/diffuse.glsl"

#include "/lib/light/warp.glsl"

#define SOLIDPASS
#define SHADOW_PREPASS

#include "/lib/light/shadow.glsl"

shadowData getShadowFast(bool diffLit, vec3 scenePos) {
    const float bias    = 0.08*(2048.0/shadowMapResolution);

    shadowData data     = shadowData(1.0, vec3(1.0), vec3(0.0));

    if (diffLit) {     
        float warp      = 1.0;
        bool clipped    = false;
        vec3 pos        = getShadowmapPos(scenePos, bias, warp, clipped);

        if (clipped) return data;
        float s0        = textureShadowPCF(shadowtex0, pos);
        float s1        = textureShadowPCF(shadowtex1, pos);

        bool translucent = distance(s0, s1)>0.1;

        data.shadow   = s1;

        if (translucent) {
            float s0depth = texture(shadowtex0, pos.xy).x;
            float dist  = distance(s0depth, pos.z) * 2.0 * 256.0 * rcp(0.2);
            data.color  = getShadowcol(shadowcolor0, pos.xy, dist);
        }
    }

    return data;
}

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

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

    vec3 viewPos    = screenToViewSpace(vec3(coord, sceneDepth));
    vec3 viewDir    = normalize(viewPos);
    vec3 scenePos   = viewToSceneSpace(viewPos);
    vec3 worldDir   = normalize(scenePos);

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

    sceneData       = stex(colortex1);
    bool rain       = decodeMatID16(stex(colortex2).x) == 3;
    sceneData.w     = bitfieldInsert(sceneData.w, uint(float(rain) * 255.0), 24, 8);

    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);

        float diff      = diffuseLambert(sceneNormal, lightvec);

        shadowData shadow = getShadowFast(diff>0.0, scenePos); 

        float diffLit       = min(diff, shadow.shadow);

        vec4 directLight    = saturate(vec4(diffLit, shadow.color));
        indirectData.xy     = vec2(encode2x8(directLight.xy), encode2x8(directLight.zw));

        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      = encode2x8(saturate(vec2(indirectData.z, matLAB.emission)));
    }
    
    if(!(coord.y >= exp2(-SKY_RENDER_LOD) || coord.x >= exp2(-SKY_RENDER_LOD))) {
        vec3 sceneDir   = unprojectSky(coord);
            skyboxData  = atmosphericScattering(sceneDir, mat2x3(sunvec, moonvec), airIlluminance, airIllumMod);
    }

    #ifdef airTransmittanceHQ
        vec2 transmittanceCoord = coord-vec2(0.0, exp2(-SKY_RENDER_LOD) + pixelSize.y);

        if(!(transmittanceCoord.y >= exp2(-SKY_RENDER_LOD) || transmittanceCoord.x >= exp2(-SKY_RENDER_LOD)) && (transmittanceCoord.y>=0.0)) {
            vec3 sceneDir   = unprojectSky(transmittanceCoord);
            skyboxData  = getAirTransmittance(vec3(0.0, planetRad * mix(0.9997, 1.0, saturate(sqrt(max0(sunvec.y * tau)))) + eyeAltitude, 0.0), sceneDir);
        }
    #endif

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