#include <allegro.h>
#include <assert.h>

#include "collide.h"


CMask *create_mask(BITMAP *bmp)
{
    CMask *mask = new CMask;
    assert(mask);

    int x1, y1;
    int p;
    int width = 0, height = 0;

    for(x1 = 0; x1 < 32; x1++)
    { 
	mask->mask[x1] = 0;
    }

    for(y1 = 0; y1 < 32; y1++)
    {
	for(x1 = 0; x1 < 32; x1++)
	{
	    p = getpixel(bmp, x1, y1);

	    if(p>0)
	    {
		if(x1 > width)  width = x1;
		if(y1 > height) height = y1;
		mask->mask[y1] += 0x0001 << (31 - x1);
	    }
	}
    }

    mask->width = width;
    mask->height = height; 

    return mask;
}

void destroy_mask(CMask *mask)
{
    if(mask) delete mask;
}

CMask *copy_mask(CMask *mask)
{
    CMask *newmask = new CMask;

    newmask->width = mask->width;
    newmask->height = mask->height;
    for(int i=0; i<32; ++i)
    {
	newmask->mask[i] = mask->mask[i];
    }

    return newmask;
}

bool check_collision(CMask *mask1, int x1, int y1, CMask *mask2, int x2, int y2)
{
    assert(mask1);
    assert(mask2);

    if( (x1 > (x2 + mask2->width)) || (x2 > (x1 + mask1->width)) ||
	(y1 > (y2 + mask2->height)) || (y2 > (y1 + mask1->height)) )
    {
	return 0;
    }
    else
    {
/*
	int dx1, dx2, dy1, dy2;

	if(x1>x2)
	{
	    dx1 = 0;
	    dx2 = x1 - x2;
	}
	else
	{
	    dx1 = x2 - x1;
	    dx2 = 0;
	}

	if(y1>y2)
	{
	    dy1 = 0;
	    dy2 = y1 - y2;
	}
	else
	{
	    dy1 = (y2 - y1) - 1;
	    dy2 = 0;
	}

	while( (dy1 < mask1->height) && (dy2 <= mask2->height) )
	{
	    if( (mask1->mask[dy1] << dx1) & (mask2->mask[dy2] << dx2) )
	    {
		return 1;
	    }

	    dy1++;
	    dy2++;
	}

	return 0; 
	*/
	return 1;
    }
}
