#version 430 core

uniform mat4 ModelViewProjectionMatrix;
uniform mat4 ModelViewMatrix;
uniform mat4 NormalMatrix;

uniform float time;

#define WAVECOUNT 4
uniform vec4 waveParams[WAVECOUNT]; // speed, amplitude, wavelength,steepness
uniform vec2 waveDirs[WAVECOUNT]; 

layout(location = 0) in vec3 POSITION;
// layout(location = 1) in vec3 NORMAL;
layout(location = 4) in vec2 TEXCOORD;

out vec3 normal;
out vec3 ec_pos;
out vec2 uv;
out vec4 extinction;
out vec3 inscatter;

#include <shading_model/atmosphere_include.frag>

void main()
{
	vec3 wavePos = POSITION;
	vec3 waveNormal = vec3(0.0);
	for(int i=0; i < WAVECOUNT; i++)
	{
		vec2 dir = waveDirs[i];
		float speed = waveParams[i].x;
		float amplitude = waveParams[i].y;
		float wavelength = waveParams[i].z;
		float steepness = waveParams[i].w;
		float freq = sqrt(9.81*2.0*3.1415926/wavelength);
		float phase = speed * freq;
		float alpha = freq * dot(dir, uv_view) + phase * time;

		wavePos.x += dir.x * steepness * amplitude * cos(alpha);
		wavePos.y += amplitude * sin(alpha);
		wavePos.z += dir.y * steepness * amplitude * cos(alpha);

		waveNormal.x += dir.x * wavelength * amplitude * cos(alpha);
		waveNormal.y += steepness * wavelength * amplitude * sin(alpha);
		waveNormal.z += dir.y * wavelength * amplitude * cos(alpha);
	}
	waveNormal.x = -waveNormal.x;
	waveNormal.y = 1.0 - waveNormal.y;
	waveNormal.z = -waveNormal.z;

	calculateGroundAtmosphereDualSided(wavePos, waveNormal, extinction, inscatter);

	uv = TEXCOORD;
	ec_pos = vec3(ModelViewMatrix * vec4(wavePos,1.0));
	normal = NormalMatrix * waveNormal;
	gl_Position = ModelViewProjection * vec4(wavePos,1.0);
}
