#include <stdio.h>
#include <GL/glut.h>
#include <math.h>
#include <pam.h>

static GLuint texName;
static GLuint heightfieldList;
static GLfloat spin=0;
static GLboolean spinny=GL_TRUE;
static GLboolean alphatest=GL_FALSE;
#define SPINAMT 0.1
/* location of viewer, and texture offset */
static GLfloat loc[3],  mmx, mmy;
/* scale mouse-pixel-distance to degree-of-rotation ratio */
#define MOUSE_ACCEL 0.4

/* mouse scaling factor */
#define ZOOMFACTOR 0.100

int button[3]; /*mouse button state */
int statexy[2]; /*mouse window coord state */
/* direction of viewer. zoom and aspect ratio for projection matrix */
float xzangle = 90.0, azimuth = 90.0,  zoom=1.0, gaspect;

void error(char *errstr) {
	GLenum err;

	if ( ( err = glGetError()) != GL_NO_ERROR ) {
		fprintf(stderr, "GL ERROR: %s : %s", errstr, gluErrorString(err));
		exit(1);
	}
}


/* read pixel data from file, return x,y resolution and byte array */
GLubyte *get_ppm_pixels(char *fname, int *xresp, int *yresp) {

	GLubyte *image_map, rb, bb, gb;
	FILE *img_f;

        int width, height, maxval, i, j, offset;
        pixel **pnmrows, a_pixel, *pixel_row;

        /* read ppm file */

        if (img_f = fopen(fname, "r")) {
                pnmrows = ppm_readppm(img_f, &width, &height, &maxval);
                /* printf("Image %s is %d by %d with max %d\n", 
			fname, width, height, maxval); */
                image_map = (GLubyte *) 
                        malloc( sizeof(GLubyte) * width * height * 4);
                for ( j = 0 ; j < height ; j++)
                        for ( i = 0 ; i < width ; i++) {
                                offset = ( width *  j + i ) ;
                                pixel_row = pnmrows[height - j - 1];  
                                /* pixel_row = pnmrows[j];  */
                                a_pixel = pixel_row[i];
                                rb = PPM_GETR(a_pixel);
                                gb = PPM_GETG(a_pixel);
                                bb = PPM_GETB(a_pixel);
                                image_map[offset * 4 + 0] = rb;
                                image_map[offset * 4 + 1] = bb;
                                image_map[offset * 4 + 2] = bb;
				if ( rb & bb & gb == 0xff )
                                	image_map[offset * 4 + 3] = 0;
				else
                                	image_map[offset * 4 + 3] = 255;
                        }
        } else {
                fprintf(stderr, "Could not open %s for reading!\n", fname);
                exit(1);
        }
	*xresp = width;
	*yresp = height;

	return (image_map);
}

/* draw heightfield mesh from graymap from filename.
Generates quad strips with normals and texture coordinates. 
*/
void makeHeightMesh(char *pgm_filename, GLfloat scale, GLfloat zscale) {
	int xres, yres, xc, yc;
	GLfloat xi, yi, xk, yk, xd, yd, z1, z2, z3, z4, iscale;
	GLfloat nx1, ny1, nz1, nx2, ny2, nz2, nx3, ny3, nz3, nx4, ny4, nz4, 
		nx, ny, nz, lnorm;
	GLubyte *imagepixels;

	imagepixels = get_ppm_pixels(pgm_filename, &xres, &yres);
	xd = scale / (GLfloat) xres;
	yd = scale / (GLfloat) yres;
	iscale = ( 1.0 / scale );
	for ( yc = 0 ; yc < (yres - 1); yc++) {
		glBegin(GL_QUAD_STRIP);
		for ( xc = 0 ; xc < xres; xc++) {
			xi = scale * (GLfloat) xc * xd;
			yi = scale * (GLfloat) yc * yd;
			z1 = (GLfloat) imagepixels[( yc * xres + xc ) * 4] / 256.0 * zscale ;
			z2 = (GLfloat) imagepixels[( ( yc + 1) * xres + xc ) * 4] / 256.0 * zscale;
			if (xc < ( xres - 1)) {
				nz3 = (GLfloat) imagepixels[
					( yc * xres + xc + 1 ) * 4] / 
					256.0 * zscale ;
				nz4 = (GLfloat) imagepixels[
					( (yc + 1) * xres + xc + 1 ) * 4] / 
					256.0 * zscale ;
			} else {
				/* genius -> extend previous vector */
				nz3 = 2 * nz1 - (GLfloat) imagepixels[
					( yc * xres + xc - 1 ) * 4] / 
					256.0 * zscale ;
				nz4 = 2 * nz2 - (GLfloat) imagepixels[
					( (yc + 1) * xres + xc - 1 ) * 4] / 
					256.0 * zscale ;
			}
			/* n = ( n3 - n1 ) cross ( n2 - n1 ) */
	
			nx1 = xi ;             ny1 = yi;              nz1 = z1; 
			nx2 = xi;              ny2 = yi + scale * yd; nz2 = z2;
			nx3 = xi + scale * xd; ny3 = yi;
			nx4 = xi + scale * xd; ny4 = yi + scale * yd;
			nx1 = 0.0        ; ny1 = scale * yd ; nz1 = z3 - z1;
			nx2 = scale * xd ; ny2 = 0.0;	    ; nz2 =  z2 - z1;
			nx3 = 0.0 	 ; ny3 = scale * yd ; nz3 =  z4 - z2;

			nx = (ny1 * nz2 - nz1 * ny2);
            		ny = (nz1 * nx2 - nx1 * nz2);
            		nz = (nx1 * ny2 - ny1 * nx2);
			lnorm = -1.0 / sqrt( nx * nx + ny * ny + nz * nz );
			nx *= lnorm;
			ny *= lnorm;
			nz *= lnorm;
			glNormal3f(nx, ny, nz);
			glTexCoord2f( (GLfloat) xc / (GLfloat) xres, (GLfloat) yc / (GLfloat) yres); 
			glVertex3f( xi, yi, z1);
			nx =  (ny3 * nz2 - nz3 * ny2);
            		ny =  (nz3 * nx2 - nx3 * nz2);
            		nz =  (nx3 * ny2 - ny3 * nx2);
			lnorm = -1.0 / sqrt( nx * nx + ny * ny + nz * nz );
			nx *= lnorm;
			ny *= lnorm;
			nz *= lnorm;
			glNormal3f(nx, ny, nz);
			glTexCoord2f( (GLfloat) xc / (GLfloat) xres, (GLfloat) ( yc + 1) / (GLfloat) yres); 
			glVertex3f( xi, yi + scale * yd, z2);
		}
		glEnd();
	}
	free(imagepixels);
}

