#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "glut.h"

/* this is an expansion of the first.c example. One additional callback
function is registered: glutMotionFunc (premikanje_miske);
It traps the mouse movement and enables user to dynamically
rotate model about x and y axes
*/

typedef struct {
  float x;
  float y;
  float z;
} POINT;


POINT vertices[8]= {    {0.0, 0.0, 0.0},
			{1.0, 0.0, 0.0},
			{1.0, 1.0, 0.0},
			{0.0, 1.0, 0.0},
			{0.0, 0.0, 1.0},
			{1.0, 0.0, 1.0},
			{1.0, 1.0, 1.0},
			{0.0, 1.0, 1.0}};

int quads[3][4] = {{0, 3, 2, 1}, {4, 5, 6, 7},
			{0, 1, 5, 4}};

POINT normals[3] = {{0.0, 0.0, -1.0}, {0.0, 0.0, 1.0}, {0.0, -1.0, 0.0}};

float fi_x = 0.0, fi_y=0.0;
int old_x = 0, old_y=0;

void risi()
{
  int i,j;

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();
  glScalef(0.5, 0.5, 0.5);
  glRotatef(fi_y, 1.0, 0.0, 0.0);
  glRotatef(fi_x, 0.0, 1.0, 0.0);

  for (i=0;i<3;i++) {
    if (i==0) glColor3f(1.0, 0.0, 0.0);
    if (i==1) glColor3f(0.0, 1.0, 0.0);
    if (i==2) glColor3f(0.0, 0.0, 1.0);
    glBegin(GL_QUADS);
      for(j=0; j<4; j++) {
        glNormal3f(normals[i].x, normals[i].y, normals[i].z);
        glVertex3f(vertices[quads[i][j]].x,
		vertices[quads[i][j]].y,
		vertices[quads[i][j]].z);
      }
    glEnd();
  }
  glFlush();
}

void premikanje_miske(int x, int y)
{
  if (old_x < x)  fi_x += 1.0;
  if (old_x > x)  fi_x -= 1.0;
  if (old_y > y)  fi_y += 1.0;
  if (old_y < y)  fi_y -= 1.0;

  glutPostRedisplay();
  old_x = x;
  old_y = y;
}


int main(int argn, char **argc)
{
  glutInit(&argn, argc);
  glutInitWindowSize(500, 500);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_DEPTH | GLUT_RGB);
  glutCreateWindow("my first program");
  glEnable(GL_LIGHTING);
  glEnable(GL_COLOR_MATERIAL);
  glEnable(GL_LIGHT0);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_NORMALIZE);
  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
  glutDisplayFunc (risi);
  glutMotionFunc (premikanje_miske);
  glutMainLoop();
  return 0;
}
