// Helper.cpp: implementation of the CHelper class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CryViewer.h"
#include "Helper.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

#pragma warning( disable : 4244)

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CHelper::CHelper() : BaseObj()
{
	memset(&chunk,0,sizeof(chunk));
	PointPen=CreatePen(PS_SOLID,0,RGB(0,255,0));
	DummyPen=CreatePen(PS_SOLID,0,RGB(0,255,255));
}

CHelper::~CHelper()
{
	DeleteObject(PointPen);
	DeleteObject(DummyPen);
}

RECT CHelper::Paint(HDC hdc, DispOptions &opt)
{
	CRect r;

	const int radius=5;
	CryPoint3 p=CryPoint3(0,0,0);
	CryPoint3 pp=p*opt.tm;

	r.top=r.bottom=pp.y;
	r.left=r.right=pp.x;
	r.top-=radius;
	r.bottom+=radius;
	r.left-=radius;
	r.right+=radius;

	HGDIOBJ  old_pen;
	switch(chunk.type)
	{
	case HP_POINT:
		old_pen=SelectObject(hdc,PointPen);
		MoveToEx(hdc,pp.x, pp.y-radius,NULL);
		LineTo(hdc,pp.x, pp.y+radius);
		MoveToEx(hdc,pp.x-radius, pp.y,NULL);
		LineTo(hdc,pp.x+radius, pp.y);
		
		break;

	case HP_DUMMY:
		{
			old_pen=SelectObject(hdc,DummyPen);
			CryPoint3 dx,dy,dz;
			dx=dy=dz=chunk.size*0.5;
			dx.y=dx.z=dy.x=dy.z=dz.x=dz.y=0.0f;
			CryPoint3 np[8];
			np[0]=p-dx-dy-dz;
			np[1]=p+dx-dy-dz;
			np[2]=p+dx+dy-dz;
			np[3]=p-dx+dy-dz;
			np[4]=p-dx-dy+dz;
			np[5]=p+dx-dy+dz;
			np[6]=p+dx+dy+dz;
			np[7]=p-dx+dy+dz;
			for(int i=0;i<8;i++)
			{
				np[i]=np[i]*opt.tm;
				r.top		=min(r.top,		np[i].y);
				r.bottom	=max(r.bottom,	np[i].y);
				r.left		=min(r.left,	np[i].x);
				r.right		=max(r.right,	np[i].x);
			}

			MoveToEx(hdc,np[0].x, np[0].y,NULL);
			LineTo(hdc  ,np[1].x, np[1].y);
			LineTo(hdc  ,np[2].x, np[2].y);
			LineTo(hdc  ,np[3].x, np[3].y);
			LineTo(hdc  ,np[0].x, np[0].y);
			LineTo(hdc  ,np[4].x, np[4].y);
			LineTo(hdc  ,np[5].x, np[5].y);
			LineTo(hdc  ,np[6].x, np[6].y);
			LineTo(hdc  ,np[7].x, np[7].y);
			LineTo(hdc  ,np[4].x, np[4].y);
			MoveToEx(hdc,np[1].x, np[1].y,NULL);
			LineTo(hdc  ,np[5].x, np[5].y);
			MoveToEx(hdc,np[2].x, np[2].y,NULL);
			LineTo(hdc  ,np[6].x, np[6].y);
			MoveToEx(hdc,np[3].x, np[3].y,NULL);
			LineTo(hdc  ,np[7].x, np[7].y);
		}
		break;
	}

	SelectObject(hdc,old_pen);
	return r;
}

bool CHelper::Load(FILE *f, long pos)
{
	if(fseek(f,pos,SEEK_SET)) return true;

	int res=fread(&chunk,sizeof(chunk),1,f);
	if(res!=1) return true;
	
	if(chunk.chdr.ChunkType != ChunkType_Helper || chunk.chdr.ChunkVersion != HELPER_CHUNK_DESC_VERSION)
	{
		memset(&chunk,0,sizeof(chunk));
		return true;
	}

	hdr=chunk.chdr;

	return false;
}
