

#include "DXUT.h"
#include "terrain.h"
#include "global.h"

#define NUM_RAND_MAPS 13
int g_seedMapValues[NUM_RAND_MAPS] = { 343, 298, 888, 74, 54, 23, 34, 2, 934, 343, 99, 17, 3435 };


Terrain::Terrain( void )
: m_nextMap(NUM_RAND_MAPS)
{

}

void Terrain::Create( void )
{
	NextMap();
}

void Terrain::NextMap( void )
{
	if( m_nextMap > NUM_RAND_MAPS )
	{
		m_nextMap = 0;
	}

	if( m_nextMap == NUM_RAND_MAPS )
	{	//Clear map
		for( int r=0; r<TERRAIN_WIDTH; r++ )
		{
			for( int c=0; c<TERRAIN_WIDTH; c++ )
			{
				m_terrain[r][c] = 0;
			}
		}
	}
	else
	{
		int modValue = 3;
		srand(g_seedMapValues[m_nextMap]);
		if( m_nextMap < 3 ) { modValue = 10; }

		for( int r=0; r<TERRAIN_WIDTH; r++ )
		{
			for( int c=0; c<TERRAIN_WIDTH; c++ )
			{
				if( rand()%modValue == 0 )
				{
					m_terrain[r][c] = -1;
				}
				else
				{
					m_terrain[r][c] = 0;
				}
			}
		}
	}

	ResetColors();
	m_nextMap++;
}

D3DXVECTOR3 Terrain::GetCoordinates( int r, int c )
{
	D3DXVECTOR3 pos;
	pos.x = ((float)c/(float)TERRAIN_WIDTH) + 0.025f;
	pos.y = 0.0f;
	pos.z = ((float)r/(float)TERRAIN_WIDTH) + 0.025f;
	
	return( pos );
}

bool Terrain::GetRowColumn( D3DXVECTOR3* pos, int* r, int* c )
{
	if( pos->x >= 0.0f && pos->x <= 1.0f && pos->z >= 0.0f && pos->z <= 1.0f )
	{
		*r = (int)(pos->z * (float)TERRAIN_WIDTH);
		*c = (int)(pos->x * (float)TERRAIN_WIDTH);
		return true;
	}
	else
	{
		return false;
	}
}

void Terrain::SetColor( int r, int c, DebugDrawingColor color )
{
	if( m_terrain[r][c] >= 0 )
	{
		m_terrainColor[r][c] = color;
	}
	else
	{
		ASSERTMSG( 0, "Can't set color to a grid square that is a wall" );
	}
}

void Terrain::ResetColors( void )
{
	for( int r=0; r<TERRAIN_WIDTH; r++ )
	{
		for( int c=0; c<TERRAIN_WIDTH; c++ )
		{
			if( m_terrain[r][c] >= 0 )
			{
				m_terrainColor[r][c] = DEBUG_COLOR_WHITE;
			}
			else
			{
				m_terrainColor[r][c] = DEBUG_COLOR_BLACK;
			}
		}
	}
}

void Terrain::DrawDebugVisualization( IDirect3DDevice9* pd3dDevice )
{
	D3DXVECTOR3 pos( 0.0f, 0.005f, 0.0f );

	for( int r=0; r<TERRAIN_WIDTH; r++ )
	{
		for( int c=0; c<TERRAIN_WIDTH; c++ )
		{
			pos.x = (float)c / (float)TERRAIN_WIDTH;
			pos.z = (float)r / (float)TERRAIN_WIDTH;
			if(m_terrainColor[r][c] == DEBUG_COLOR_BLACK)
			{
				g_debugdrawing.DrawCube( pd3dDevice, &pos, 1.0f/(float)TERRAIN_WIDTH, m_terrainColor[r][c] );
			}
			else
			{
				g_debugdrawing.DrawQuad( pd3dDevice, &pos, 1.0f/(float)TERRAIN_WIDTH, m_terrainColor[r][c] );
			}
		}
	}
}
