//==============================================================================
/*! \file
 * OpenMesh Toolkit for mesh analysis    \n
 * Copyright (c) 2010 by Rostislav Hulik     \n
 *
 * Author:  Rostislav Hulik, rosta.hulik@gmail.com  \n
 * Date:    2010/3/2                          \n
 *
 * This file is part of software developed for support of Rostislav Hulik's dissertation thesis at dcgm-robotics@FIT group.
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this file.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Description:
 * - Class representing AABB in R-tree structure
 */

#include <OMToolkit\OMTriBSPTreeAABB.h>

namespace OMToolkit {

TreeElement::TreeElement(int id)
{
	left = NULL;
	right = NULL;
	_id = id;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tests intersection between ray and aabb
// @param origin Ray origin - intersection is computed also in inverse direction
// @param vector Ray direction
// @param cube Tree element (aabb)
// @return True if aabb is hit
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool TreeElement::intersects(OMRay &ray)
{
	ScalarT interval_min = 0;
	ScalarT interval_max = FLT_MAX;

	int posneg = ray.m_posneg[0];

	float t0 = (aabb[posneg][0] - ray.m_origin[0]) * ray.m_inv_dir[0];
	float t1 = (aabb[1-posneg][0] - ray.m_origin[0]) * ray.m_inv_dir[0];
		
	if (t0 > interval_min) interval_min = t0;
	if (t1 < interval_max) interval_max = t1;
	if (interval_min > interval_max) return false;
	
	posneg = ray.m_posneg[1];
	t0 = (aabb[posneg][1] - ray.m_origin[1]) * ray.m_inv_dir[1];
	t1 = (aabb[1-posneg][1] - ray.m_origin[1]) * ray.m_inv_dir[1];
	
	if (t0 > interval_min) interval_min = t0;
	if (t1 < interval_max) interval_max = t1;
	if (interval_min > interval_max) return false;


	posneg = ray.m_posneg[2];
	t0 = (aabb[posneg][2] - ray.m_origin[2]) * ray.m_inv_dir[2];
	t1 = (aabb[1-posneg][2] - ray.m_origin[2]) * ray.m_inv_dir[2];
	
	if (t0 > interval_min) interval_min = t0;
	if (t1 < interval_max) interval_max = t1;
	return (interval_min <= interval_max);
}

}