#include<GL/glut.h>
#include<GL/glu.h>
#include<GL/gl.h>
#include <stdlib.h>

#include<string.h>
#include<stdio.h>

#define POLSO	1
#define DITO1	2
#define DITO2	3

int shoulder = 0, elbow1 = 0, elbow2 = 0;
int roty= 0;

void init(void) 
{
   glClearColor (0.0, 0.0, 0.0, 0.0);
   glEnable(GL_DEPTH_TEST);	// Hidden surface removal
   glFrontFace(GL_CCW);		// Counter clock-wise polygons face out
   glEnable(GL_CULL_FACE);	// Do not calculate insides
}

void display(void)
{
   glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   glBegin(GL_LINES);
   glColor3f(1.0,0.0,0.0);
   glVertex3f(0.0,0.0,0.0);
   glVertex3f(1.0,0.0,0.0);
   glColor3f(0.0,1.0,0.0);
   glVertex3f(0.0,0.0,0.0);
   glVertex3f(0.0,1.0,0.0);
   glColor3f(0.0,0.0,1.0);
   glVertex3f(0.0,0.0,0.0);
   glVertex3f(0.0,0.0,1.0);
   glEnd();
   
   glColor3f(1.0,1.0,1.0);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glTranslatef (0.0, 0.0, -8.0);
   glPushMatrix();

   glInitNames();
   glPushName(0);

   glRotatef((GLfloat) roty, 0.0, 1.0, 0.0);
   glRotatef ((GLfloat) shoulder, 0.0, 0.0, 1.0);
   glTranslatef (1.0, 0.0, 0.0);

   glPushMatrix();
   glScalef (2.0, 0.4, 4.0);
   glLoadName(POLSO);
   // il cubo non e' in wireframe perche' in wireframe il picking seleziona le primitive solo se
   // si clicca sul bordo!
   glutSolidCube (1.0);
   glPopMatrix();

   glPushMatrix();
   glTranslatef (1.0, 0.0, -1.0); // traslazione nella posizione finale
   glRotatef ((GLfloat) elbow1, 0.0, 0.0, 1.0); // rotazione rispetto al polso
   glTranslatef (1.0, 0.0, 0.0); // traslazione nell'origine

   glPushMatrix();
   glScalef (2.0, 0.4, 1.0);
   glPushName(DITO1);
   glutSolidCube (1.0);
   glPopName();
   glPopMatrix();

   glPopMatrix();

   glTranslatef (1.0, 0.0, 1.0);
   glRotatef ((GLfloat) elbow2, 0.0, 0.0, 1.0);
   glTranslatef (1.0, 0.0, 0.0);

   glPushMatrix();
   glScalef (2.0, 0.4, 1.0);
   glPushName(DITO2);
   glutSolidCube (1.0);
   glPopName();
   glPopMatrix();

   glPopMatrix();
   glutSwapBuffers();
}

void ProcessHand(GLuint *pSelectBuff)
	{
	int id,count;
	char cMessage[64];
	strcpy(cMessage,"Error, no selection detected");

	for (int i=0;i<9;i++)
          printf("pSelectBuff[%d]=%u\n",i,pSelectBuff[i]);

	count = pSelectBuff[0];

	id = pSelectBuff[3];

	switch(id)
		{
		case POLSO:
			strcpy(cMessage,"Selezionato il polso.");
                        
                        // azzera gli angoli di rotazione del polso
			roty=0;
			shoulder=0;
			glutPostRedisplay();

                        printf("count=%d\n",pSelectBuff[0]);
			if(count == 2)
				if(pSelectBuff[4] == DITO1)
					strcat(cMessage," - dito #1.");
				else
					strcat(cMessage," - dito #2.");

			break;
		}

	glutSetWindowTitle(cMessage);
	}

#define BUFFER_LENGTH 64
void ProcessSelection(int xPos, int yPos)
	{
	GLfloat fAspect;	// Screen aspect ratio

	// Space for selection buffer
	GLuint selectBuff[BUFFER_LENGTH];

	// Hit counter and viewport storeage
	GLint hits, viewport[4];

	// Setup selection buffer
	glSelectBuffer(BUFFER_LENGTH, selectBuff);
	
	// Get the viewport
	glGetIntegerv(GL_VIEWPORT, viewport);

	// Switch to projection and save the matrix
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();

	// Change render mode
	glRenderMode(GL_SELECT);


	glLoadIdentity();
	gluPickMatrix(xPos, viewport[3] - yPos, 4,4, viewport);

	
	fAspect = (float)viewport[2] / (float)viewport[3];
	gluPerspective(45.0f, fAspect, 1.0, 425.0);

	// Chiama la funzione di rendering in modalita' selezione (la scena non viene disegnata).
        // display() deve contenere la chiamata a glMatrixMode(GL_MODELVIEW); all'inizio
        // perche' in questo punto in cui viene chiamata siamo in modo GL_PROJECTION.
        display();

	// Restore the projection matrix
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	// Go back to modelview for normal rendering
	glMatrixMode(GL_MODELVIEW);

	// Collect the hits
	hits = glRenderMode(GL_RENDER);

	printf("# hits=%d\n",hits);
	if(hits >= 1)
		ProcessHand(selectBuff);
	else
		glutSetWindowTitle("You clicked empty space!");
	}

void MouseCallback(int button, int state, int x, int y)
	{
	if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
		ProcessSelection(x, y);
}

void reshape (int w, int h)
{  
   GLfloat fAspect;
   glViewport (0, 0, (GLsizei) w, (GLsizei) h); 
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
   fAspect = (GLfloat)w/(GLfloat)h;
   gluPerspective(45.0f, fAspect, 1.0, 425.0);
}

void keyboard (unsigned char key, int x, int y)
{
   switch (key) {
      case 's':
         shoulder = (shoulder + 5) % 360;
         glutPostRedisplay();
         break;
      case 'S':
         shoulder = (shoulder - 5) % 360;
         glutPostRedisplay();
         break;
      case 'e':
         elbow1 = (elbow1 + 5) % 360;
         glutPostRedisplay();
         break;
      case 'E':
         elbow1 = (elbow1 - 5) % 360;
         glutPostRedisplay();
         break;
      case 'd':
         elbow2 = (elbow2 + 5) % 360;
         glutPostRedisplay();
         break;
      case 'D':
         elbow2 = (elbow2 - 5) % 360;
         glutPostRedisplay();
         break;
     case 'w':
         roty = (roty + 5) % 360 ;
         glutPostRedisplay();
         break;
      case 'W':
         roty = (roty - 5) % 360;
         glutPostRedisplay();
         break;
      case 27:
         exit(0);
         break;
      default:
         break;
   }
}

int main(int argc, char** argv)
{
   glutInit(&argc, argv);
   glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
   glutInitWindowSize (500, 500); 
   glutInitWindowPosition (100, 100);
   glutCreateWindow (argv[0]);
   init ();
   glutDisplayFunc(display); 
   glutReshapeFunc(reshape);
   glutKeyboardFunc(keyboard);
   glutMouseFunc(MouseCallback);
   glutMainLoop();
   return 0;
}
