
/*
-----------------------------------------------------------------------------
This source file is part of GIMPACT Library.

For the latest info, see http://gimpact.sourceforge.net/

Copyright (c) 2006 Francisco Leon. C.C. 80087371.
email: projectileman@yahoo.com

 This library is free software; you can redistribute it and/or
 modify it under the terms of EITHER:
   (1) The GNU Lesser General Public License as published by the Free
       Software Foundation; either version 2.1 of the License, or (at
       your option) any later version. The text of the GNU Lesser
       General Public License is included with this library in the
       file GIMPACT-LICENSE-LGPL.TXT.
   (2) The BSD-style license that is included with this library in
       the file GIMPACT-LICENSE-BSD.TXT.

 This library 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 files
 GIMPACT-LICENSE-LGPL.TXT and GIMPACT-LICENSE-BSD.TXT for more details.

-----------------------------------------------------------------------------
*/

#include "GIMPACT/gim_trimesh.h"


void ray_triangle_intersection_new (float * origin, float * dir, float * v1, float * v2, float * v3, float * plane, float *pout, 
					float * u, float * v, float * tparam, float tmax, char * intersect);

//! Trimesh Ray Collisions
/*!

\param trimesh
\param contact
\return 1 if the ray collides, else 0
*/
int gim_trimesh_ray_collision(GIM_TRIMESH * trimesh,vec3f origin,vec3f dir, GREAL tmax, GIM_TRIANGLE_RAY_CONTACT_DATA * contact)
{
    GDYNAMIC_ARRAY collision_result;
	GIM_CREATE_BOXQUERY_LIST(collision_result);

	gim_aabbset_ray_collision(origin,dir,tmax,&trimesh->m_aabbset,&collision_result);

	if(collision_result.m_size==0)
	{
	    GIM_DYNARRAY_DESTROY(collision_result);
	    return 0;
	}

	//collide triangles

	GUINT32 * boxesresult = GIM_DYNARRAY_POINTER(GUINT32,collision_result);
	GIM_TRIANGLE_DATA * tridata =  (GIM_TRIANGLE_DATA*)GIM_ALLOCA16(sizeof(GIM_TRIANGLE_DATA));
	vec3f pout;
	GREAL tparam,u,v;
	char does_intersect;

	gim_trimesh_locks_work_data(trimesh);

	for(unsigned int i=0;i<collision_result.m_size;i++)
	{
		gim_trimesh_get_triangle_data(trimesh,boxesresult[i],tridata);

		ray_triangle_intersection_new(origin,dir,tridata->m_vertices[0],tridata->m_vertices[1],tridata->m_vertices[2],tridata->m_planes.m_planes[0],pout,&u,&v,&tparam,tmax,&does_intersect);
		if(does_intersect) {
		    contact->tparam = tparam;
		    contact->u = u;
		    contact->v = v;
		    contact->m_face_id = boxesresult[i];
		    VEC_COPY(contact->m_point,pout);
		    VEC_COPY(contact->m_normal,tridata->m_planes.m_planes[0]);

		    gim_trimesh_unlocks_work_data(trimesh);
            GIM_DYNARRAY_DESTROY(collision_result);
		    return 1;
		}
	}

	gim_trimesh_unlocks_work_data(trimesh);
	GIM_DYNARRAY_DESTROY(collision_result);
	return 0;//no collisiion
}


//! Trimesh Ray Collisions closest
/*!
Find the closest primitive collided by the ray
\param trimesh
\param contact
\return 1 if the ray collides, else 0
*/

// New collision routine, we get rid of those stupid macros.
// Uses vdet for fast determinant

