
#version 130

uniform sampler2D texture;
uniform sampler2D shineMap;
uniform vec2 textureSize;
uniform vec2 mapScroll;
uniform vec2 screenSize;
uniform vec2 screenScale;
uniform vec2 screenOffset;
uniform vec2 worldSize;
uniform bool grimeEnabled;
uniform bool shineEnabled;
uniform float time;

#include "Shared/Perlin.frag"


void main()
{
    vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);

    float mapScrollMultiplier = 1.0;

    // invert screen offset x
	vec2 invertedScreenOffset = screenOffset;
	invertedScreenOffset.x = -invertedScreenOffset.x;

    // grime
    if(grimeEnabled)
    {
        vec2 screenPos = invertedScreenOffset + gl_FragCoord.xy;
        screenPos.y = screenSize.y - screenPos.y;

        //vec2 uv = (((screenPos + (mapScroll * mapScrollMultiplier)) / screenScale)) / 9000;
        vec2 uv = (((screenPos + (mapScroll * mapScrollMultiplier)) / screenScale)) / 900;
        
        uint seed = 4232312u;
        float sample = perlin2D(uv, 20, 5, seed);

        vec4 noisePixel = vec4(sample, sample, sample, 1);

        pixel = mix(pixel, noisePixel, 0.2); //0.15); //0.12);
    }

	// shine
	if(shineEnabled && pixel.a > 0.5)
	{
        vec2 screenPos = invertedScreenOffset + gl_FragCoord.xy;
        screenPos.y = screenSize.y - screenPos.y;			

        vec2 uvPerlin = screenPos + (mapScroll * mapScrollMultiplier * 0.9);//(gl_TexCoord[0].xy * textureSize);

        //uvPerlin *= 0.00001;
        //uvPerlin += (time * 0.00005);
        uvPerlin *= 0.0001;
        uvPerlin += (time * 0.005);

        uint seed = 12382u;
        float sample = perlin2D(uvPerlin, 20, 1, seed);

        //if(sample > 0.5)
        {
            vec4 noisePixel = vec4(sample, sample, sample, 1);

            vec4 shineMapPixel = texture2D(shineMap, gl_TexCoord[0].xy);
            float shine = shineMapPixel.r;
            vec4 bright = vec4(shine, shine, shine, 1.0);
            if(bright.a > 0 && bright.r > 0 && sample > 0)
            {
                //bright *= 1.2;
                //bright *= 0.6;
                bright *= 0.5;
                float a = pixel.a;

                pixel = pixel + (noisePixel * bright);

                pixel.a = a;
            }
        }
    }
	    
    gl_FragColor = pixel;
    
}
