#include "gba.h"
#include "sprite.h"

//create an OAM variable and make it point to the address of OAM
u16* OAM = (u16*)0x7000000;

//create the array of sprites (128 is the maximum)
OAMEntry sprites[128];

//create the rotation and scaling array (overlaps the OAMEntry array memory)
RotData* rotData = (RotData*)sprites;

//Copy our sprite array to OAM
void CopyOAM()
{
	u16 loop;
	u16* temp;
	temp = (u16*)sprites;
	for(loop = 0; loop < 128*4; loop++)
	{
		OAM[loop] = temp[loop];
	}
}

//Set sprites to off screen
void InitialiseSprites()
{
	u16 loop;
	for(loop = 0; loop < 128; loop++)
	{
		sprites[loop].attribute0 = 160;  //y to > 159
		sprites[loop].attribute1 = 240;  //x to > 239
	}
	CopyOAM();
}

/* sprite allocater */

u8 sprite_allocation[128];
u16 sprite_alloc_last = 0;

u16 sprite_alloc()
{
	u16 s = sprite_alloc_last + 1, i;

	for(i=0; i < NUM_SPRITES; i++)
	{
		if(sprite_allocation[s]==0)
		{
			sprite_allocation[s] = 1;
			sprite_alloc_last = s;			
			return s;
		}
		s++;
		if(s >= NUM_SPRITES) s=0;
	}
	/* no free sprites - give back the last sprite + 1 */
	return NUM_SPRITES+1;
}

void sprite_free(u16 sprite)
{
	sprite_allocation[sprite] = 0;
	sprites[sprite].attribute1 = SIZE_8 | 240;
}
