/** 
 *  _   _        _  _                           _             
 * | |_| |  ___ | || |  ___   __ _  _ __  _ __ (_)  ___  _ __ 
 * |  _  | / _ \| || | / __| / _` || '__|| '__|| | / _ \| '__|
 * | | | ||  __/| || || (__ | (_| || |   | |   | ||  __/| |   
 * |_| |_| \___||_||_| \___| \__,_||_|   |_|   |_| \___||_|   
 * 
 *  (c) 2001 Free Lunch Design, Teknisk-IT, AerotechTelub
 *			  http://www.freelunchdesign.com
 * 
 * This source code is released as is under GPL (General Public
 * License). Please refer to license.txt for more information.
 * 
 */
 
#include <math.h>
#include "allegro.h"
#include "blob.h"

char blob_blender[256][256];


blob::blob(int diameter, int from_col, int to_col) {
	bmp = create_bitmap(diameter, diameter);
	upper = to_col;
	lower = from_col;
	int dist = upper-lower;
	dx = rand()%40/10.0+1;
	dy = rand()%50/10.0;
	a_matt = diameter * 0.07;
	int a,b;

	if (bmp != NULL) {
		//generate blob
		for(int y=0;y<diameter;y++)
			for(int x=0;x<diameter;x++) {
				int dx = x - diameter / 2;
				int dy = y - diameter / 2;
				float k = 1 - sqrt(dx*dx+dy*dy) * 2 / diameter;
			    if (k < 0) k = 0;
				unsigned char c = MAX(dist * k * k, 0);
				bmp->line[x][y] = c;
			}

		// setup blender
		for(a=0;a<256;a++)
			for(b=0;b<256;b++)
				blob_blender[a][b] = MIN(a+b, upper);
	}
}

blob::~blob() {
	if (bmp != NULL) destroy_bitmap(bmp);
}

void blob::draw(BITMAP *dest_bmp) {
	int v,u;
	ix = x;
	iy = y;

	// add blob to bitmap
    for(v=a_matt;v<bmp->h-a_matt;v++)
      for(u=a_matt;u<bmp->w-a_matt;u++) 
		  dest_bmp->line[iy+v][ix+u] = blob_blender[dest_bmp->line[iy+v][ix+u]][bmp->line[v][u]];
}

void blob::move(int x1, int y1, int x2, int y2) {
	if (x + dx + bmp->w > x2 || x + dx < x1) {
		dx = -dx;
		dy = -rand()%7-3;
	}
	if (y + dy + bmp->h > y2) dy = -dy*0.8;
	if (y + dy < y1) dy = -dy;

	x += dx;
	y += dy;
	dy = dy + 0.2;
}