#version 330 core

layout(location=0) in vec3 position;

uniform mat4 model;
uniform mat4 view;
uniform mat4 proj;

uniform sampler2D wave1;
uniform sampler2D wave2;
uniform sampler2D reflectionTex;

out vec3 fPosition;
out vec4 fLocalPosition;
out vec2 fWave1TexLookup;
out vec2 fWave2TexLookup;
out vec3 fCamPosition;

out float fWave1Ratio;
out float fWave2Ratio;

out vec4 fRefractionMapLookup;

void main(void) {
	float waveAmplitude = 17;
	float waterHeightLevel = 0;

	float wave1TexScale = 0.1f/256;
	float wave2TexScale = 0.3f/256;

	fWave1Ratio = 0.6f;
	fWave2Ratio = 0.4f;

	mat4 viewModel = inverse(view);
 	vec3 cam = viewModel[3].xyz;
	fCamPosition = cam;

	//calcualte x, z
	vec4 pos = vec4(position, 1.0f);
	pos.xz = pos.xz * pow(pos.y, 4) * 0.000000065483;

	//waveAmplitude = min(length(abs((model * pos).xyz) * 0.01), 4);

	//Calculate y first wave
	vec2  wave1TexLookup = (pos.xz + cam.xz) * wave1TexScale;
	vec4 wave1TexComponents = texture(wave1, wave1TexLookup);
	float wave1Height = wave1TexComponents.a - 0.5f;

	//Calculate y second wave
	vec2  wave2TexLookup = (pos.xz + cam.xz) * wave2TexScale;
	vec4 wave2TexComponents = texture(wave2, wave2TexLookup);
	float wave2Height = wave2TexComponents.a -0.5f;

	float finalWaveHeight = fWave1Ratio * wave1Height + fWave2Ratio  * wave2Height;

	//pos.y = waterHeightLevel;
	pos.y = waterHeightLevel + finalWaveHeight * waveAmplitude;
	gl_Position = proj * view * model * pos;

	fWave1TexLookup = wave1TexLookup.xy;
	fWave2TexLookup = wave2TexLookup.xy;

	fPosition = (model * pos).xyz;
	fRefractionMapLookup = proj * view * model * vec4(pos.x, pos.y, pos.z, 1.0f);
	fLocalPosition = pos;
}
