#define surfaceNormal vec3(0, 1, 0)
uniform sampler2D lookup;
uniform float waterLevel;
uniform bool refractionPass;

void main() {

	vec4 vertex = vec4(position, 1.0);

	if (refractionPass) {
		vertex = modelMatrix * vertex;
		vec3 camera = cameraPosition;
		
		vec3 view = camera - vertex.xyz;
		vec3 viewDir = normalize(view);
		float cosL = dot(viewDir, surfaceNormal);
		float yRatio = (camera.y - waterLevel) / view.y;
		
		vertex.y -= waterLevel;
		
		// Modify lookup if camera is underwater
		float offsetRatio = 1.0;
		if (camera.y < level) 
			offsetRatio = 1.0 / texture(lookup, vec2(abs(cosL), 1.0 - yRatio)).r;
		else
			offsetRatio = texture(lookup, vec2(cosL, yRatio)).r;

		vertex.y *= offsetRatio;
		vertex.y += waterLevel;
		
		gl_Position = projectionMatrix * viewMatrix * vertex;
	}
	
	else 
		gl_Position = projectionMatrix * modelViewMatrix * vertex;
}