#include once "iso_sprite.bi"
#include once "iso_plog.bi"

#include once "fbpng.bi"

sub calc_center _
	( _
		byref sprite as sprite_t _
	)

	dim as any ptr p = any

	' Find the center point for y axis
	p = sprite.img + 1 ' first pixel

	for y as integer = 0 to sprite.img->height - 1
		dim as uinteger c = *cptr( uinteger ptr, p )
		if c = RGB( 255, 163, 255 ) then
			sprite.cy = y - 1
		end if
		p += sprite.img->pitch
	next y

	' Find the center point for x axis
	p = sprite.img + 1 ' first pixel

	for x as integer = 0 to sprite.img->width - 1
		dim as uinteger c = cptr( uinteger ptr, p )[x]
		if c = RGB( 255, 163, 255 ) then
			sprite.cx = x - 1
		end if
	next x

end sub

sub fix_trans _
	( _
		byref sprite as sprite_t _
	)

	dim as any ptr p = any

	' Find the center point for y axis
	p = sprite.img + 1 ' first pixel

	for y as integer = 0 to sprite.img->height - 1
		for x as integer = 0 to sprite.img->width - 1
			dim as uinteger c = cptr( uinteger ptr, p )[x]
			if c = RGB( 91, 0, 0 ) then ' Translate the trans color
				cptr( uinteger ptr, p )[x] = RGB( 255, 0, 255 )
			end if
		next x
		p += sprite.img->pitch
	next y

end sub

constructor sheet_t _
	( _
		byref filename      as string, _
		byval sheet_xcount  as integer, _
		byval sheet_ycount  as integer, _
		byval sprite_width  as integer, _
		byval sprite_height as integer _
	)

	dim as fb.image ptr temp

	temp = png_load( filename, PNG_TARGET_FBNEW )

	count = sheet_xcount * sheet_ycount

	for y as integer = 0 to sheet_ycount - 1
		for x as integer = 0 to sheet_xcount - 1
			dim as integer sx = x * sprite_width
			dim as integer sy = y * sprite_height
			dim as integer i = (y * sheet_xcount) + x

			sprite(i).img = imagecreate( sprite_width - 1, sprite_height - 1 )
			get temp, (sx, sy) - (sx + (sprite_width - 2), sy + (sprite_height - 2)), sprite(i).img

			calc_center( sprite(i) )

			line sprite(i).img, (0, 0)-(sprite(i).img->width - 1, sprite(i).img->height - 1), RGB( 255, 0, 255 ), B

			fix_trans( sprite(i) )

		next x
	next y

	png_destroy( temp )

end constructor

destructor sheet_t _
	( _
	)

	for i as integer = 0 to count - 1
		imagedestroy( sprite(i).img )
	next i

end destructor