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

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_gfxPrimitives.h"

#define N 256


int VERT;
int GONS;

/* 4 colors bytes, 2 coordinates per vertex */
#define GONLEN (4 + VERT * 2)
/* this for each polygon plus a backgroung color */
#define LEN (GONLEN * GONS + 3) 

/* Function prototypes */

Uint8 *make_rand_dna(void);
Uint8 *make_dna(void);
SDL_Surface *raster_dna(Uint8 *dna);
double compare_imgs(SDL_Surface *ima, SDL_Surface *imb);
double fitness(Uint8 *dna, SDL_Surface *target);
Uint32 getpixel(SDL_Surface *surface, int x, int y);

Uint8 *step_uphill(Uint8 *dna, SDL_Surface *target);

int main(int argc, char **argv)
{
	SDL_Surface *screen, *target, *raster;
	Uint8 *dna, *evol;
	int starttick, iter;
	
	int invisible = 0, output = 0;
	
	char filename[256];
	
	/* args */
	
	switch (argc)
	{
		case 6:
			invisible = 1;
		case 5:
			output = 1;
			break;	
	}
	
	if (argc < 4)
	{
		printf("Usage : genepic vert gon path [output [invisible]]\n");
		exit(EXIT_FAILURE);
	}

	VERT = atoi(argv[1]);
	GONS = atoi(argv[2]);	
	
	/* Init stuff, yeah */

	if( SDL_Init(SDL_INIT_VIDEO) < 0 )
	{
		printf("Couldn't initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}
	
	screen=SDL_SetVideoMode(N,N,32, SDL_HWSURFACE|SDL_DOUBLEBUF);
        
        if(screen == NULL)
	{
		printf("Couldn't set %dx%d video mode: %s\n", N, N, SDL_GetError());
		exit(1);
        }
	
	srand(clock());
	
	/* load the target picture */
	
	{
		SDL_Surface *tmp;
		
		tmp = IMG_Load(argv[3]);
		if ( tmp == NULL )
		{
			printf("Couldn't load image %s. Exiting.\n", PATH);
			exit(EXIT_FAILURE);
		}
	
		target = SDL_DisplayFormat(tmp);
		SDL_FreeSurface(tmp);
	}
	
	printf("Length of DNA: %d\n", LEN);
	
	dna = make_rand_dna();
	
	starttick = SDL_GetTicks();
	iter = 0;
	
	while (1)
	{
		SDL_Event e;
		double rate;
		double time;

		while(SDL_PollEvent(&e))
		{
			switch(e.type)
			{
				case SDL_QUIT:
					exit(0);
					break;
			}
		}
		
		time = (SDL_GetTicks()-starttick)/60000.0; /* minutes */
		rate = iter / time; /* iteration per minute */
		
		printf("#%d: %f %fmin (%f it/min)\n", iter, fitness(dna,target), time, rate);
		
		raster = raster_dna(dna);
		
		if(output)
		{	
			sprintf(filename, "%s-%.8d.bmp", argv[4], iter);
			if(SDL_SaveBMP(raster, filename) < 0)
				printf("Couldn't save file %s\n",filename);
		}
		if (!invisible)
		{
			SDL_BlitSurface(raster,NULL,screen,NULL);
			SDL_FreeSurface(raster);
			SDL_Flip(screen);
		}

		/* evolution stuff */		
		evol = step_uphill(dna,target);
		free(dna);
		
		dna = evol;
		iter++;
	}
	
	SDL_FreeSurface(target);
	SDL_Quit();
	return 0;
}

Uint8 *make_dna(void)
{
	Uint8 *dna;
	
	dna = (Uint8 *)malloc(LEN * sizeof(dna));
	if (dna == NULL)
	{
		printf("Couldn't allocate memory. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	return dna;
}

Uint8 *dup_dna(Uint8 *dna)
{
	Uint8 *dup;
	int i;
	
	dup = make_dna();
	for (i = 0; i < LEN; i += 1)
	{
		dup[i] = dna[i];
	}
	
	return dup;
}

Uint8 *make_rand_dna(void)
{
	Uint8 *dna;
	int i;
	
	dna = make_dna();
	
	for (i = 0; i < LEN; i += 1)
	{
		dna[i] = rand() % 256;
	}
	
	return dna;
}

SDL_Surface *raster_dna(Uint8 *dna)
{
	SDL_Surface *surf, *tmp;
	int i;
	Sint16 *x, *y;
	
	/* prepare the coord tables */
	
	x = (Sint16 *)malloc(VERT * sizeof(x));
	y = (Sint16 *)malloc(VERT * sizeof(y));
	if (x == NULL || y == NULL)
	{
		printf("Couldn't allocate memory. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	/* make a surface */
	
	tmp = SDL_CreateRGBSurface(SDL_HWSURFACE,N,N,32,0,0,0,0);
	if ( tmp == NULL )
	{
		printf("Couldn't create surface. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	surf = SDL_DisplayFormat(tmp);
	SDL_FreeSurface(tmp);
	
	/* give it its background color */
	
	SDL_FillRect(surf,NULL, SDL_MapRGB(surf->format,dna[LEN-3],dna[LEN-2],dna[LEN-1]));
	
	/* and fill it with stuff */
	
	for (i = 0; i < GONS; i += 1)
	{
		Uint8 r,g,b,a;

		int j;
		
		r = dna[i*GONLEN];
		g = dna[i*GONLEN + 1];
		b = dna[i*GONLEN + 2];
		a = dna[i*GONLEN + 3] / 255.0 * 30 + 30; /* alpha between 30 and 60 */
		
		for (j = 0 ; j < VERT; j += 1)
		{
			x[j] = dna[i*GONLEN + 4 + 2*j];
			y[j] = dna[i*GONLEN + 4 + 2*j + 1];
		}
		
		filledPolygonRGBA(surf, x, y, VERT, r, g, b, a);
	}
	
	return surf;
}

/* returns 1 if equal, 0 if black and white */
double compare_imgs(SDL_Surface *ima, SDL_Surface *imb)
{
	int i,j;
	Uint32 pixa, pixb;
	Uint8 r,g,b;
	Uint8 rr,gg,bb;
	
	double sum = 0;

	for (i = 0; i < N; i += 1)
	for (j = 0; j < N; j += 1)
	{
		double dr, dg, db;
		pixa = getpixel(ima,i,j);
		pixb = getpixel(imb,i,j);
		
		SDL_GetRGB(pixa, ima->format, &r, &g, &b);
		SDL_GetRGB(pixb, imb->format, &rr, &gg, &bb);
		
		dr = (r - rr);
		dg = (g - gg);
		db = (b - bb);
		
		sum += 0.4*dr*dr + 0.45*dg*dg + 0.15*db*db;
	}
	return 1.0 - sum/(N*N*255.0*255.0);	/* 65025 is the max value for one pixel */
}

double fitness(Uint8 *dna, SDL_Surface *target)
{
	SDL_Surface *raster;
	double diff;
	
	raster = raster_dna(dna);
	diff = compare_imgs(raster,target);
	
	SDL_FreeSurface(raster);
	
	return diff;
}

/*
 * Return the pixel value at (x, y)
 * NOTE: The surface must be locked before calling this!
 */
Uint32 getpixel(SDL_Surface *surface, int x, int y)
{
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to retrieve */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    switch (bpp) {
    case 1:
        return *p;

    case 2:
        return *(Uint16 *)p;

    case 3:
        if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
            return p[0] << 16 | p[1] << 8 | p[2];
        else
            return p[0] | p[1] << 8 | p[2] << 16;

    case 4:
        return *(Uint32 *)p;

    default:
        return 0;       /* shouldn't happen, but avoids warnings */
    } // switch
}

Uint8 *step_uphill(Uint8 *dna, SDL_Surface *target)
{
	int byte;
	Uint8 *dup;
	double fit;
	char *grad;
	
	fit = fitness(dna,target);
	
	dup = dup_dna(dna);
	
	/* make a table for the gradient, inited to 0 */
	
	grad = (char *)calloc(LEN,sizeof(grad));
	if ( grad == NULL )
	{
		printf("Couldn't Allocate memory. Exiting.\n");
		exit(EXIT_FAILURE);
	}
	
	/* compute gradient: for each byte, try adding one and see if fitness increases */
	for (byte = 0; byte < LEN; byte += 1)
	{	
		double newfit;
		int dir;
		
		dir = rand() % 5 - 2;
		
		dup[byte] += dir;
		newfit = fitness(dup,target);
		
		grad[byte] += newfit > fit ? dir : -dir;

		/* set it back for the next calculations */
		dup[byte] -= dir;
	}

	/* and add the gradient */
	for (byte = 0; byte < LEN; byte += 1)
	{
		int try = dup[byte] + grad[byte];
		if (try < 256 && try >= 0)
			dup[byte] = try;
	}

	free(grad);
	
	return dup;
}
