/* In this demo we render underwater geometry in a separate pass. We tell our shader 
   when we're at the refraction pass and perform vertex displacement. Note that the 
   water's clipping plane should be slighty lower than the actual water level. */

#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;
		
		// Calculate lookup coordinates
		vec3 view = camera - vertex.xyz;
		vec3 viewDir = normalize(view);
		float cosL = dot(viewDir, surfaceNormal);
		float yRatio = (camera.y - waterLevel) / view.y;
		
		// Apply Y offset relative to water plane
		vertex.y -= waterLevel;
		vertex.y *= texture(lookup, vec2(cosL, yRatio)).r;
		vertex.y += waterLevel;
		
		gl_Position = projectionMatrix * viewMatrix * vertex;
	}
	
	else 
		gl_Position = projectionMatrix * modelViewMatrix * vertex;
}