#include "BVHBottom.h"

using namespace VRUT;

float BVHBottom::GetSubtreeCost(int index) const
{
	if (nodes[index].offset < 0)
	{ 
		// interior node 
		BVHNode & left = nodes[nodes[index].t];
		BVHNode & right = nodes[nodes[index].t + 1];
		float sa = nodes[index].box.SurfaceArea();
		float leftCost = sa != 0.0f ? left.box.SurfaceArea() / sa * GetSubtreeCost(nodes[index].t) : 0.0f;
		float rightCost = sa != 0.0f ? right.box.SurfaceArea() / sa * GetSubtreeCost(nodes[index].t+1) : 0.0f;
		return CT + leftCost + rightCost; 
	} 
	else 
	{ 
		// leaf node
		return CI * nodes[index].t; 
	}
}

void BVHBottom::GetVerticesAt(const int index, Vector3 & v1, Vector3 & v2, Vector3 & v3) const
{
	v1 = triangleCols[index].v1;
	v2 = triangleCols[index].e21 + triangleCols[index].v1;
	v3 = triangleCols[index].v1  - triangleCols[index].e13;
}

void BVHBottom::GetTextureCoordsAt(const int index, Vector2 *& texCoords1, Vector2 *& texCoords2, Vector2 *& texCoords3) const
{
	texCoords1 = const_cast<Vector2*>(&triangleTexs[index].texCoord1);
	texCoords2 = const_cast<Vector2*>(&triangleTexs[index].texCoord2);
	texCoords3 = const_cast<Vector2*>(&triangleTexs[index].texCoord3);
}

void BVHBottom::GetNormalAtUnnormalized(const int index, const float u, const float v, Vector3 & normal) const
{
	if ((triangleNorms[index].n1.x == 0) && (triangleNorms[index].n1.y == 0) && (triangleNorms[index].n1.z == 0))
		normal = triangleNorms[index].n2;
	else
		normal = (u * triangleNorms[index].n1 + (1 - u - v) * triangleNorms[index].n2 + v * triangleNorms[index].n3);
}
