#include <stdlib.h>
#include <fcntl.h>
#include <math.h>
#include <unistd.h>
#include <stdio.h>
#include <GL/glut.h>
#include <GL/gl.h>

float viewRotY = 0, viewRotX = 0;

#define TOPO_ROWS 128
#define TOPO_COLS 128

typedef struct { float r,g,b; } color_t;
color_t * colors;
float * elevation;
float heightScale = 1;


void readTopoData(char * elevFile, char *colorFile);
void drawEverything(void);
void drawTopoMesh(void);
void checkGLError(char *);
void key(unsigned char k, int x, int y);
void specialkey(int k, int x, int y);



int main(int argc, char *argv[])
    {
    glutInit(&argc, argv);
    if (argc < 3)
        {
        fprintf(stderr,"Usage; %s elevation-file color-file\n",argv[0]);
        exit(1);
        }
    readTopoData(argv[1],argv[2]);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("example");
    glutDisplayFunc(drawEverything);
    glutKeyboardFunc(key);
    glutSpecialFunc(specialkey);
    glutMainLoop();
    return 0;
    }


void readTopoData(char * elevFile, char *colorFile)
    {
    int fd;
    
    elevation = (float *) malloc(TOPO_ROWS * TOPO_COLS * sizeof(float));
    colors = (color_t *) malloc(TOPO_ROWS * TOPO_COLS * sizeof(color_t));
    
    fd = open(elevFile, O_RDONLY);
    if (fd < 0)
        {
        perror(elevFile);
        exit(1);
        }
    read(fd,elevation,TOPO_ROWS * TOPO_COLS * sizeof(float));
    close(fd);
    
    fd = open(colorFile, O_RDONLY);
    if (fd < 0)
        {
        perror(colorFile);
        exit(1);
        }
    read(fd,colors,TOPO_ROWS * TOPO_COLS * sizeof(color_t));
    close(fd);
    }


void drawEverything(void)
    {
    glClearColor(0.5, 0.8, 1.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, 1.0, 1.0, 100.0);
    glMatrixMode(GL_MODELVIEW);

    glLoadIdentity();
    glTranslatef(0.0, 0.0, -15.0);
    glRotatef(viewRotX, 1.0, 0.0, 0.0);
    glRotatef(viewRotY, 0.0, 1.0, 0.0);
    
    drawTopoMesh();
    
    glutSwapBuffers();
    
    checkGLError("end-of-frame");
    }


void drawTopoMesh(void)
    {
    int i,j, index;
    float x,y,z;
    srand48(0);
    for (j = 0; j < TOPO_ROWS-1; j++)
        {
        glBegin(GL_TRIANGLE_STRIP);
        for (i = 0; i < TOPO_COLS; i++)
            {
            index = i + j * TOPO_COLS;
            x = (((float)i) / TOPO_COLS) * 10.0 - 5.0;
            z = (((float)j) / TOPO_ROWS) * 10.0 - 5.0;
            y = elevation[index] * heightScale;
            glColor3f(colors[index].r, colors[index].g, colors[index].b); 
            glVertex3f(x,y,z);

            index = i + (j+1) * TOPO_COLS;
            z = (((float)j+1) / TOPO_ROWS) * 10.0 - 5.0;
            y = elevation[index] * heightScale;
            glVertex3f(x,y,z);
            }
        glEnd();
        }
    }


float currentTime(void)
    {
    static struct timeval startTime;
    static int firstCall=1;
    struct timeval t;
    if (firstCall)
        {
        firstCall = 0;
        gettimeofday(&startTime, NULL);
        }
    gettimeofday(&t,NULL);
    return (t.tv_sec-startTime.tv_sec) +
           (t.tv_usec - startTime.tv_usec) / 1000000.0;
    }


void checkGLError(char *prefix)
    {
    GLenum err = glGetError();
    if (err != GL_NO_ERROR)
        printf("%s GL error '%s'\n",prefix,gluErrorString(err));
    }


void key(unsigned char k, int x, int y)
    {
    if (k == 27)
        exit(0);
    else if (k == '1')
        heightScale *= 1.1;
    else if (k == '2')
        heightScale /= 1.1;
    glutPostRedisplay();
    }


void specialkey(int k, int x, int y)
    {
    if (k == GLUT_KEY_LEFT)
        viewRotY += 3;
    else if (k == GLUT_KEY_RIGHT)
        viewRotY -= 3;
    else if (k == GLUT_KEY_UP)
        viewRotX += 3;
    else if (k == GLUT_KEY_DOWN)
        viewRotX -= 3;
    glutPostRedisplay();
    }
