/*!\file Rain.cpp
   \brief Rain project source code
*/

#include <particle/papi.h>

#include <GL/glut.h>

#include <im.h>
#include <im_image.h>
#include <im_convert.h>

imImage* bg_image = NULL;
imImage* tex_image = NULL;
unsigned char* gl_bg_data = NULL;
unsigned char* gl_tex_data_R = NULL;
unsigned char* gl_tex_data_G = NULL;
unsigned char* gl_tex_data_B = NULL;
unsigned char* gl_tex_data_RGBA = NULL;
GLuint tex_id = -1;
GLuint SpotTexID = -1;


/*!\fn MakeRainStreaksTexture()
  \brief makes the rain streaks texture for testing

	For OpenGL the texture image must be of the form 2^x
*/
void MakeRainStreaksTexture()
{

	int error;

	tex_image = imFileImageLoadBitmap("rain_32x32.png", 0, &error);
	int width = tex_image->width;
	int height = tex_image->height;
	gl_tex_data_RGBA = (unsigned char*) malloc(4*width*height); 

	gl_tex_data_R = (unsigned char*) malloc(tex_image->size); 
	gl_tex_data_G = (unsigned char*) malloc(tex_image->size); 
	gl_tex_data_B = (unsigned char*) malloc(tex_image->size); 

	imConvertPacking(tex_image->data[0], gl_tex_data_R, tex_image->width, tex_image->height, 
	tex_image->depth,tex_image->data_type, 0);
	imConvertPacking(tex_image->data[1], gl_tex_data_G, tex_image->width, tex_image->height, 
	tex_image->depth,tex_image->data_type, 0);
	imConvertPacking(tex_image->data[2], gl_tex_data_B, tex_image->width, tex_image->height, 
	tex_image->depth,tex_image->data_type, 0);

	int rgba_count = 0;
	for(int i=0; i<width; i++)
		for(int j=0; j<height; j++)
		{
			int ch_count = i*width + j;

			gl_tex_data_RGBA[rgba_count++] = gl_tex_data_R[ch_count];
			gl_tex_data_RGBA[rgba_count++] = gl_tex_data_G[ch_count];
			gl_tex_data_RGBA[rgba_count++] = gl_tex_data_B[ch_count];


			if ((gl_tex_data_R[ch_count] == 0) &&
			    (gl_tex_data_G[ch_count] == 0) &&
			    (gl_tex_data_B[ch_count] == 0))
				gl_tex_data_RGBA[rgba_count++] = 0;
			else
				gl_tex_data_RGBA[rgba_count++] = 255;

		}

	glGenTextures(1, &tex_id);
	glBindTexture(GL_TEXTURE_2D, tex_id);

	glTexImage2D(GL_TEXTURE_2D, 0, 4, tex_image->width, tex_image->height, 0, GL_RGBA,
	GL_UNSIGNED_BYTE, gl_tex_data_RGBA);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);


}


/*!\fn LoadBackgroundImage(char* file_name)
  \brief loads the image for the background

	The IM package will take are of most common formats...
*/
void LoadBackgroundImage(char* file_name)
{
	int error;

	bg_image = imFileImageLoadBitmap(file_name, 0, &error);
	gl_bg_data = (unsigned char*) malloc(bg_image->size); 

	imConvertPacking(bg_image->data[0], gl_bg_data, bg_image->width, bg_image->height, bg_image->depth, bg_image->data_type, 0);
}

/*!\fn ComputeParticles()
  \brief calculates the particle dynamics

	The control over the Particles API is done here

*/
void ComputeParticles()
{
	// Set up the state.
	pVelocityD(PDLine(pVec(0.0,0.0,0.1),pVec(0.0,0.0,0.0)));
	pColorD(PDLine(pVec(0.8, 0.9, 1.0), pVec(0.1, 1.0, 1.0)));
	pSize(1.5);
	pStartingAge(0);

	// Generate particles along a very small line in the nozzle.
	//pSource(2, PDLine(pVec(0.0, 0.0, 0.0), pVec(0.0, 0.0, 0.405)));
	pSource(200,PDBox(pVec(-3.5,-3.5,0.0),pVec(3.5,3.5,0.5)));

	// Gravity.
	pGravity(pVec(0.0, 0.0, -0.01));
	
	// Kill particles below Z=-3.
	pSink(false, PDPlane(pVec(0,0,0), pVec(0,0,1)));

	// Move particles to their new positions.
	pMove();
}

