#include "softProjRender.h"

#include "streams\ErrorStream.h"
extern ExceptionStream< ostream&, PauseAndExitFunctor  > KODIAK_ERROR;
extern ExceptionStream< ostream&, ContinueFunctor  > KODIAK_WARNING;
extern KODIAK_DEBUG_STREAM KODIAK_DEBUG_COUT;


SoftProjRender::SoftProjRender( Context &context, CGprogram vertexShader, CGprogram fragmentShader ): GLPhongRender( context, vertexShader, fragmentShader )
{

}



void SoftProjRender::renderGrid2D( const Point_3<double> &from, const Point_3<double> &to, const CRgbw &color, double lineOffset, float rot[3], float width  )
{
	glPushMatrix();
	this->bind();

	GLboolean useBlending;
	glGetBooleanv( GL_BLEND, &useBlending );

	glEnable(GL_BLEND);
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	selectTextureUnit( 0 );
	glDisable(GL_TEXTURE_2D);

	Vector_3<double> offset = to - from;
	
	


	float diffX = offset.x();
	float diffY = offset.y();

	if ( offset == Vector_3<double>(0,0,0) )
	{
		KODIAK_WARNING<<"Cannot normalize, is zero vector: SoftProjRender::renderGrid2D -> Vector_3<float> offset = to - from; !";
		return;
	}

	offset.normalize();
	
	glColor4f( color.col.r, color.col.g, color.col.b, color.w );

	Point_3<double> beginLine;
	Point_3<double> endLine;

	float hLineLenght = int (diffY / lineOffset) * lineOffset;
	float vLineLenght = int (diffX / lineOffset) * lineOffset;

	glRotatef( rot[0],1,0,0 );
	glRotatef( rot[1],0,1,0 );
	glRotatef( rot[2],0,0,1 );


	glLineWidth( width );

	//NOTE: solution with matrix translation is much more stable than glVertex3f( x+translation ) version!!!
	glTranslatef( from.x(), from.y(), from.z() );
	glBegin( GL_LINES );
		
		//render vertical lines
		beginLine= MAKE_POINT<double>(0,0,0);
		endLine= MAKE_POINT<double>(0,0,0) + MAKE_VECTOR<double>(0, hLineLenght, 0);
		do
		{
			glVertex3d( beginLine.x(), beginLine.y(), beginLine.z()  );
			glVertex3d( endLine.x(), endLine.y(), endLine.z() );

			beginLine.x() += lineOffset;
			endLine.x() += lineOffset;
		}
		while ( beginLine.x() < to.x()-from.x() );

		//render horizontal lines
		beginLine= MAKE_POINT<double>(0,0,0);
		endLine= MAKE_POINT<double>(0,0,0) + MAKE_VECTOR<double>( vLineLenght, 0, 0);
		do
		{
			glVertex3d( beginLine.x(), beginLine.y(), beginLine.z()  );
			glVertex3d( endLine.x(), endLine.y(), endLine.z() );

			beginLine.y() += lineOffset;
			endLine.y() += lineOffset;
		}
		while ( beginLine.y() < to.y()-from.y() );

	glEnd();

	glPopMatrix();

	if ( useBlending ) glEnable( GL_BLEND ); else glDisable( GL_BLEND );
}