/* create texture opject from filename */
void makeMapTexture(char *map_filename) {
	GLubyte *imagepixels;
	int xres, yres, xc, yc;

	imagepixels = get_ppm_pixels(map_filename, &xres, &yres);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, xres, yres, 
			0, GL_RGBA, GL_UNSIGNED_BYTE, imagepixels);
	free(imagepixels);
	error("glTexImage2D");
}
/* set default texture parameters */
void setTexParams(void)
{
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	error("glTexFiltmag");
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	error("glTexFiltmin");

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	error("glTexWrap");
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	error("glTexWrap");
	/* leave as modulate
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);  */
}

double inline deg2rad(double deg) {
        double rad;
                                                                      
        rad = (deg / 360.0 * M_PI * 2.0);
        return rad;
}
                                                                      
void init(void) {
	GLfloat mat_diffuse[] = {1.0, 1.0, 1.0, 1.0};
	GLfloat mat_specular[] = {0.0, 0.0, 1.0, 1.0};
	GLfloat light_diffuse[] = {1.0, 1.0, 1.0, 1.0};
	GLfloat light_specular[] = {0.0, 0.0, 1.0, 1.0};
	
	glClearColor(0.0, 0.4, 0.6, 0.0);
	glEnable(GL_DEPTH_TEST);
	glShadeModel(GL_SMOOTH);
	glEnable(GL_AUTO_NORMAL);

	/* makeStripeImage(); */

	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	/* generate heightfield mesh in display list */
	heightfieldList = glGenLists(1);
	glNewList(heightfieldList, GL_COMPILE);
	makeHeightMesh("sfbikeheight.pgm", 10.0, 14.0);
	glEndList();

	/* create bike map texture */
	glGenTextures(1, &texName);
	glBindTexture(GL_TEXTURE_2D, texName);
	setTexParams();
	makeMapTexture("bikemap2k.ppm");
	
	glEnable(GL_LIGHTING); 
	glEnable(GL_LIGHT0); 
	glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
	glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 64.0);
	glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
	glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);

	glEnable(GL_TEXTURE_2D);

	/* setup viewer */
	loc[0] = 0.0 ; loc[1] = -7.0;  loc[2] = -6.0;
	xzangle = 0.0; azimuth = 0.0;
	mmx = 0.0 ; mmy = 0.0;

        button[0] = button[1] = button[2] = GLUT_UP;


}

void display(void) {
	GLfloat position[] = {1.0, 1.0, 1.0, 0.0};


	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glColor3f(0.0, 1.0, 0.0);
	/* orient viewer */
	glLoadIdentity();
	glRotatef(-azimuth, 1.0, 0.0, 0.0);
	glRotatef(xzangle, 0.0, 1.0, 0.0);

	glTranslatef(loc[0], loc[1], loc[2]);

	glPushMatrix();
	glRotatef(-90.0, 1.0, 0.0, 0.0);
	glLightfv(GL_LIGHT0, GL_POSITION, position);
	glColor4f(0.0, 1.0 , 0.0, 0.0 );
	glCallList(heightfieldList);
	glPopMatrix();
	glutSwapBuffers();
}

void idle(void) {
	if ( spinny )
		spin += SPINAMT;
	glutPostRedisplay();
}

