/**
*
* \file Tools_Colour.cpp
*
* Created by Kevin Lea - 24/01/2003 11:38:11
*
* Copyright (C) 2002 Rebellion, All Rights Reserved.
*
* \brief
*
**/

#include "Core/Asura.h"

#include "Misc/Tools_Colour.h"

#include "Core/Asura_Maths.h"
#include "Debugging/Asura_Assert.h"

void Tools_Colour_RGB::ToHSV(Tools_Colour_HSV& xHSV) const
{
	float fMax = Asura_Maths::Max( Asura_Maths::Max( m_fR, m_fG ), m_fB );
	float fMin = Asura_Maths::Min( Asura_Maths::Min( m_fR, m_fG ), m_fB );
		
	xHSV.m_fV = fMax / 255.0f;
	
	if (fMax > 0.0f)
	{
		xHSV.m_fS = (fMax - fMin) / fMax;

		if (xHSV.m_fS > 0.0f)
		{
			if (m_fR == fMax)
			{
				xHSV.m_fH = (m_fG - m_fB) / (fMax - fMin);
			}
			else if (m_fG == fMax)
			{
				xHSV.m_fH = 2.0f + (m_fB - m_fR) / (fMax - fMin);
			}
			else
			{
				xHSV.m_fH = 4.0f + (m_fR - m_fG) / (fMax - fMin);
			}

			xHSV.m_fH /= 6.0f;

			if (xHSV.m_fH < 0.0f)
			{
				xHSV.m_fH += 1.0f;

			}
		}
		else
		{
			xHSV.m_fH = 0.0f;
		}

	}
	else
	{
		xHSV.m_fS = 0.0f;
		xHSV.m_fH = 0.0f;
	}

	xHSV.m_fH *= 100.0f;
	xHSV.m_fS *= 100.0f;
	xHSV.m_fV *= 100.0f;
}
	
void Tools_Colour_HSV::ToRGB(Tools_Colour_RGB& xRGB) const
{
	if (m_fV == 0.0f)
	{
		xRGB.m_fR = 0.0f;
		xRGB.m_fG = 0.0f;
		xRGB.m_fB = 0.0f;
	}
	else if (m_fS == 0.0f)
	{
		xRGB.m_fR = m_fV * 2.55f;
		xRGB.m_fG = m_fV * 2.55f;;
		xRGB.m_fB = m_fV * 2.55f;;
	}
	else
	{
		float fH = (m_fH >= 100.0f) ? 0.0f : (m_fH/100.0f);
		
		int i = Asura_Maths::FloatToInt_Chop(fH*6.0f);
		float f = fH * 6.0f - (float)i;

		float fP = m_fV * (1.0f - m_fS/100.0f);
		float fQ = m_fV * (1.0f - m_fS/100.0f * f);
		float fT = m_fV * (1.0f - m_fS/100.0f * (1.0f - f));

		switch(i)
		{
			case 0:
			{
				xRGB.m_fR = m_fV;
				xRGB.m_fG = fT;
				xRGB.m_fB = fP;
				break;
			}
			case 1:
			{
				xRGB.m_fR = fQ;
				xRGB.m_fG = m_fV;
				xRGB.m_fB = fP;
				break;
			}
			case 2:
			{
				xRGB.m_fR = fP;
				xRGB.m_fG = m_fV;
				xRGB.m_fB = fT;
				break;
			}
			case 3:
			{
				xRGB.m_fR = fP;
				xRGB.m_fG = fQ;
				xRGB.m_fB = m_fV;
				break;
			}
			case 4:
			{
				xRGB.m_fR = fT;
				xRGB.m_fG = fP;
				xRGB.m_fB = m_fV;
				break;
			}
			case 5:
			{
				xRGB.m_fR = m_fV;
				xRGB.m_fG = fP;
				xRGB.m_fB = fQ;
				break;
			}
			default:
			{
				Asura_Assert( false, "Colour values out of range?" );
				return;
			}

		}
		xRGB.m_fR *= 2.55f;
		xRGB.m_fG *= 2.55f;
		xRGB.m_fB *= 2.55f;

	}
}
