/* Placage de 6 textures sur les faces          */
/* d'un cube                                    */
/*                                              */
/* Auteur: Nicolas JANEY                        */
/* nicolas.janey@univ-fcomte.fr                 */
/* Fevrier 2019                                 */

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

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

/* Variables et constantes globales             */

static double px = 0.0;
static double py = 0.0;
static double pz = 10.0;

static const float blanc[]       = { 1.2F,1.2F,1.2F,1.0F };

static int affichage = 1;
static int texture = 1;
static int animation = 0;

static float rx = 0.0F;
static float ry = 0.0F;
static float rz = 0.0F;

/* Fonction d'initialisation des parametres     */
/* OpenGL ne changeant pas au cours de la vie   */
/* du programme                                 */

static void init(void) {
  glClearColor(0.25F,0.25F,0.25F,1.0F);
  glLightfv(GL_LIGHT0,GL_DIFFUSE,blanc);
  glEnable(GL_LIGHTING);
  glEnable(GL_LIGHT0);
  glDepthFunc(GL_LESS);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_NORMALIZE);
  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE,1);
}

//////////////////////////////////////////////////

#include "PNG/ChargePngFile.h"

/* Fonction de chargement d'une texture         */
/* a partir d'un fichier image au format png    */
/* filename : le nom du fichier                 */
/* @retour : le handle de la texture            */

unsigned int chargementTexturePNG(char *filename) {
  unsigned int textureID = 0;
  glGenTextures(1,&textureID);
  int rx;
  int ry;
  unsigned char *img = chargeImagePng(filename,&rx,&ry);
  if ( img && textureID ) {
    glBindTexture(GL_TEXTURE_2D,textureID);
    glPixelStorei(GL_UNPACK_ALIGNMENT,1);
    glTexImage2D(GL_TEXTURE_2D,0,3,rx,ry,0,GL_RGB,GL_UNSIGNED_BYTE,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);
    free(img); }
    else {
    if ( img ) {
      free(img); }
    if ( textureID ) {
      glDeleteTextures(1,&textureID);
      textureID = 0; } }
  return textureID;
}

/* Modelisation geometrique d'un cube           */
/* avec placage de textures sur chacune         */
/* de ses faces                                 */
/* ct : la taille du cube                       */
/* filenames : le tableau des noms              */
/*             des 6 fichiers png a utiliser    */
/*             pour le placage de texture       */

static void mySolidCube(double ct,char **filenames) {
  float c =(float) ct/2.0F;
  unsigned int textureID;
  /* Chargement premiere texture                */
  textureID = chargementTexturePNG(filenames[0]);
  glBegin(GL_QUADS);
  glNormal3f(0.0F,0.0F,-1.0F);
  glTexCoord2f(0.0F,0.0F);
  glVertex3f( c, c,-c);
  glTexCoord2f(0.0F,1.0F);
  glVertex3f( c,-c,-c);
  glTexCoord2f(1.0F,1.0F);
  glVertex3f(-c,-c,-c);
  glTexCoord2f(1.0F,0.0F);
  glVertex3f(-c, c,-c);
  glEnd();
  /* Dechargement premiere texture              */
  glDeleteTextures(1,&textureID);
  /* Chargement deuxieme texture                */
  textureID = chargementTexturePNG(filenames[1]);
  glBegin(GL_QUADS);
  glNormal3f(0.0F,0.0F,1.0F);
  glTexCoord2f(0.0F,0.0F);
  glVertex3f(-c,-c, c);
  glTexCoord2f(1.0F,0.0F);
  glVertex3f( c,-c, c);
  glTexCoord2f(1.0F,1.0F);
  glVertex3f( c, c, c);
  glTexCoord2f(0.0F,1.0F);
  glVertex3f(-c, c, c);
  glEnd();
  /* Dechargement deuxieme texture              */
  glDeleteTextures(1,&textureID);
  /* Chargement troisieme texture               */
  textureID = chargementTexturePNG(filenames[2]);
  glBegin(GL_QUADS);
  glNormal3f(-1.0F,0.0F,0.0F);
  glTexCoord2f(0.0F,0.0F);
  glVertex3f(-c, c,-c);
  glTexCoord2f(0.0F,1.0F);
  glVertex3f(-c,-c,-c);
  glTexCoord2f(1.0F,1.0F);
  glVertex3f(-c,-c, c);
  glTexCoord2f(1.0F,0.0F);
  glVertex3f(-c, c, c);
  glEnd();
  /* Dechargement troisieme texture             */
  glDeleteTextures(1,&textureID);
  /* Chargement quatrieme texture               */
  textureID = chargementTexturePNG(filenames[3]);
  glBegin(GL_QUADS);
  glNormal3f(1.0F,0.0F,0.0F);
  glTexCoord2f(0.0F,0.0F);
  glVertex3f( c, c, c);
  glTexCoord2f(0.0F,1.0F);
  glVertex3f( c,-c, c);
  glTexCoord2f(1.0F,1.0F);
  glVertex3f( c,-c,-c);
  glTexCoord2f(1.0F,0.0F);
  glVertex3f( c, c,-c);
  glEnd();
  /* Dechargement quatrieme texture             */
  glDeleteTextures(1,&textureID);
  /* Chargement cinquieme texture               */
  textureID = chargementTexturePNG(filenames[4]);
  glBegin(GL_QUADS);
  glNormal3f(0.0F,-1.0F,0.0F);
  glTexCoord2f(0.0F,0.0F);
  glVertex3f(-c,-c, c);
  glTexCoord2f(0.0F,1.0F);
  glVertex3f(-c,-c,-c);
  glTexCoord2f(1.0F,1.0F);
  glVertex3f( c,-c,-c);
  glTexCoord2f(1.0F,0.0F);
  glVertex3f( c,-c, c);
  glEnd();
  /* Dechargement cinquieme texture             */
  glDeleteTextures(1,&textureID);
  /* Chargement sixieme texture                 */
  textureID = chargementTexturePNG(filenames[5]);
  glBegin(GL_QUADS);
  glNormal3f(0.0F,1.0F,0.0F);
  glTexCoord2f(0.0F,0.0F);
  glVertex3f( c, c, c);
  glTexCoord2f(0.0F,1.0F);
  glVertex3f( c, c,-c);
  glTexCoord2f(1.0F,1.0F);
  glVertex3f(-c, c,-c);
  glTexCoord2f(1.0F,0.0F);
  glVertex3f(-c, c, c);
  glEnd();
  /* Dechargement sixieme texture               */
  glDeleteTextures(1,&textureID);
}