#ifdef PSP_GIMPACT_OPT
void ray_triangle_intersection_new (float * origin, float * dir, float * v1, float * v2, float * v3, float * plane, float *pout, 
					float * u, float * v, float * tparam, float tmax, char * intersect) {
	float dotp;
	__asm__ volatile (
	"ulv.q     R300, %1\n"  //plane R300
	"lv.s      S001, %2\n lv.s  S011, 4+%2 \n lv.s  S021, 8+%2\n"   //dir R001
	"vdot.t    S033, R300, R001[-x,-y,-z]\n"    // dotdir S033
	"mfv       %0, S033\n"
	:"=r"(dotp): "m"(plane[0]),"m"(dir[0]):"$f12");
	if (dotp < PLANEDIREPSILON) { *intersect = 0; return; }
	
	__asm__ volatile (
	"lv.s      S002, %1\n lv.s  S012, 4+%1 \n lv.s  S022, 8+%1\n"   //origin R002
	"vone.s    S032\n vneg.s S032,S032\n"
	"vdot.q    S023, R300, R002\n"
	"vrcp.s    S033, S033\n"
	"vmul.s    S033, S033, S023\n"
	"sv.s      S033, %0\n"
	:"=m"(*tparam): "m"(origin[0]));
	if (*tparam < -G_EPSILON or *tparam > tmax+G_EPSILON) { *intersect = 0; return; }

	__asm__ volatile (
	"vscl.t    R003, R001, S033\n"
	"vadd.t    R003, R003, R002\n"
	"sv.s  S003, %0\n sv.s  S013, 4+%0\n sv.s  S023, 8+%0\n"
	:"=m"(pout[0]));

	__asm__ volatile (
	"lv.q  R000, %0\n"
	"lv.q  R001, %1\n"
	"lv.q  R002, %2\n"

	"vsub.t    R201, R001, R000\n"  // R201 axis1
	"vsub.t    R202, R002, R000\n"  // R202 axis2
	"vsub.t    R200, R003, R000\n"  // R200 vecproj

	"vabs.t    R103, R300\n"
	::"m"(v1[0]),"m"(v2[0]),"m"(v3[0]));

	__asm__ volatile (".set push\n .set noreorder\n vcmp.s  GT, S103, S113\n bvf 0,middle_bl_1_\n .set pop\n");
	__asm__ volatile (".set push\n .set noreorder\n vcmp.s  GT, S103, S123\n bvf 0,cont_bl__1__\n nop\n .set pop\n");
			__asm__ volatile (
			"vmov.t    R200, R200[y,z,0]\n"
			"vmov.t    R201, R201[y,z,0]\n"
			"vmov.t    R202, R202[y,z,0]\n"
			);
	__asm__ volatile ("j cont_bl__1__\n nop\n");
	__asm__ volatile ("middle_bl_1_:\n");
	
	__asm__ volatile (".set push\n .set noreorder\n vcmp.s  GT, S123, S113\n bvt 0,cont_bl__1__\n nop\n .set pop\n");
			__asm__ volatile (
			"vmov.t    R200, R200[x,z,0]\n"
			"vmov.t    R201, R201[x,z,0]\n"
			"vmov.t    R202, R202[x,z,0]\n"
			);
	__asm__ volatile ("cont_bl__1__:\n");

	__asm__ volatile (  // vecproj is located in R200.p and axis1 in R201.p and R202.p in axis2
	"vdet.p    S310, R201, R202\n"
//	"vdet.p    S311, R202, R201\n"  // Is the same but *-1
	"vneg.s    S311, S310\n"
	"vrcp.p    C310, C310\n"
	"vdet.p    S300, R200, R202\n"
	"vdet.p    S301, R200, R201\n"
	"vmul.p    C300, C300, C310\n"
	"sv.s      S300, %0\n"
	"sv.s      S301, %1\n"
	:"=m"(*u),"=m"(*v));
	
	if (*u < -G_EPSILON or *v < -G_EPSILON or (*u+*v)>1.0f+G_EPSILON) { *intersect = 0; return; }
	*intersect = 1;
}
#else
void ray_triangle_intersection_new (float * origin, float * dir, float * v1, float * v2, float * v3, float * plane, float *pout, 
					float * u, float * v, float * tparam, float tmax, char * intersect) {

	float dotp = -(plane[0]*dir[0] + plane[1]*dir[1] + plane[2]*dir[2]);
	if (dotp < PLANEDIREPSILON) { *intersect = 0; return; }
	float planedist = plane[0]*origin[0] + plane[1]*origin[1] + plane[2]*origin[2] - plane[3];
	*tparam = planedist/dotp;

	if (*tparam < -G_EPSILON or *tparam > tmax+G_EPSILON) { *intersect = 0; return; }

	pout[0] = origin[0]+dir[0]*(*tparam);
	pout[1] = origin[1]+dir[1]*(*tparam);
	pout[2] = origin[2]+dir[2]*(*tparam);

	float axis1[4], axis2[4], vecproj[4];
	axis1[0] = v2[0] - v1[0];       axis1[1] = v2[1] - v1[1];     axis1[2] = v2[2] - v1[2];
	axis2[0] = v3[0] - v1[0];       axis2[1] = v3[1] - v1[1];     axis2[2] = v3[2] - v1[2];
	vecproj[0] = pout[0] - v1[0]; vecproj[1] = pout[1] - v1[1]; vecproj[2] = pout[2] - v1[2];

	int i0,i1;
	float A[4] = {fabs(plane[0]),fabs(plane[1]),fabs(plane[2]),0};
	if(A[0]>A[1]) {
		if(A[0]>A[2]) {i0=1; i1=2;}
		else {i0=0;i1=1;}
	}else{
		if(A[2]>A[1]) {i0=0;i1=1;}
		else {i0=0;i1=2;}
	}

	*u = (vecproj[i1]*axis2[i0]-vecproj[i0]*axis2[i1]) / (axis1[i1]*axis2[i0]-axis1[i0]*axis2[i1]);
	*v = (vecproj[i1]*axis1[i0]-vecproj[i0]*axis1[i1]) / (axis2[i1]*axis1[i0]-axis2[i0]*axis1[i1]);
	if (*u < -G_EPSILON or *v < -G_EPSILON or (*u+*v)>1.0f+G_EPSILON) { *intersect = 0; return; }
	*intersect = 1;
}
#endif

