#version 150

in vec3 vertex;
in vec4 color;
in vec4 texcoord;

out vec4 vertColor;
out vec4 vertTexcoord;

uniform mat4 modelView;
uniform mat4 modelViewProj;
uniform mat4 billboard;
uniform vec4 flipTCoordsAndFogDensity;
uniform vec4 fogColor;
uniform vec4 billboardColor;
uniform vec4 fade;
uniform mat4 basis;

void main()
{
	vec4 vertex4 = vec4(vertex.x, vertex.y, vertex.z, 1.0);
    vec3 eyePosition = (modelView * vertex4).xyz;
    float fogDistance = length(eyePosition);
    float fogExponent = clamp(fogDistance * flipTCoordsAndFogDensity.y, 0.0, 1.0);
    float fogFactor = clamp(exp(-abs(fogExponent)), 0.0, 1.0);
    vec4 preFadedColor;

    if (billboardColor.w > 0.0)
    {
        preFadedColor.xyz = mix(fogColor.xyz, billboardColor.xyz, fogFactor);
        preFadedColor.w = billboardColor.w;
    }
    else
    {
        preFadedColor = mix(fogColor, color, fogFactor);
    }
		
	float voxelFade = 1.0;
	if (fade.z > 0.0) {
		if (texcoord.w > 0.0) {
			voxelFade = abs(texcoord.w) * (fade.w - fade.z);
		} else if (texcoord.w < 0.0) {
			voxelFade = 1.0 - abs(texcoord.w) * (fade.w - fade.z);	
		}
		voxelFade = clamp(voxelFade, 0.0, 1.0);
	}

    vertColor = mix(vec4(0.0, 0.0, 0.0, 0.0), preFadedColor, fade.xxxx * voxelFade * (1.0 - fogExponent * fogExponent));

    vec3 texCoord3 = texcoord.xyz;

    vec4 vertPos = vec4(abs(texCoord3.x) * sign(texCoord3.y), abs(texCoord3.x) * sign(texCoord3.z), 0.0, 1.0);

    vec4 rotatedPos;

    float angle = abs(texCoord3.z) + abs(texCoord3.y) * sign(texCoord3.x) * fade.w;
	angle = mod(angle, 3.14159265f * 2.0f);
    float cosLength = cos(angle);
    float sinLength = sin(angle);

    rotatedPos.x = (cosLength * vertPos.x + -sinLength * vertPos.y);
    rotatedPos.y = (sinLength * vertPos.x + cosLength * vertPos.y);
    rotatedPos.z = 0.0;
    rotatedPos.w = 1.0;

	vec4 vert = vertex4 * basis;
    mat4 xlate = mat4(1.0, 0.0, 0.0, 0.0,
                      0.0, 1.0, 0.0, 0.0,
                      0.0, 0.0, 1.0, 0.0,
                      vert.x, vert.y, vert.z, 1.0);

    mat4 xlatebb = (xlate * billboard);
    mat4 mvb = (modelViewProj * xlatebb);
    gl_Position = (mvb * rotatedPos);

    vertTexcoord = vec4(0.5 * sign(texCoord3.y) + 0.5,
                          0.5 * sign(texCoord3.z) * flipTCoordsAndFogDensity.x + 0.5,
                          0.0, 0.0);

}
