#include "stdafx.h"
#include "Lines.h"

#include "Camera.h"
#include "SceneNode.h"

cCircleLines::cCircleLines( const NiColorA& color )
{
	mPosCoords = NiNew NiPoint3[11];
	for( unsigned int i = 0; i < 11; ++i )
	{
		mPosCoords[i] = NiPoint3::ZERO;
	}

	mColors = NiNew NiColorA[11];
	for( unsigned int i = 0; i < 10; i += 2 )
	{
		mColors[i] = NiColorA::BLACK;
		mColors[i+1] = color;
	}
	mColors[10] = NiColorA::BLACK;

	mFlags = NiAlloc( NiBool, 11 );
	mFlags[0] = 1;
	mFlags[1] = 1;
	mFlags[2] = 1;
	mFlags[3] = 1;
	mFlags[4] = 1;
	mFlags[5] = 1;
	mFlags[6] = 1;
	mFlags[7] = 1;
	mFlags[8] = 1;
	mFlags[9] = 1;
	mFlags[10] = 0;

	mLines = NiNew NiLines(
		11,
		mPosCoords,
		mColors,
		0,
		0,
		NiGeometryData::NBT_METHOD_NONE,
		mFlags );

	mMatProp = NiNew NiMaterialProperty;
	mMatProp->SetAmbientColor( NiColor::WHITE );
	mMatProp->SetDiffuseColor( NiColor::WHITE );
	mMatProp->SetSpecularColor( NiColor::WHITE );
	mMatProp->SetEmittance( NiColor::WHITE );

	mVertColorProp = NiNew NiVertexColorProperty;
	mVertColorProp->SetSourceMode( NiVertexColorProperty::SOURCE_EMISSIVE );
	mVertColorProp->SetLightingMode( NiVertexColorProperty::LIGHTING_E );

	mWireProp = NiNew NiWireframeProperty;
	mWireProp->SetWireframe( false );

	mLines->AttachProperty( mMatProp );
	mLines->AttachProperty( mVertColorProp );
	mLines->AttachProperty( mWireProp );
	mLines->UpdateProperties();
	mLines->Update( 0.0f );
}

void cCircleLines::Render( cSceneNode* n, cCamera* cam )
{
	NiPoint3 right = cam->GetWorldRightVector();
	NiPoint3 up = cam->GetWorldUpVector();

	const NiPoint3& c = n->GetCenter();
	float r = n->GetRadius();
	float x, y;
	NiPoint3 dir;

	for( unsigned int i = 0, ang = 0; ang < 360; ++i, ang += 36 )
	{
		x = NiCos( ang * NI_PI / 180.0f );
		y = NiSin( ang * NI_PI / 180.0f );

		dir = right * x + up * y;
		mPosCoords[i] = c + dir * r;
	}

	mPosCoords[10] = mPosCoords[0];

	NiGeometryData* geom = mLines->GetModelData();

	geom->Replace(
		11,
		mPosCoords,
		0,
		mColors,
		0,
		0,
		NiGeometryData::NBT_METHOD_NONE );

	geom->MarkAsChanged( NiGeometryData::VERTEX_MASK );
	mLines->RenderImmediate( NiRenderer::GetRenderer() );
}