/* Scene dessinee                               */

static void scene(void) {
  glPushMatrix();
  char *filenames[6] = { "Emoji1.png","Emoji2.png","Emoji3.png",
                         "Emoji4.png","Emoji5.png","Emoji6.png" };
  mySolidCube(5.0,filenames);
  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[] = { 0.0,0.0,10.0,1.0 };
  glPolygonMode(GL_FRONT_AND_BACK,(affichage) ? GL_FILL : GL_LINE);
  if ( texture ) 
    glEnable(GL_TEXTURE_2D);
    else
    glDisable(GL_TEXTURE_2D);
  glPushMatrix();
  glLightfv(GL_LIGHT0,GL_POSITION,light0_position);
  gluLookAt(px,py,pz,0.0,0.0,0.0,0.0,1.0,0.0);
  glRotatef(rx,1.0F,0.0F,0.0F);
  glRotatef(ry,0.0F,1.0F,0.0F);
  glRotatef(rz,0.0F,0.0F,1.0F);
  scene();
  glPopMatrix();
  glFlush();
  glutSwapBuffers();
  int error = glGetError();
  if ( error != GL_NO_ERROR )
    printf("Erreur OpenGL: %d\n",error);
}

/* Desallocations                               */

static void clean(void) {
}

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

static void reshape(int tx,int ty) {
  glViewport(0,0,tx,ty); 
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  double ratio =(double) tx/ty;
  if ( ratio >= 1.0 )
    gluPerspective(50.0,ratio,0.01,200.0);
    else
    gluPerspective(50.0/ratio,ratio,0.01,200.0);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

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

static void special(int key,int x,int y) {
  switch ( key ) {
    case GLUT_KEY_UP :
      py += 0.1;
      glutPostRedisplay(); 
      break;
    case GLUT_KEY_DOWN :
      py -= 0.1;
      glutPostRedisplay(); 
      break;
    case GLUT_KEY_LEFT :
      px -= 0.1;
      glutPostRedisplay(); 
      break;
    case GLUT_KEY_RIGHT :
      px += 0.1;
      glutPostRedisplay(); 
      break;
    case GLUT_KEY_PAGE_UP :
      pz -= 0.1;
      glutPostRedisplay(); 
      break;
    case GLUT_KEY_PAGE_DOWN :
      pz += 0.1;
      glutPostRedisplay(); 
      break;
    case GLUT_KEY_F1 :
      px = 0.0;
      py = 0.0;
      pz = 10.0;
      glutPostRedisplay(); 
      break;
    case GLUT_KEY_F2 :
      rx = 0.0;
      ry = 0.0;
      rz = 10.0;
      glutPostRedisplay(); 
      break; }
}

/* Fonction executee en tache de fond           */

static void idle(void) {
  rx += 0.7F;
  ry += 0.5F;
  rz += 0.3F;
  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' :
      animation = !animation;
      glutIdleFunc(( animation ) ? idle : NULL);
      break;
    case 0x0D :
      affichage = (affichage+1)%2;
      glutPostRedisplay(); 
      break;
    case 0x20 :
      texture = (texture+1)%2;
      glutPostRedisplay(); 
      break;
    case 0x1B :
      exit(0); 
      break; }
}

/* Fonction principale                          */

int main(int argc,char **argv) {

  atexit(clean);

  glutInit(&argc,argv);
  glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
  glutInitWindowSize(480,360); 
  glutInitWindowPosition(50,50); 
  glutCreateWindow("Plaçage de textures"); 
  init();
  glutKeyboardFunc(keyboard);
  glutSpecialFunc(special);
  glutReshapeFunc(reshape);
  glutDisplayFunc(display);
  glutMainLoop();
  return(0);
}