/*!\fn DrawGroupAsPoints()
  \brief renders the points

	We have used the Array implementation for performance
to draw as textured point sprites just call glEnable(GL_POINT_SPRITE_ARB) 
before calling this function and after binding the texture.
	
*/
void DrawGroupAsPoints()
{
	int cnt = (int)pGetGroupCount();
	if(cnt < 1) return;

	float *ptr;
	size_t flstride, pos3Ofs, posB3Ofs, size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs;

	cnt = (int)pGetParticlePointer(ptr, flstride, pos3Ofs, posB3Ofs,
     
	size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs);
	if(cnt < 1) return;
    	

	glEnableClientState(GL_COLOR_ARRAY);
	glColorPointer(4, GL_FLOAT, int(flstride) * sizeof(float), ptr + color3Ofs);

	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(3, GL_FLOAT, int(flstride) * sizeof(float), ptr + pos3Ofs);

	glDrawArrays(GL_POINTS, 0, cnt);
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);
		

}

/*!\fn drawParticles()
  \brief renders the particles
	
	We have used Perspective projection for this... TODO
*/
void drawParticles() {
	
	glLoadIdentity();
	gluPerspective(10, bg_image->width / double(bg_image->height), 1, 100);
	gluLookAt(0, -8, 3, 0, 0, 0, 0, 0, 1);

	DrawGroupAsPoints();
}

/*!\fn DrawBackground()
  \brief renders the background

	We have used Parallel projection for this... TODO	
*/
void drawBackground() {
	
	glLoadIdentity();
	glOrtho(0.0,bg_image->width,0.0,bg_image->height,3.5,-3.5);

	glDisable(GL_DEPTH_TEST);
	glRasterPos2f(0.0,0.0);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 
	glDrawPixels(bg_image->width, bg_image->height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)gl_bg_data);
	
}

/*!\fn Draw()
  \brief OpenGL registrered rendering method

	The rendering consists of :
	1- clean up the buffers
	2- drawing the background on the back color buffer
	3- drawing the particles on the back color buffer
	4- blitting
*/
void Draw()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_PROJECTION);

	// Draws the background
	drawBackground();
	
	// Do what the particles do.
	ComputeParticles();
	
	// Draw the particles.
	drawParticles();
	
	// shows everything...
	glutSwapBuffers();
}


/*!\fn Draw()
  \brief OpenGL registrered reshape method

	This is useless... TODO	
*/
void Reshape(int w, int h)
{
	glViewport(0, 0, w, h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glMatrixMode(GL_MODELVIEW);
}

/*!\fn Draw()
  \brief OpenGL initialization method
	
	These are the settings mainly for the SPRITE usage...
*/
void initGL() {


/*	float values[2];
	glGetFloatv(GL_POINT_SIZE_RANGE, values);

	float min = values[0];
	float max = values[1];

*/


	//const GLubyte *v = glGetString(GL_VERSION);
	// we want depth buffering, etc... for the particles.
	glEnable(GL_TEXTURE_2D);

//	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
//	float col[4] = {1.f, 1.f, 1.f, 1.f};
//	glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, col);
	glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glEnable(GL_ALPHA_TEST);
	glAlphaFunc(GL_GREATER, 2/255.0);

	glEnable(GL_POINT_SPRITE_ARB);

	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glPointSize(1.0);

}

int main(int argc, char **argv)
{
	// Initialize GLUT.
	glutInit(&argc, argv);

	// init GL states
	initGL();
	
	// Makes the rain streak texture
	MakeRainStreaksTexture();

	// Loads the background image
	LoadBackgroundImage("rain_bg.jpg");	
	
	// Make a normal 3D window.
	glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
	glutInitWindowSize(bg_image->width,bg_image->height);
	glutCreateWindow("Rain Streaks");
	
	glutDisplayFunc(Draw);
	glutIdleFunc(Draw);
	glutReshapeFunc(Reshape);
	
	// Make a particle group
	int particle_handle = pGenParticleGroups(1, 10000);
	pCurrentGroup(particle_handle);
	
	glutMainLoop();
	
	return 0;
}