int gim_trimesh_ray_closest_collision(GIM_TRIMESH * trimesh,vec3f origin,vec3f dir, GREAL tmax, GIM_TRIANGLE_RAY_CONTACT_DATA * contact)
{
    GDYNAMIC_ARRAY collision_result;
	GIM_CREATE_BOXQUERY_LIST(collision_result);

	gim_aabbset_ray_collision(origin,dir,tmax,&trimesh->m_aabbset,&collision_result);

	if(collision_result.m_size==0)
	{
	    GIM_DYNARRAY_DESTROY(collision_result);
	    return 0;
	}

	//collide triangles

	GUINT32 * boxesresult = GIM_DYNARRAY_POINTER(GUINT32,collision_result);
	GIM_TRIANGLE_DATA * tridata =  (GIM_TRIANGLE_DATA*)GIM_ALLOCA16(sizeof(GIM_TRIANGLE_DATA));
	vec3f pout;
	GREAL tparam,u,v;
	char does_intersect;
	contact->tparam = tmax + 0.1f;

	gim_trimesh_locks_work_data(trimesh);

	for(unsigned int i=0;i<collision_result.m_size;i++) {
		gim_trimesh_get_triangle_data(trimesh,boxesresult[i],tridata);

		ray_triangle_intersection_new(origin,dir,tridata->m_vertices[0],tridata->m_vertices[1],tridata->m_vertices[2],tridata->m_planes.m_planes[0],pout,&u,&v,&tparam,tmax,&does_intersect);
		if(does_intersect && (tparam < contact->tparam)) {
		    contact->tparam = tparam;
		    contact->u = u;
		    contact->v = v;
		    contact->m_face_id = boxesresult[i];
		    VEC_COPY(contact->m_point,pout);
		    VEC_COPY(contact->m_normal,tridata->m_planes.m_planes[0]);
		}
	}

	gim_trimesh_unlocks_work_data(trimesh);
	GIM_DYNARRAY_DESTROY(collision_result);
	if(contact->tparam > tmax) return 0;
	return 1;
}

