#version 330 core

layout(location = 0) in vec4 vertex;
out vec3 rdb;
flat out vec3 roo;

uniform vec2 iResolution;
uniform float iTime;
uniform mat4 glModelViewMatrix;
uniform vec2 cameraPan;
uniform float cameraDistance;
uniform float iAnimT;

const float focalLength = 3.0;

void main() {
	gl_Position = vertex; //gl_Vertex;

    float introZoom = 100.0*max(0.0,iAnimT-iTime);
    vec3 up = vec3(0.0,1.0,0.0);

    float a = 3.0*3.1415926*max(0.0, iAnimT-iTime);
    vec4 col = vec4(cos(a),0.0,sin(a),0.0);
    mat4 m = mat4(col.x,0.0,col.z,0.0,0.0,1.0,0.0,0.0,-col.z,0.0,col.x,0.0,0.0,0.0,0.0,1.0)*glModelViewMatrix;
    mat4 introM = mat4(col.x,0.0,col.z,0.0,0.0,1.0,0.0,0.0,-col.z,0.0,col.x,0.0,0.0,0.0,0.0,1.0);

    vec3 ta = (introM * vec4(cameraPan.x, 0.0, cameraPan.y, 1.0)).xyz;
    vec3 viewDir = normalize((m * vec4(0.0, 0.0, 1.0, 0.0)).xyz);
    roo = ta - (cameraDistance + introZoom) * viewDir;
    up = normalize((m*vec4(up, 1.0)).xyz);

    vec3 cw = normalize(ta - roo);
    vec3 cu = normalize(cross(up,cw));
    vec3 cv = cross(cw, cu);

    vec2 ratio = vec2(iResolution.x/iResolution.y, 1.0);
    vec2 q0 = (vertex.xy + vec2(0.5,0.5)/iResolution) * ratio;
	// Unnormalized, like the stereo shader beside it: a varying must carry the
	// direction, not the unit vector, or interpolation bends the rays. Here the
	// four corners happen to have equal length so it made no difference — which
	// is exactly why the same line in stereo.glsl went unnoticed. The fragment
	// shader normalizes.
	rdb = q0.x*cu + q0.y*cv + focalLength*cw;
}
