#version 120

uniform float time;

attribute vec4 position;

varying float fade_factor;
varying vec2 texcoord;


mat4 view_frustum(float angle_of_view,
                  float aspect_ratio,
                  float z_near,
                  float z_far)
{
  return mat4(vec4(1.0/tan(angle_of_view),           0.0, 0.0, 0.0),
              vec4(0.0, aspect_ratio/tan(angle_of_view),  0.0, 0.0),
              vec4(0.0, 0.0,    (z_far+z_near)/(z_far-z_near), 1.0),
              vec4(0.0, 0.0, -2.0*z_far*z_near/(z_far-z_near), 0.0)
              );
}

mat4 scale(float x, float y, float z)
{
  return mat4(
              vec4(x,   0.0, 0.0, 0.0),
              vec4(0.0, y,   0.0, 0.0),
              vec4(0.0, 0.0, z,   0.0),
              vec4(0.0, 0.0, 0.0, 1.0)
              );
}

mat4 translate(float x, float y, float z)
{
  return mat4(vec4(1.0, 0.0, 0.0, 0.0),
              vec4(0.0, 1.0, 0.0, 0.0),
              vec4(0.0, 0.0, 1.0, 0.0),
              vec4(x,   y,   z,   1.0)
              );
}

mat4 rotate_x(float theta)
{
  return mat4(vec4(1.0,         0.0,         0.0, 0.0),
              vec4(0.0,  cos(time),  sin(time), 0.0),
              vec4(0.0, -sin(time),  cos(time), 0.0),
              vec4(0.0,         0.0,         0.0, 1.0)
              );
}

void main()
{

  gl_Position = view_frustum(radians(45.0), 4.0/3.0, 0.5, 5.0)
        * translate(cos(time), 0.0, 3.0+sin(time))
        * rotate_x(time)
        * scale(4.0/3.0, 1.0, 1.0)
        * position;

  vec2 tex = position.xy * vec2(0.5) + vec2(0.5);

  texcoord = vec2(tex.x * 400 / 512,
                  (1.0 - tex.y) * 300 / 512);

  fade_factor = sin(time) * 0.5 + 0.5;
}