void reshape(int w, int h) {
	GLfloat aspect;
	
	aspect = (GLfloat) w / (GLfloat) h;

	glViewport(0, 0, (GLsizei) w, (GLsizei) h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	/* if ( w <= h )
		glOrtho( -3.5, 3.5, -3.5 / aspect , 3.5 / aspect , -3.5, 33.5);
	else
		glOrtho( -3.5 * aspect , 3.5 * aspect , -3.5, 3.5, -3.5, 33.5);
	*/
	/* gluPerspective(120.0, aspect, 1.0, 100.0); */
	gaspect = aspect;
	gluPerspective(50.0, aspect, 1.0, 1000.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void keyboard(unsigned char c, int x, int y) {

	/* calculate forward, left, right, up, down, back
	vectors from viewer direction angles */
        GLfloat cosxz, sinxz, rtc, rts, upness, cosupness;

	/* turning left/right */
        cosxz = cos(deg2rad(xzangle));
        sinxz = -sin(deg2rad(xzangle));
	/* strafing */
        rtc = cos(deg2rad(xzangle + 90.0));
        rts = -sin(deg2rad(xzangle + 90.0));

	/* neck up/down */
	cosupness = cos(deg2rad(azimuth));
	upness = -sin(deg2rad(azimuth));

	switch (c) {
		case 27: case 'q':
			exit(0);
			break;
		case ' ':
			if (spinny)
				spinny = GL_FALSE;
			else
				spinny = GL_TRUE;
			break;
		/* forward */
		case 'w': loc[2] += cosxz * cosupness;
			  loc[1] += upness;
		 	  loc[0] += sinxz * cosupness; break;
		/* back */
		case 's': loc[2] -= cosxz * cosupness;
			  loc[1] -= upness;
			  loc[0] -= sinxz * cosupness; break;
		/* strafe left */
		case 'a': loc[0] -= rts; loc[2] -= rtc; break;
		/* strafe right */
		case 'd': loc[0] += rts; loc[2] += rtc; break;
		/* rotate left */
		case 'z': xzangle += 1.4; break;
		/* rotate right */
		case 'x': xzangle -= 1.4; break;
		/* offset texture -y */
		case 'i': mmy -= .01; break;
		/* offset texture +y */
		case 'k': mmy += .01; break;
		/* offset texture -x */
		case 'j': mmx -= .01; break;
		/* offset texture +x */
		case 'l': mmx += .01; break;
		/* toggle on billboarding effect */
		case 'b': if (alphatest) {
				alphatest = GL_FALSE;
				glDisable(GL_ALPHA_TEST);
			} else {
				alphatest = GL_TRUE;
				glEnable(GL_ALPHA_TEST);
				glAlphaFunc(GL_GREATER, 0.5);
				printf("Billboarding\n");
			}
			break;
			  
		default:
			printf("No key bound for '%c' dec: %d hex: %x\n",c,c,c);
			break;
	}
	glMatrixMode(GL_TEXTURE);
	glLoadIdentity();
	glTranslatef(mmx, mmy, 0.0);
	glMatrixMode(GL_MODELVIEW);
	glutPostRedisplay();
}
void mouse(int but, int state, int x, int y) {
        switch (but) {
                case GLUT_LEFT_BUTTON:
                        if (state == GLUT_DOWN) {
                                button[0] = GLUT_DOWN;
                        } else {
                                button[0] = GLUT_UP;
                        }       break;
                case GLUT_MIDDLE_BUTTON:
                        if (state == GLUT_DOWN) {
                                button[1] = GLUT_DOWN;
                        } else {
                                button[1] = GLUT_UP;
                        }       break;
                case GLUT_RIGHT_BUTTON:
                        if (state == GLUT_DOWN) {
                                button[2] = GLUT_DOWN;
                        } else {
                                button[2] = GLUT_UP;
                        }       break;
        }
        statexy[0] = x;
        statexy[1] = y;
}

void motion(int x, int y) {
        if (button[0] == GLUT_DOWN) {
        /* orbit left/right and up/down */
                azimuth -= (float) (y - statexy[1]) * MOUSE_ACCEL;
                xzangle += (float) (x - statexy[0]) * MOUSE_ACCEL;
                                                                      
        }
	/* move near and far planes of projection */
        if (button[1] == GLUT_DOWN) {
                zoom *= ( 1.0 +  (GLfloat) ( y - statexy[1]) * ZOOMFACTOR);
                if (zoom <= 0.0) zoom = 0.1;
                if (zoom > 4.0) zoom = 4.0;
                        glMatrixMode(GL_PROJECTION);
                        glLoadIdentity();
                        /* gluPerspective(40.0, gaspect,
                                zoom / 10.0, zoom * 100.0); */
                        gluPerspective(zoom * 40.0 , gaspect,
				1.0, 1000.0);
                        glMatrixMode(GL_MODELVIEW);
        }
        statexy[0] = x; statexy[1] = y;
}


int main (int argc, char **argv) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowPosition(100, 50);
	glutInitWindowSize(800, 700);
	glutCreateWindow(argv[0]);
	init();
	glutDisplayFunc(display);
	glutKeyboardFunc(keyboard);
	glutIdleFunc(idle);
	glutMouseFunc(mouse);
        glutMotionFunc(motion);
	glutReshapeFunc(reshape);
	glutMainLoop();
	return (0);
}
