#include "StdAfx.h"
#include "CrossSectionRender.h"

#include <GLUtility/IndexColor.h>

#include <C2/gl/OpenGLUT/OpenGlutStringExt.h>

using namespace geom;



void CrossSectionRender::DrawAllGeomCsLengthInfo(std::vector<geom::MeshBuf*>& meshes)
{
	glColor3d(0.5, 1, 1);

	for (MeshBuf* mbuf : meshes)
	{
		DrawCsLengthInfo(mbuf->m_CrossSection);

		for (const lib_geo::CrossSection& cs : mbuf->m_CrossSectionLog)
		{
			DrawCsLengthInfo(cs);
		}
	}
}

void CrossSectionRender::DrawCsLengthInfo(const lib_geo::CrossSection& cs)
{
	const CrossSectionConfig& cs_config = m_Scene->m_CrossSectionConfig;
	bool show_len = cs_config.m_EnableShowLength;
	bool show_chlen = cs_config.m_EnableShowCHLength && cs_config.m_EnableConvexHull;

	for (const lib_geo::CrossSectionUnit& csu : cs.m_Sections)
	{
		std::ostringstream s;
		if (show_len && show_chlen)
			s << csu.m_Length << " , " << csu.m_ConvexLength;
		else if (show_len)
			s << csu.m_Length;
		else
			s << csu.m_ConvexLength;

		glutBitmapString3f(csu.m_Range.max_point(), s.str().c_str());
	}
}

void CrossSectionRender::DrawAllGeomCsConvexHull(std::vector<geom::MeshBuf*>& meshes)
{
	const CrossSectionConfig& cs_config = m_Scene->m_CrossSectionConfig;

	for (MeshBuf* mbuf : meshes)
	{
		GeomObject* obj = mbuf->GetParent();

		if (cs_config.m_EnableConvexHull)
		{
			glColor3d(0.5, 1, 1);
			DrawCsConvexHull(mbuf->m_CrossSection);
		}

		for (const lib_geo::CrossSection& cs : mbuf->m_CrossSectionLog)
		{
			if (cs_config.m_EnableConvexHull)
			{
				glColor3d(0.5, 1, 1);
				DrawCsConvexHull(cs);
			}

			lgr::color4f c;
			if (cs_config.m_MultiColor)
				c = IndexColor::GetColor(mbuf->m_WholeIndex);
			else
				c.set(1.0, 0.0, 0.0, 1.0);

			c *= 0.9f;

			glColor3fv(c.v());

			DrawCrossSectinPath(cs);
		}
	}
}

void CrossSectionRender::DrawCsConvexHull(const lib_geo::CrossSection& cs)
{
	for (const lib_geo::CrossSectionUnit& csu : cs.m_Sections)
	{
		glBegin(GL_LINE_LOOP);
		for (const lm::vec3f& v : csu.m_ConvexVerts)
		{
			glVertex3fv(v.v());
		}
		glEnd();
	}
}

void CrossSectionRender::DrawCrossSectinPath(const lib_geo::CrossSection& cs)
{
	for (const lib_geo::CrossSectionUnit& csu : cs.m_Sections)
	{
		glBegin(GL_LINES);
		for (const lib_geo::SectionSegment& seg : csu.m_Segments)
		{
			glVertex3fv(seg.p0.v());
			glVertex3fv(seg.p1.v());
		}
		glEnd();
	}
}
