#include "StdAfx.h"
#include "SampleTextureBuilder.h"


SDL_Surface* SampleTextureBuilder::CreateTexture(SampleTextureBuilder::TextureType tex_type, int size)
{
	switch(tex_type)
	{
	case TEX_CHECKER : return CreateChecker(size);
	case TEX_STRIPE_V : return CreateStripeV(size);
	case TEX_STRIPE_H : return CreateStripeH(size);
	default:
		return NULL;
	}
}


SDL_Surface* SampleTextureBuilder::CreateChecker(int size)
{
	SDL_Surface* surface = CreateSquareSurface(size);
	if( surface == NULL )
		return NULL;
	
	for( int y = 0 ; y < surface->h ; ++y )
	{
		for( int x = 0 ; x < surface->w ; ++x )
		{
			int w = 0;
			if((x / (size / 4)) % 2 == 0) w += 1;
			if((y / (size / 4)) % 2 == 0) w += 1;

			if(w % 2 == 0)
				SetRGB(surface, x, y, 255, 255, 255);
			else
				SetRGB(surface, x, y, 0, 0, 255);
		}
	}

	return surface;
}

SDL_Surface* SampleTextureBuilder::CreateStripeV(int size)
{
	SDL_Surface* surface = CreateSquareSurface(size);
	if( surface == NULL )
		return NULL;

	for( int y = 0 ; y < surface->h ; ++y )
	{
		for( int x = 0 ; x < surface->w ; ++x )
		{
			if((x / (size / 4)) % 2 == 0)
				SetRGB(surface, x, y, 0, 0, 255);
			else
				SetRGB(surface, x, y, 255, 255, 255);
		}
	}

	return surface;
}

SDL_Surface* SampleTextureBuilder::CreateStripeH(int size)
{
	SDL_Surface* surface = CreateSquareSurface(size);
	if( surface == NULL )
		return NULL;
	
	for( int y = 0 ; y < surface->h ; ++y )
	{
		for( int x = 0 ; x < surface->w ; ++x )
		{
			if((y / (size / 4)) % 2 == 0)
				SetRGB(surface, x, y, 255, 255, 255);
			else
				SetRGB(surface, x, y, 0, 0, 255);
		}
	}

	return surface;
}

SDL_Surface* SampleTextureBuilder::CreateSquareSurface(int size)
{
	return SDL_CreateRGBSurface(SDL_SWSURFACE, size, size, 32, 0, 0, 0, 0);
}

void SampleTextureBuilder::SetRGB(SDL_Surface* surface, int x, int y, int r, int g, int b)
{
	int w = surface->w;
	int h = surface->h;
	int bps = surface->format->BytesPerPixel;
	int pitch_w = surface->pitch;
	unsigned char* bits = (unsigned char*)surface->pixels;

	int iu = ( x * bps + y * pitch_w );
	bits[iu + 0] = (unsigned char)b;
	bits[iu + 1] = (unsigned char)g;
	bits[iu + 2] = (unsigned char)r;
	bits[iu + 3] = 255;
}
