#include "sprite.h"
#include "resource.h"

Sprite::Sprite()
{
	// Set to no visibility.
	Show = false;
}

Sprite::~Sprite() { }

VOID Sprite::Release()
{
	// Release the sprite object.
	if (Object != NULL)
	{
		Object->Release();
		Object = NULL;
	}

	// Release the sprite texture.
	if (Texture != NULL)
	{
		Texture->Release();
		Texture = NULL;
	}

	// Release the Direct3D Device.
	if (Device != NULL)
	{
		Device->Release();
		Device = NULL;
	}
}

void Sprite::LoadFromResources(int id)
{
	// Load a sprite from a supplied resource ID.
	D3DXCreateTextureFromResource(Device, NULL, MAKEINTRESOURCE(id), &Texture); 
	SetProperties();
}

void Sprite::LoadFromFile(LPCSTR file)
{
	// Load a sprite from a specified path.
	D3DXCreateTextureFromFile(Device, file, &Texture);
	SetProperties();
}

void Sprite::SetProperties()
{
	// Set the texture from the sprite surface.
	Texture->GetLevelDesc(0, &Surface);
	// Set the sprite center point.
	Center = D3DXVECTOR2(Surface.Width/2, Surface.Height/2);

	// Set other sprite default properties.
	Scale = D3DXVECTOR2(1.0f,1.0f);
	Rotation = 0.0f;
	Color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
}

void Sprite::SetCenter() 
{
	// Get the device viewport.
	D3DVIEWPORT9 Viewport;
	Device->GetViewport(&Viewport);

	D3DDISPLAYMODE Display;

	// Get the device display mode.
	Device->GetDisplayMode(0, &Display);

	if (Viewport.Width > Display.Width)
		Viewport.Width = Display.Width;

	if (Viewport.Height > Display.Height)
		Viewport.Height = Display.Height;

	// Position the sprite in the center point of the window.
	Position = D3DXVECTOR2(
		((float)Viewport.Width/2)-((float)Surface.Width/2),
		((float)Viewport.Height/2)-((float)Surface.Width/2));
}

void Sprite::Init(IDirect3DDevice9* device) 
{
	Device = device;

	// Create a sprite object on the device.
	D3DXCreateSprite(Device, &Object);
}

void Sprite::Render() 
{
	// Begin the sprite render process.
	Object->Begin(D3DXSPRITE_ALPHABLEND);

		// Create the sprite transforms.
		D3DXMATRIX Matrix;
		D3DXMatrixTransformation2D(&Matrix, &Center, 0.0f, &Scale, &Center, Rotation, &Position);

		// Transform and draw the sprite.
		Object->SetTransform(&Matrix);
		Object->Draw(Texture, NULL, NULL, NULL, Color);

	// End the sprite render process.
	Object->End();
}