/* Animations sur des images                    */
/*                                              */
/* Auteur: Nicolas JANEY                        */
/* nicolas.janey@univ-fcomte.fr                 */
/* Avril 2014                                   */

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

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

#include "PNG/ChargePngFile.h"

/* Variables et constantes globales             */

static const float blanc[] = { 1.0F,1.0F,1.0F,1.0F };
static const float blancFort[] = { 10.0F,10.0F,10.0F,10.0F };
static const float gris[]  = { 0.7F,0.7F,0.7F,1.0F };
static const float noir[]  = { 0.0F,0.0F,0.0F,1.0F };
static int aff = 1;
static float max = 10.0F;
static float cutOff = 1.0F;
static float inc = 0.5F;

/* Fonction executee lorsqu'aucun evenement     */
/* n'est en file d'attente                      */

static void idle(void) {
  if ( cutOff >= max ) {
    inc += 0.25F;
    max = max+15.0F/inc;
    inc = -inc; }
  if ( cutOff <= 0.0F ) {
    inc = -inc; }
  cutOff += inc;
  if ( cutOff <= 0.0F ) {
    cutOff = 0.0F; }
  if ( cutOff >= 90.0F ) {
    cutOff = 180.0F;
    glutIdleFunc(NULL); }
  glutPostRedisplay();
}

/* Fonction executee lors de la frappe          */
/* d'une touche du clavier                      */

static void keyboard(unsigned char key,int x,int y) {
  switch ( key ) {
    case 'a' :
      cutOff = 1.0F;
      inc = 0.5F;
      max = 10.0F;
      break;
    case 0x20 :
      aff = (aff+1)%2;
      glutPostRedisplay(); 
      break;
    case 0x0D :
      { static int anim = 0;
        anim = !anim;
        glutIdleFunc(( anim ) ? idle : NULL); }
      glutPostRedisplay(); 
      break;
    case 0x1B :
      exit(0); 
      break; }
}

/* Fonction executee lors de l'appui            */
/* d'une touche de curseur ou d'une touche      */
/* page up ou page down                         */

static void special(int key,int x,int y) {
  switch(key) {
    case GLUT_KEY_UP :
      glutPostRedisplay();
      break;
    case GLUT_KEY_DOWN :
      glutPostRedisplay();
      break;
    case GLUT_KEY_LEFT :
      glutPostRedisplay();
      break;
    case GLUT_KEY_RIGHT :
      glutPostRedisplay();
      break;
    case GLUT_KEY_PAGE_UP :
      glutPostRedisplay();
      break;
    case GLUT_KEY_PAGE_DOWN :
      glutPostRedisplay();
      break; }
}

/* Fonction d'initialisation des parametres     */
/* OpenGL ne changeant pas au cours de la vie   */
/* du programme                                 */
/* Contient en particulier l'initialisation     */
/* d'une texture 2D                             */

static void init(void) {
  const GLfloat mat_shininess[] = { 50.0 };
  glMaterialfv(GL_FRONT,GL_DIFFUSE,blanc);
  glMaterialfv(GL_FRONT,GL_SPECULAR,blanc);
  glMaterialfv(GL_FRONT,GL_AMBIENT,noir);
  glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);
  glLightfv(GL_LIGHT0,GL_DIFFUSE,blancFort);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
  glDepthFunc(GL_LESS);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_NORMALIZE);
  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,1);
  glEnable(GL_TEXTURE_2D);
  glPixelStorei(GL_UNPACK_ALIGNMENT,1); 
  { int rx;
    int ry;
    unsigned char *img = chargeImagePng("IG.png",&rx,&ry);
    if ( img ) {
      glTexImage2D(GL_TEXTURE_2D,0,3,rx,ry,0,GL_RGB,GL_UNSIGNED_BYTE,img);
      free(img); } }
  glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); 
  glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); 
  glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); 
}

/* Modelisation par facettes                    */
/* d'un cylindre texturable                     */

#ifndef M_PI
#define M_PI 3.14159
#endif

static void diapo(void) {
  GLboolean nm = glIsEnabled(GL_NORMALIZE);
  if ( !nm )
    glEnable(GL_NORMALIZE);
  float normale[4];
  glGetFloatv(GL_CURRENT_NORMAL,normale);
  glPushMatrix();
  glNormal3f(0.0F,0.0F,1.0F);
  int xCut = 683;
  int yCut = 384;
  for ( int i = 0 ; i < xCut ; i++ ) {
    float xi = -683.0F+(1366.0F*i)/xCut;
    float xf = -683.0F+(1366.0F*(i+1))/xCut;
    float si =(float) i/xCut;
    float sf =(float) (i+1)/xCut;
    glBegin(GL_QUAD_STRIP);
    for ( int j = 0 ; j <= yCut ; j++ ) {
      float y = -384.0F+(768.0F*j)/yCut;
      float t =(float) j/yCut;
      glTexCoord2f(si,t);
      glVertex3f(xi,y,0.0F);
      glTexCoord2f(sf,t);
      glVertex3f(xf,y,0.0F); }
    glEnd(); }
  glPopMatrix();
  glNormal3f(normale[0],normale[1],normale[2]);
  if ( !nm )
    glDisable(GL_NORMALIZE);
}

/* Scene dessinee                               */

static void scene(void) {
  glPushMatrix();
  diapo();
  glPopMatrix();
}

/* Fonction executee lors d'un rafraichissement */
/* de la fenetre de dessin                      */

static void display(void) {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  const GLfloat light0_position[] = { -500.0,300.0,300.0,1.0 };
  glLightfv(GL_LIGHT0,GL_POSITION,light0_position);
  const GLfloat light0_direction[] = { 0.2,-0.2,-1.0,0.0 };
  glLightfv(GL_LIGHT0,GL_SPOT_DIRECTION,light0_direction);
  if ( cutOff <= 90.0F )
    glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,cutOff);
    else
    glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,180.0F);
  glPolygonMode(GL_FRONT_AND_BACK,(aff) ? GL_FILL : GL_LINE);
  glPushMatrix();
  scene();
  glPopMatrix();
  glFlush();
  glutSwapBuffers();
  int error = glGetError();
  if ( error != GL_NO_ERROR )
    printf("Erreur OpenGL: %d\n",error);
}

/* Fonction executee lors d'un changement       */
/* de la taille de la fenetre OpenGL            */
/* -> Ajustement de la camera de visualisation  */

static void reshape(int x,int y) {
  glViewport(0,0,x,y); 
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-683.0,683.0,-384.0,384.0,-500.0,500.0);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

/* Fonction principale                          */

int main(int argc,char **argv) {
  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
  glutInitWindowSize(300,300); 
  glutInitWindowPosition(50,50); 
  glutCreateWindow("Une animation sur des images"); 
  init();
  glutKeyboardFunc(keyboard);
  glutSpecialFunc(special);
  glutReshapeFunc(reshape);
  glutDisplayFunc(display);
  glutFullScreen();
  glutIdleFunc(idle);
  glutMainLoop();
  return(0);
}
