#include "StdAfx.h"
#include "ColladaNode.h"



namespace lib_geo
{


void ColladaNode::UpdateTransmat(void)
{
	const lm::vec3f& ax = m_Transform.m_RotX.m_Axis;
	const lm::vec3f& ay = m_Transform.m_RotY.m_Axis;
	const lm::vec3f& az = m_Transform.m_RotZ.m_Axis;
	float rx = m_Transform.m_RotX.m_Angle * (float)M_PI / 180.0f;
	float ry = m_Transform.m_RotY.m_Angle * (float)M_PI / 180.0f;
	float rz = m_Transform.m_RotZ.m_Angle * (float)M_PI / 180.0f;

	float sx = m_Transform.m_Scale.x;
	float sy = m_Transform.m_Scale.y;
	float sz = m_Transform.m_Scale.z;

	lm::matrix4f mrx = lm::matrix4f::get_rotate( ax , rx );
	lm::matrix4f mry = lm::matrix4f::get_rotate( ay , ry );
	lm::matrix4f mrz = lm::matrix4f::get_rotate( az , rz );
	lm::matrix4f mt  = lm::matrix4f::get_translate( m_Transform.m_Trans );
	lm::matrix4f ms  = lm::matrix4f::get_scale( sx , sy , sz );

	m_TransMat = ms * mrx * mry * mrz * mt;

	if( m_Parent != NULL )
	{
		if( m_Parent->m_Type == m_Type )
		{
			m_TransMat = m_TransMat * m_Parent->m_TransMat;
		}
	}

	for( size_t i = 0 ; i < m_Childs.size() ; ++i )
		m_Childs[i].UpdateTransmat();
}

void ColladaNode::InitializeInvmat(void)
{
	m_TransMatIniInv = m_TransMat;
	m_TransMatIniInv.invert();

	for( size_t i = 0 ; i < m_Childs.size() ; ++i )
		m_Childs[i].InitializeInvmat();
}

void ColladaNode::SetParent(ColladaNode* parent)
{
	m_Parent = parent;
	for( size_t i = 0 ; i < m_Childs.size() ; ++i )
		m_Childs[i].SetParent(this);
}

void ColladaNode::ApplyTransMat(lm::vec3f& v) const
{
	v = v * m_TransMat;
}

void ColladaNode::ApplyNormalTransMat(lm::vec3f& v) const
{
	lm::matrix4f m = m_TransMat;
	m(3,0) = 0.0f;
	m(3,1) = 0.0f;
	m(3,2) = 0.0f;
	m(0,3) = 0.0f;
	m(1,3) = 0.0f;
	m(2,3) = 0.0f;
	v = v * m;
}


}
