/*
Copyright (C) 1996-1997 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
// world.c -- world query functions

#include "quakedef.h"
#include "ds.h"

/*

entities never clip against themselves, or their owner

line of sight checks trace->crosscontent, but bullets don't

*/


typedef struct
{
	fixed_point3		boxmins, boxmaxs;// enclose the test object along entire move
	fixed_point		*mins, *maxs;	// size of the moving object
	fixed_point3		mins2, maxs2;	// size when clipping against mosnters
	fixed_point		*start, *end;
	trace_t		trace;
	int			type;
	edict_t		*passedict;
} moveclip_t;


int SV_HullPointContents (hull_t *hull, int num, vec3_t p);
int SV_HullPointContentsFP (hull_t *hull, int num, fixed_point *p);

/*
===============================================================================

HULL BOXES

===============================================================================
*/


static	hull_t		box_hull;
static	dclipnode_t	box_clipnodes[6];
static	mplane_t	box_planes[6];

mleaf_t *Mod_PointInLeaf (vec3_t p, model_t *model) __attribute__((section(".itcm"), long_call));
mleaf_t *Mod_PointInLeaf (vec3_t p, model_t *model)
{
	mnode_t		*node;
	int			f_d;
	mplane_t	*plane;
	
	if (!model || !model->nodes)
		Sys_Error ("Mod_PointInLeaf: bad model");

	node = model->nodes;
	
//	fixed_point f_p[3];
//	f_p[0] = p[0];
//	f_p[1] = p[1];
//	f_p[2] = p[2];

	int f_p[3];
	
	f_p[0] = float_to_fixed(p[0]);
	f_p[1] = float_to_fixed(p[1]);
	f_p[2] = float_to_fixed(p[2]);
	
	while (node->contents >= 0)
	{
		plane = node->plane;
		
//		f_d = ((long long)plane->normal[0].value * (long long)f_p[0].value
//						+ (long long)plane->normal[1].value * (long long)f_p[1].value
//						+ (long long)plane->normal[2].value * (long long)f_p[2].value) >> FP_SCALE_SHIFT;
		f_d =			(int)(((long long)plane->normal[0].value * (long long)f_p[0]) >> FP_SCALE_SHIFT)
						+ (int)(((long long)plane->normal[1].value * (long long)f_p[1]) >> FP_SCALE_SHIFT)
						+ (int)(((long long)plane->normal[2].value * (long long)f_p[2]) >> FP_SCALE_SHIFT);
						
		f_d -= plane->dist.value;
		
		if (f_d > 0)
			node = node->children[0];
		else
			node = node->children[1];			
	}
	
	return (mleaf_t *)node;
}


/*
===================
SV_InitBoxHull

Set up the planes and clipnodes so that the six floats of a bounding box
can just be stored out and get a proper hull_t structure.
===================
*/
void SV_InitBoxHull (void)
{
	int		i;
	int		side;

	box_hull.clipnodes = box_clipnodes;
	box_hull.planes = box_planes;
	box_hull.firstclipnode = 0;
	box_hull.lastclipnode = 5;

	for (i=0 ; i<6 ; i++)
	{
		box_clipnodes[i].planenum = i;
		
		side = i&1;
		
		box_clipnodes[i].children[side] = CONTENTS_EMPTY;
		if (i != 5)
			box_clipnodes[i].children[side^1] = i + 1;
		else
			box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
		
#ifdef USE_EXTRA_RAM
		byte_write(&box_planes[i].type, i >> 1);
#else
		box_planes[i].type = i>>1;
#endif
		box_planes[i].normal[i>>1] = 1.0f;
//		box_planes[i].bignormal[i>>1] = 1024;
	}
	
}


/*
===================
SV_HullForBox

To keep everything totally uniform, bounding boxes are turned into small
BSP trees instead of being compared directly.
===================
*/
hull_t	*SV_HullForBox (vec3_t mins, vec3_t maxs)
{
	box_planes[0].dist = maxs[0];
	box_planes[1].dist = mins[0];
	box_planes[2].dist = maxs[1];
	box_planes[3].dist = mins[1];
	box_planes[4].dist = maxs[2];
	box_planes[5].dist = mins[2];

//	box_planes[0].bigdist = maxs[0] * 1024;
//	box_planes[1].bigdist = mins[0] * 1024;
//	box_planes[2].bigdist = maxs[1] * 1024;
//	box_planes[3].bigdist = mins[1] * 1024;
//	box_planes[4].bigdist = maxs[2] * 1024;
//	box_planes[5].bigdist = mins[2] * 1024;

	return &box_hull;
}



/*
================
SV_HullForEntity

Returns a hull that can be used for testing or clipping an object of mins/maxs
size.
Offset is filled in to contain the adjustment that must be added to the
testing object's origin to get a point to use with the returned hull.
================
*/
hull_t *SV_HullForEntity (edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset) __attribute__((section(".itcm"), long_call));
hull_t *SV_HullForEntity (edict_t *ent, vec3_t mins, vec3_t maxs, vec3_t offset)
{
	model_t		*model;
	vec3_t		size;
	vec3_t		hullmins, hullmaxs;
	hull_t		*hull;

// decide which clipping hull to use, based on the size
	if (ent->v.solid == SOLID_BSP)
	{	// explicit hulls in the BSP model
		if (ent->v.move_type.movetype != MOVETYPE_PUSH)
			Sys_Error ("SOLID_BSP without MOVETYPE_PUSH");

		model = sv.models[ (int)ent->v.modelindex ];

		if (!model || model->type != mod_brush)
			Sys_Error ("MOVETYPE_PUSH with a non bsp model");

		VectorSubtract (maxs, mins, size);
		if (size[0] < 3)
			hull = &model->hulls[0];
		else if (size[0] <= 32)
			hull = &model->hulls[1];
		else
			hull = &model->hulls[2];

// calculate an offset value to center the origin
		VectorSubtract (hull->clip_mins, mins, offset);
		VectorAdd (offset, ent->v.origin, offset);
	}
	else
	{	// create a temp hull from bounding box sizes

		VectorSubtract (ent->v.mins, maxs, hullmins);
		VectorSubtract (ent->v.maxs, mins, hullmaxs);
		hull = SV_HullForBox (hullmins, hullmaxs);
		
		VectorCopy (ent->v.origin, offset);
	}


	return hull;
}

hull_t *SV_HullForEntityFP (edict_t *ent, fixed_point3 mins, fixed_point3 maxs, fixed_point3 offset) __attribute__((section(".itcm"), long_call));
hull_t *SV_HullForEntityFP (edict_t *ent, fixed_point3 mins, fixed_point3 maxs, fixed_point3 offset)
{
	model_t		*model;
	vec3_t		size;
	vec3_t		hullmins, hullmaxs;
	hull_t		*hull;

// decide which clipping hull to use, based on the size
	if (ent->v.solid == SOLID_BSP)
	{	// explicit hulls in the BSP model
		if (ent->v.move_type.movetype != MOVETYPE_PUSH)
			Sys_Error ("SOLID_BSP without MOVETYPE_PUSH");

		model = sv.models[ (int)ent->v.modelindex ];

		if (!model || model->type != mod_brush)
			Sys_Error ("MOVETYPE_PUSH with a non bsp model");

		VectorSubtract (maxs, mins, size);
		if (size[0] < 3)
			hull = &model->hulls[0];
		else if (size[0] <= 32)
			hull = &model->hulls[1];
		else
			hull = &model->hulls[2];

// calculate an offset value to center the origin
		VectorSubtract (hull->clip_mins, mins, offset);
		VectorAdd (offset, ent->v.origin, offset);
	}
	else
	{	// create a temp hull from bounding box sizes

		VectorSubtract (ent->v.mins, maxs, hullmins);
		VectorSubtract (ent->v.maxs, mins, hullmaxs);
		hull = SV_HullForBox (hullmins, hullmaxs);
		
		VectorCopy (ent->v.origin, offset);
	}


	return hull;
}

/*
===============================================================================

ENTITY AREA CHECKING

===============================================================================
*/

typedef struct areanode_s
{
	int		axis;		// -1 = leaf node
	fixed_point	dist;
	struct areanode_s	*children[2];
	link_t	trigger_edicts;
	link_t	solid_edicts;
} areanode_t;

#define	AREA_DEPTH	4
#define	AREA_NODES	32

static	areanode_t	sv_areanodes[AREA_NODES];
static	int			sv_numareanodes;

/*
===============
SV_CreateAreaNode

===============
*/
areanode_t *SV_CreateAreaNode (int depth, vec3_t mins, vec3_t maxs)
{
	areanode_t	*anode;
	vec3_t		size;
	vec3_t		mins1, maxs1, mins2, maxs2;

	anode = &sv_areanodes[sv_numareanodes];
	sv_numareanodes++;

	ClearLink (&anode->trigger_edicts);
	ClearLink (&anode->solid_edicts);
	
	if (depth == AREA_DEPTH)
	{
		anode->axis = -1;
		anode->children[0] = anode->children[1] = NULL;
		return anode;
	}
	
	VectorSubtract (maxs, mins, size);
	if (size[0] > size[1])
		anode->axis = 0;
	else
		anode->axis = 1;
	
	anode->dist = 0.5 * (maxs[anode->axis] + mins[anode->axis]);
	VectorCopy (mins, mins1);	
	VectorCopy (mins, mins2);	
	VectorCopy (maxs, maxs1);	
	VectorCopy (maxs, maxs2);	
	
	maxs1[anode->axis] = mins2[anode->axis] = anode->dist;
	
	anode->children[0] = SV_CreateAreaNode (depth+1, mins2, maxs2);
	anode->children[1] = SV_CreateAreaNode (depth+1, mins1, maxs1);

	return anode;
}

/*
===============
SV_ClearWorld

===============
*/
void SV_ClearWorld (void)
{
	SV_InitBoxHull ();
	
	ds_memset (sv_areanodes, 0, sizeof(sv_areanodes));
	sv_numareanodes = 0;
	SV_CreateAreaNode (0, sv.worldmodel->mins, sv.worldmodel->maxs);
}


/*
===============
SV_UnlinkEdict

===============
*/
void SV_UnlinkEdict (edict_t *ent)
{
	if (!ent->area.prev)
		return;		// not linked in anywhere
	RemoveLink (&ent->area);
	ent->area.prev = ent->area.next = NULL;
}


/*
====================
SV_TouchLinks
====================
*/
void SV_TouchLinks ( edict_t *ent, areanode_t *node ) __attribute__((section(".itcm"), long_call));
void SV_TouchLinks ( edict_t *ent, areanode_t *node )
{
	link_t		*l, *next;
	edict_t		*touch;
	int			old_self, old_other;

// touch linked edicts
	for (l = node->trigger_edicts.next ; l != &node->trigger_edicts ; l = next)
	{
		next = l->next;
		touch = EDICT_FROM_AREA(l);
		if (touch == ent)
			continue;
		if (!touch->v.touch || touch->v.solid != SOLID_TRIGGER)
			continue;
		if (ent->v.absmin[0] > touch->v.absmax[0]
		|| ent->v.absmin[1] > touch->v.absmax[1]
		|| ent->v.absmin[2] > touch->v.absmax[2]
		|| ent->v.absmax[0] < touch->v.absmin[0]
		|| ent->v.absmax[1] < touch->v.absmin[1]
		|| ent->v.absmax[2] < touch->v.absmin[2] )
			continue;
		old_self = pr_global_struct->self;
		old_other = pr_global_struct->other;

		pr_global_struct->self = EDICT_TO_PROG(touch);
		pr_global_struct->other = EDICT_TO_PROG(ent);
		pr_global_struct->time = sv.time;
		PR_ExecuteProgram (touch->v.touch);

		pr_global_struct->self = old_self;
		pr_global_struct->other = old_other;
	}
	
// recurse down both sides
	if (node->axis == -1)
		return;
	
	if ( ent->v.absmax[node->axis] > node->dist )
		SV_TouchLinks ( ent, node->children[0] );
	if ( ent->v.absmin[node->axis] < node->dist )
		SV_TouchLinks ( ent, node->children[1] );
}


/*
===============
SV_FindTouchedLeafs

===============
*/
void SV_FindTouchedLeafs (edict_t *ent, mnode_t *node, fixed_point *f_absmin, fixed_point *f_absmax) __attribute__((section(".itcm"), long_call));
void SV_FindTouchedLeafs (edict_t *ent, mnode_t *node, fixed_point *f_absmin, fixed_point *f_absmax)
{
	mplane_t	*splitplane;
	mleaf_t		*leaf;
	int			sides;
	int			leafnum;

	if (node->contents == CONTENTS_SOLID)
		return;
	
// add an efrag if the node is a leaf

	if ( node->contents < 0)
	{
		if (ent->num_leafs == MAX_ENT_LEAFS)
			return;

		leaf = (mleaf_t *)node;
		leafnum = leaf - sv.worldmodel->leafs - 1;

		ent->leafnums[ent->num_leafs] = leafnum;
		ent->num_leafs++;			
		return;
	}
	
// NODE_MIXED

	splitplane = node->plane;
//	sides = BOX_ON_PLANE_SIDE(ent->v.absmin, ent->v.absmax, splitplane);
	sides = BOX_ON_PLANE_SIDE_FP(f_absmin, f_absmax, splitplane);
	
// recurse down the contacted sides
	if (sides & 1)
		SV_FindTouchedLeafs (ent, node->children[0], f_absmin, f_absmax);
		
	if (sides & 2)
		SV_FindTouchedLeafs (ent, node->children[1], f_absmin, f_absmax);
}

/*
===============
SV_LinkEdict

===============
*/
void SV_LinkEdict (edict_t *ent, qboolean touch_triggers)
{
	areanode_t	*node;

	if (ent->area.prev)
		SV_UnlinkEdict (ent);	// unlink from old position
		
	if (ent == sv.edicts)
		return;		// don't add the world

	if (ent->free)
		return;

// set the abs box

	{
		VectorAdd (ent->v.origin, ent->v.mins, ent->v.absmin);	
		VectorAdd (ent->v.origin, ent->v.maxs, ent->v.absmax);
	}

//
// to make items easier to pick up and allow them to be grabbed off
// of shelves, the abs sizes are expanded
//
	if ((int)ent->v.flags & FL_ITEM)
	{
		ent->v.absmin[0] = ent->v.absmin[0] - 15;
		ent->v.absmin[1] = ent->v.absmin[1] - 15;
		ent->v.absmax[0] = ent->v.absmax[0] + 15;
		ent->v.absmax[1] = ent->v.absmax[1] + 15;
	}
	else
	{	// because movement is clipped an epsilon away from an actual edge,
		// we must fully check even when bounding boxes don't quite touch
		ent->v.absmin[0] = ent->v.absmin[0] - 1;
		ent->v.absmin[1] = ent->v.absmin[1] - 1;
		ent->v.absmin[2] = ent->v.absmin[2] - 1;
		ent->v.absmax[0] = ent->v.absmax[0] + 1;
		ent->v.absmax[1] = ent->v.absmax[1] + 1;
		ent->v.absmax[2] = ent->v.absmax[2] + 1;
	}
	
// link to PVS leafs
	ent->num_leafs = 0;
	if (ent->v.modelindex)
	{
		fixed_point f_absmin[3], f_absmax[3];
		
		f_absmin[0] = ent->v.absmin[0];
		f_absmin[1] = ent->v.absmin[1];
		f_absmin[2] = ent->v.absmin[2];
		
		f_absmax[0] = ent->v.absmax[0];
		f_absmax[1] = ent->v.absmax[1];
		f_absmax[2] = ent->v.absmax[2];
		
		SV_FindTouchedLeafs (ent, sv.worldmodel->nodes, f_absmin, f_absmax);
	}

	if (ent->v.solid == SOLID_NOT)
		return;

// find the first node that the ent's box crosses
	node = sv_areanodes;
	while (1)
	{
		if (node->axis == -1)
			break;
		if (ent->v.absmin[node->axis] > node->dist)
			node = node->children[0];
		else if (ent->v.absmax[node->axis] < node->dist)
			node = node->children[1];
		else
			break;		// crosses the node
	}
	
// link it in	

	if (ent->v.solid == SOLID_TRIGGER)
		InsertLinkBefore (&ent->area, &node->trigger_edicts);
	else
		InsertLinkBefore (&ent->area, &node->solid_edicts);
	
// if touch_triggers, touch all entities at this node and decend for more
	if (touch_triggers)
		SV_TouchLinks ( ent, sv_areanodes );
}



/*
===============================================================================

POINT TESTING IN HULLS

===============================================================================
*/

#if	!id386

/*
==================
SV_HullPointContents

==================
*/
int SV_HullPointContents (hull_t *hull, int num, vec3_t p) __attribute__((section(".itcm"), long_call));
int SV_HullPointContents (hull_t *hull, int num, vec3_t p)
{
	int f_d;
	dclipnode_t	*node;
	mplane_t	*plane;
	
	int f_p[3];
	
	f_p[0] = float_to_fixed(p[0]);
	f_p[1] = float_to_fixed(p[1]);
	f_p[2] = float_to_fixed(p[2]);

	while (num >= 0)
	{
//		if (num < hull->firstclipnode || num > hull->lastclipnode)
//			Sys_Error ("SV_HullPointContents: bad node number");
	
		node = hull->clipnodes + num;
		plane = hull->planes + node->planenum;
		
		if (plane->type < 3)
		{
			f_d = f_p[plane->type] - plane->dist.value;
		}
		else
		{
//			f_d = DotProduct (plane->normal, f_p) - plane->dist;
			
			f_d = ((long long)plane->normal[0].value * (long long)f_p[0]
						+ (long long)plane->normal[1].value * (long long)f_p[1]
						+ (long long)plane->normal[2].value * (long long)f_p[2]) >> FP_SCALE_SHIFT;
			f_d -= plane->dist.value;
		}
		if (f_d < 0)
			num = node->children[1];
		else
			num = node->children[0];
	}
	
	return num;
}
int SV_HullPointContentsFP (hull_t *hull, int num, fixed_point *f_p) __attribute__((section(".itcm"), long_call));
int SV_HullPointContentsFP (hull_t *hull, int num, fixed_point *f_p)
{
//	float		d;
//	fixed_point f_d;
	int f_d;
	dclipnode_t	*node;
	mplane_t	*plane;
	
	int p[3];
	
	p[0] = f_p[0].value;
	p[1] = f_p[1].value;
	p[2] = f_p[2].value;

	while (num >= 0)
	{
//		if (num < hull->firstclipnode || num > hull->lastclipnode)
//			Sys_Error ("SV_HullPointContents: bad node number");
	
		node = hull->clipnodes + num;
		plane = hull->planes + node->planenum;
		
		if (plane->type < 3)
		{
			f_d = f_p[plane->type].value - plane->dist.value;
		}
		else
		{
//			f_d = DotProduct (plane->normal, f_p) - plane->dist;

			int n0 = plane->normal[0].value;
			int n1 = plane->normal[1].value;
			int n2 = plane->normal[2].value;
			
			f_d = ((long long)n0 * (long long)p[0]
						+ (long long)n1 * (long long)p[1]
						+ (long long)n2 * (long long)p[2]) >> FP_SCALE_SHIFT;
			f_d -= plane->dist.value;
		}
		if (f_d < 0)
			num = node->children[1];
		else
			num = node->children[0];
	}
	
	return num;
}
//int SV_HullPointContents (hull_t *hull, int num, vec3_t p)
//{
//	float		d;
//	dclipnode_t	*node;
//	mplane_t	*plane;
//	
////	int big_p[3];
////	big_p[0] = p[0] * 1024;
////	big_p[1] = p[1] * 1024;
////	big_p[2] = p[2] * 1024;
//
//	while (num >= 0)
//	{
//		if (num < hull->firstclipnode || num > hull->lastclipnode)
//			Sys_Error ("SV_HullPointContents: bad node number");
//	
//		node = hull->clipnodes + num;
//		plane = hull->planes + node->planenum;
//		
//		if (plane->type < 3)
//			d = p[plane->type] - plane->dist;
////			d = p[plane->type] - (plane->bigdist >> 10);
//		else
//		{
//			d = DotProduct (plane->normal, p);
//			d -= plane->dist;
////			d = DotProduct (plane->normal, p) - (plane->bigdist >> 10);
////			d = (DotProductII(plane->bignormal, big_p) - plane->bigdist) >> 10;
//		}
//		if (d < 0)
//			num = node->children[1];
//		else
//			num = node->children[0];
//	}
//	
//	return num;
//}


#endif	// !id386


/*
==================
SV_PointContents

==================
*/
int SV_PointContents (vec3_t p)
{
	int		cont;

	cont = SV_HullPointContents (&sv.worldmodel->hulls[0], 0, p);
	if (cont <= CONTENTS_CURRENT_0 && cont >= CONTENTS_CURRENT_DOWN)
		cont = CONTENTS_WATER;
	return cont;
}

int SV_PointContentsFP (fixed_point *p)
{
	int		cont;

	cont = SV_HullPointContentsFP (&sv.worldmodel->hulls[0], 0, p);
	if (cont <= CONTENTS_CURRENT_0 && cont >= CONTENTS_CURRENT_DOWN)
		cont = CONTENTS_WATER;
	return cont;
}

int SV_TruePointContents (vec3_t p)
{
	return SV_HullPointContents (&sv.worldmodel->hulls[0], 0, p);
}

//===========================================================================

/*
============
SV_TestEntityPosition

This could be a lot more efficient...
============
*/
edict_t	*SV_TestEntityPosition (edict_t *ent)
{
	trace_t	trace;

	trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, ent->v.origin, 0, ent);
	
	if (trace.startsolid)
		return sv.edicts;
		
	return NULL;
}


/*
===============================================================================

LINE TESTING IN HULLS

===============================================================================
*/

// 1/32 epsilon to keep floating point happy
#define	DIST_EPSILON	(0.03125)
const int DIST_EPSILON_FP = (int)(0.03125 * FP_SCALE);

/*
==================
SV_RecursiveHullCheck

==================
*/

unsigned int min_stack_pointer = 0x0b000000 + 16 * 1024;

qboolean SV_NonRecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace);

int hull_depth = 0;
#if 0
void recursive_hull_fp_convert(fixed_point *f_p1, fixed_point *f_p2, vec3_t p1, vec3_t p2)__attribute__ ((no_instrument_function));

inline void recursive_hull_fp_convert(fixed_point *f_p1, fixed_point *f_p2, vec3_t p1, vec3_t p2)
{
//	f_p1[0] = p1[0];
//	f_p1[1] = p1[1];
//	f_p1[2] = p1[2];
//	
//	f_p2[0] = p2[0];
//	f_p2[1] = p2[1];
//	f_p2[2] = p2[2];
	f_p1[0].value = float_to_fixed(p1[0]);
	f_p1[1].value = float_to_fixed(p1[1]);
	f_p1[2].value = float_to_fixed(p1[2]);
	
	f_p2[0].value = float_to_fixed(p2[0]);
	f_p2[1].value = float_to_fixed(p2[1]);
	f_p2[2].value = float_to_fixed(p2[2]);
}

qboolean SV_RecursiveHullCheckFP (hull_t *hull, int num, const fixed_point *p1f, const fixed_point *p2f, const vec3_f *p1, const vec3_f *p2, trace_t *trace);

qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace)
{
	dclipnode_t	*node;
	mplane_t	*plane;
	int			i;
	int			side;
	
	fixed_point f_mid[3];
	fixed_point f_midf;
	
	fixed_point f_t1, f_t2;
	fixed_point f_frac;
	
	fixed_point f_p1[3];
	fixed_point f_p2[3];

	recursive_hull_fp_convert(f_p1, f_p2, p1, p2);
	
	register unsigned int stack_ptr asm ("sp");
	
	if (stack_ptr < min_stack_pointer)
	{
//		printf("stack %08x, depth %d\n", stack_ptr, hull_depth + 1);
		min_stack_pointer = stack_ptr;
	}
	
	hull_depth++;

// check for empty
	if (num < 0)
	{
		if (num != CONTENTS_SOLID)
		{
			trace->allsolid = false;
			if (num == CONTENTS_EMPTY)
				trace->inopen = true;
			else
				trace->inwater = true;
		}
		else
			trace->startsolid = true;
		
		hull_depth--;
		return true;		// empty
	}

	if (num < hull->firstclipnode || num > hull->lastclipnode)
		Sys_Error ("SV_RecursiveHullCheck: bad node number");

//
// find the point distances
//
	node = hull->clipnodes + num;
	plane = hull->planes + node->planenum;

	if (plane->type < 3)
	{
		f_t1.value = f_p1[plane->type].value - plane->dist.value;
		f_t2.value = f_p2[plane->type].value - plane->dist.value;
	}
	else
	{	
		f_t1.value = ((long long)plane->normal[0].value * (long long)f_p1[0].value
						+ (long long)plane->normal[1].value * (long long)f_p1[1].value
						+ (long long)plane->normal[2].value * (long long)f_p1[2].value) / FP_SCALE;
		f_t1.value -= plane->dist.value;
		
		f_t2.value = ((long long)plane->normal[0].value * (long long)f_p2[0].value
						+ (long long)plane->normal[1].value * (long long)f_p2[1].value
						+ (long long)plane->normal[2].value * (long long)f_p2[2].value) / FP_SCALE;
		f_t2.value -= plane->dist.value;
	}
	
	if (f_t1 >= 0 && f_t2 >= 0)
	{
		qboolean res = SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace);
		hull_depth--;
		return res;
	}
	if (f_t1 < 0 && f_t2 < 0)
	{
		qboolean res = SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace);
		hull_depth--;
		return res;
	}

	if (f_t1.value < 0)
	{
		f_frac.value = (((long long)f_t1.value + (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1.value-f_t2.value);
	}
	else
	{
		f_frac.value = (((long long)f_t1.value - (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1.value-f_t2.value);
	}
	
	if (f_frac.value < 0)
		f_frac.value = 0;
	if (f_frac.value > 1 * FP_SCALE)
		f_frac.value = 1 * FP_SCALE;
		
	f_midf = p1f + (p2f - p1f)*f_frac;
	for (i=0 ; i<3 ; i++)
		f_mid[i] = p1[i] + f_frac*(p2[i] - p1[i]);

	side = (f_t1.value < 0);
	
	vec3_t mid;
	mid[0] = f_mid[0];
	mid[1] = f_mid[1];
	mid[2] = f_mid[2];
	
// move up to the node
	if (!SV_RecursiveHullCheck (hull, node->children[side], p1f, f_midf, p1, mid, trace) )
	{
		hull_depth--;
		return false;
	}
	
	if (SV_HullPointContentsFP (hull, node->children[side^1], f_mid)
	!= CONTENTS_SOLID)
// go past the node
	{
		qboolean res = SV_RecursiveHullCheck (hull, node->children[side^1], f_midf, p2f, mid, p2, trace);
		hull_depth--;
		return res;
	}
	
	if (trace->allsolid)
	{
		hull_depth--;
		return false;		// never got out of the solid area
	}
		
//==================
// the other side of the node is solid, this is the impact point
//==================
	
	if (!side)
	{
		trace->plane.normal[0].value = plane->normal[0].value;
		trace->plane.normal[1].value = plane->normal[1].value;
		trace->plane.normal[2].value = plane->normal[2].value;
		
		trace->plane.dist.value = plane->dist.value;
	}
	else
	{
		trace->plane.normal[0].value = (int)(vec3_origin[0] * FP_SCALE) - plane->normal[0].value;
		trace->plane.normal[1].value = (int)(vec3_origin[1] * FP_SCALE) - plane->normal[1].value;
		trace->plane.normal[2].value = (int)(vec3_origin[2] * FP_SCALE) - plane->normal[2].value;
		
		trace->plane.dist.value = -plane->dist.value;
	}

	const int point_one = (int)(FP_SCALE * 0.1f);
	
	while (SV_HullPointContentsFP (hull, hull->firstclipnode, f_mid)
	== CONTENTS_SOLID)
	{ // shouldn't really happen, but does occasionally
		f_frac.value = f_frac.value - point_one;
		if (f_frac.value < 0)
		{
			trace->fraction = f_midf;
			VectorCopy (f_mid, trace->endpos);
			Con_DPrintf ("backup past 0\n");
			hull_depth--;
			return false;
		}
		f_midf = p1f + (p2f - p1f)*f_frac;
		for (i=0 ; i<3 ; i++)
			f_mid[i] = p1[i] + f_frac*(p2[i] - p1[i]);
	}

	trace->fraction = f_midf;
	VectorCopy (f_mid, trace->endpos);

	hull_depth--;
	return false;
}



#else
//FILE *funny_fp = NULL;
qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace)
{
	dclipnode_t	*node;
	mplane_t	*plane;
//	float		t1, t2;
//	float		frac;
	int			i;
//	vec3_t		mid;
	int			side;
//	float		midf;

//	if (funny_fp == NULL)
//	{
//		funny_fp = fopen("fat0:/funny.txt", "w");
//		
//		if (funny_fp == NULL)
//		{
//			printf("couldn'\t open file\n");
//			while(1);
//		}
//	}
//	fprintf(funny_fp, "entered function, num %d, p1f %.2f, p2f %.2f, p1 %.2f %.2f %.2f, p2 %.2f %.2f %.2f\n", num, p1f, p2f,
//		p1[0], p1[1], p1[2], p2[0], p2[1], p2[2]);

	fixed_point f_mid[3];
	fixed_point f_midf;
	
	fixed_point f_t1, f_t2;
	fixed_point f_frac;
	
	fixed_point f_p1[3];
	f_p1[0] = p1[0];
	f_p1[1] = p1[1];
	f_p1[2] = p1[2];
	
	fixed_point f_p2[3];
	f_p2[0] = p2[0];
	f_p2[1] = p2[1];
	f_p2[2] = p2[2];

// check for empty
	if (num < 0)
	{
		if (num != CONTENTS_SOLID)
		{
#ifdef USE_EXTRA_RAM
			byte_write(&trace->allsolid, false);
			
			if (num == CONTENTS_EMPTY)
				byte_write(&trace->inopen, true);
			else
				byte_write(&trace->inwater, true);
#else
			trace->allsolid = false;
			
			if (num == CONTENTS_EMPTY)
				trace->inopen = true;
			else
				trace->inwater = true;
#endif
		}
		else
#ifdef USE_EXTRA_RAM
			byte_write(&trace->startsolid, true);
#else
			trace->startsolid = true;
#endif
			
//		fprintf(funny_fp, "returning true, 1\n");
		return true;		// empty
	}

	if (num < hull->firstclipnode || num > hull->lastclipnode)
		Sys_Error ("SV_RecursiveHullCheck: bad node number");

//
// find the point distances
//
	node = hull->clipnodes + num;
	plane = hull->planes + node->planenum;

	if (plane->type < 3)
	{
		f_t1.value = f_p1[plane->type].value - plane->dist.value;
		f_t2.value = f_p2[plane->type].value - plane->dist.value;
	}
	else
	{	
//		f_t1.value = ((long long)plane->normal[0].value * (long long)f_p1[0].value
//						+ (long long)plane->normal[1].value * (long long)f_p1[1].value
//						+ (long long)plane->normal[2].value * (long long)f_p1[2].value) / FP_SCALE;
//		f_t1.value -= plane->dist.value;
		
		f_t2.value = ((long long)plane->normal[0].value * (long long)f_p2[0].value
						+ (long long)plane->normal[1].value * (long long)f_p2[1].value
						+ (long long)plane->normal[2].value * (long long)f_p2[2].value) / FP_SCALE;
		f_t2.value -= plane->dist.value;
		
//		int temp1, temp2;
//		temp1 = f_t1.value;
//		temp2 = f_t2.value;

		f_t1 = DotProduct (plane->normal, p1) - plane->dist;
//		f_t2 = DotProduct (plane->normal, p2) - plane->dist;
//		
//		if (fabs(f_t1 - (float)temp1 / FP_SCALE) > 0.1)
//			printf("%.2f %.2f, %.2f %.2f\n", (float)f_t1, (float)f_t2, (float)temp1 / FP_SCALE, (float)temp2 / FP_SCALE);
//		
//		if (fabs(f_t2 - (float)temp2 / FP_SCALE) > 0.1)
//			printf("%.2f %.2f, %.2f %.2f\n", (float)f_t1, (float)f_t2, (float)temp1 / FP_SCALE, (float)temp2 / FP_SCALE);
	}
	
	if (f_t1 >= 0 && f_t2 >= 0)
	{
//		fprintf(funny_fp, "calling, 2\n");
		return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace);
	}
	if (f_t1 < 0 && f_t2 < 0)
	{
//		fprintf(funny_fp, "calling, 3\n");
		return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace);
	}

// put the crosspoint DIST_EPSILON pixels on the near side
//	if (f_t1.value < 0)
//		f_frac = (f_t1 + DIST_EPSILON)/(f_t1-f_t2);
//	else
//		f_frac = (f_t1 - DIST_EPSILON)/(f_t1-f_t2);
//	if (f_frac < 0)
//		f_frac = 0;
//	if (f_frac > 1)
//		f_frac = 1;
	if (f_t1.value < 0)
	{
		f_frac.value = (((long long)f_t1.value + (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1.value-f_t2.value);
//		int temp = f_frac.value;
//		f_frac = (f_t1 + DIST_EPSILON)/(f_t1-f_t2);
		
//		printf("%.2f, %.2f\n", (float)f_frac, (float)temp / FP_SCALE);
	}
	else
	{
		f_frac.value = (((long long)f_t1.value - (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1.value-f_t2.value);
//		int temp = f_frac.value;
//		f_frac = (f_t1 - DIST_EPSILON)/(f_t1-f_t2);
		
//		printf("%.2f, %.2f\n", (float)f_frac, (float)temp / FP_SCALE);
	}
	
	if (f_frac.value < 0)
		f_frac.value = 0;
	if (f_frac.value > 1 * FP_SCALE)
		f_frac.value = 1 * FP_SCALE;
		
	f_midf = p1f + (p2f - p1f)*f_frac;
	for (i=0 ; i<3 ; i++)
		f_mid[i] = p1[i] + f_frac*(p2[i] - p1[i]);

	side = (f_t1.value < 0);
	
	vec3_t mid;
	mid[0] = f_mid[0];
	mid[1] = f_mid[1];
	mid[2] = f_mid[2];
	
// move up to the node
//	fprintf(funny_fp, "calling, extra\n");
	if (!SV_RecursiveHullCheck (hull, node->children[side], p1f, f_midf, p1, mid, trace) )
		return false;
	
	if (SV_HullPointContentsFP (hull, node->children[side^1], f_mid)
	!= CONTENTS_SOLID)
// go past the node
	{
//		fprintf(funny_fp, "calling, 4\n");
		return SV_RecursiveHullCheck (hull, node->children[side^1], f_midf, p2f, mid, p2, trace);
	}
	
	if (trace->allsolid)
	{
//		fprintf(funny_fp, "return false, 5\n");
		return false;		// never got out of the solid area
	}
		
//==================
// the other side of the node is solid, this is the impact point
//==================
	
	if (!side)
	{
//		VectorCopy (plane->normal, trace->plane.normal);
		
		trace->plane.normal[0].value = plane->normal[0].value;
		trace->plane.normal[1].value = plane->normal[1].value;
		trace->plane.normal[2].value = plane->normal[2].value;
		
		trace->plane.dist.value = plane->dist.value;
	}
	else
	{
//		VectorSubtract (vec3_origin, plane->normal, trace->plane.normal);
		
		trace->plane.normal[0].value = (int)(vec3_origin[0] * FP_SCALE) - plane->normal[0].value;
		trace->plane.normal[1].value = (int)(vec3_origin[1] * FP_SCALE) - plane->normal[1].value;
		trace->plane.normal[2].value = (int)(vec3_origin[2] * FP_SCALE) - plane->normal[2].value;
		
		trace->plane.dist.value = -plane->dist.value;
	}

	const int point_one = (int)(FP_SCALE * 0.1f);
	
	while (SV_HullPointContentsFP (hull, hull->firstclipnode, f_mid)
	== CONTENTS_SOLID)
	{ // shouldn't really happen, but does occasionally
		f_frac.value = f_frac.value - point_one;
		if (f_frac.value < 0)
		{
			trace->fraction = f_midf;
			VectorCopy (f_mid, trace->endpos);
			Con_DPrintf ("backup past 0\n");
//			fprintf(funny_fp, "return false, 6\n");
			return false;
		}
		f_midf = p1f + (p2f - p1f)*f_frac;
		for (i=0 ; i<3 ; i++)
			f_mid[i] = p1[i] + f_frac*(p2[i] - p1[i]);
	}

	trace->fraction = f_midf;
	VectorCopy (f_mid, trace->endpos);

//	fprintf(funny_fp, "return false, 6\n");
	return false;
}
#if 0
fixed_point f_mid_stack[70];
fixed_point f_midf_stack[70];
fixed_point f_t1_stack[70];
fixed_point f_t2_stack[70];
fixed_point f_frac_stack[70];
fixed_point f_p1_stack[70];
fixed_point f_p2_stack[70];

int hull_depth = 0;
qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace)
{
	dclipnode_t	*node;
	mplane_t	*plane;
	int			i;
	int			side;
	
//	fixed_point f_mid[3];
//	fixed_point f_midf;
//	
//	fixed_point f_t1, f_t2;
//	fixed_point f_frac;
//	
//	fixed_point f_p1[3];
//	fixed_point f_p2[3];
	
	fixed_point *f_mid = &f_mid_stack[hull_depth * 3];
	fixed_point *f_midf = &f_midf_stack[hull_depth];
	
	fixed_point *f_t1 = &f_t1_stack[hull_depth];
	fixed_point *f_t2 = &f_t2_stack[hull_depth];
	fixed_point *f_frac = &f_frac_stack[hull_depth];
	
	fixed_point *f_p1 = &f_p1_stack[hull_depth * 3];
	fixed_point *f_p2 = &f_p2_stack[hull_depth * 3];

	recursive_hull_fp_convert(f_p1, f_p2, p1, p2);
	
	register unsigned int stack_ptr asm ("sp");
	
	if (stack_ptr < min_stack_pointer)
	{
//		printf("stack %08x, depth %d\n", stack_ptr, hull_depth + 1);
		min_stack_pointer = stack_ptr;
	}
	
	hull_depth++;

// check for empty
	if (num < 0)
	{
		if (num != CONTENTS_SOLID)
		{
			trace->allsolid = false;
			if (num == CONTENTS_EMPTY)
				trace->inopen = true;
			else
				trace->inwater = true;
		}
		else
			trace->startsolid = true;
		
		hull_depth--;
		return true;		// empty
	}

	if (num < hull->firstclipnode || num > hull->lastclipnode)
		Sys_Error ("SV_RecursiveHullCheck: bad node number");

//
// find the point distances
//
	node = hull->clipnodes + num;
	plane = hull->planes + node->planenum;

	if (plane->type < 3)
	{
		f_t1->value = f_p1[plane->type].value - plane->dist.value;
		f_t2->value = f_p2[plane->type].value - plane->dist.value;
	}
	else
	{	
		f_t1->value = ((long long)plane->normal[0].value * (long long)f_p1[0].value
						+ (long long)plane->normal[1].value * (long long)f_p1[1].value
						+ (long long)plane->normal[2].value * (long long)f_p1[2].value) / FP_SCALE;
		f_t1->value -= plane->dist.value;
		
		f_t2->value = ((long long)plane->normal[0].value * (long long)f_p2[0].value
						+ (long long)plane->normal[1].value * (long long)f_p2[1].value
						+ (long long)plane->normal[2].value * (long long)f_p2[2].value) / FP_SCALE;
		f_t2->value -= plane->dist.value;
	}
	
	if (f_t1 >= 0 && f_t2 >= 0)
	{
		qboolean res = SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace);
		hull_depth--;
		return res;
	}
	if (f_t1 < 0 && f_t2 < 0)
	{
		qboolean res = SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace);
		hull_depth--;
		return res;
	}

	if (f_t1->value < 0)
	{
		f_frac->value = (((long long)f_t1->value + (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1->value-f_t2->value);
	}
	else
	{
		f_frac->value = (((long long)f_t1->value - (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1->value-f_t2->value);
	}
	
	if (f_frac->value < 0)
		f_frac->value = 0;
	if (f_frac->value > 1 * FP_SCALE)
		f_frac->value = 1 * FP_SCALE;
		
	*f_midf = p1f + (p2f - p1f)**f_frac;
	for (i=0 ; i<3 ; i++)
		f_mid[i] = p1[i] + *f_frac*(p2[i] - p1[i]);

	side = (f_t1->value < 0);
	
	vec3_t mid;
	mid[0] = f_mid[0];
	mid[1] = f_mid[1];
	mid[2] = f_mid[2];
	
// move up to the node
	if (!SV_RecursiveHullCheck (hull, node->children[side], p1f, *f_midf, p1, mid, trace) )
	{
		hull_depth--;
		return false;
	}
	
	if (SV_HullPointContentsFP (hull, node->children[side^1], f_mid)
	!= CONTENTS_SOLID)
// go past the node
	{
		qboolean res = SV_RecursiveHullCheck (hull, node->children[side^1], *f_midf, p2f, mid, p2, trace);
		hull_depth--;
		return res;
	}
	
	if (trace->allsolid)
	{
		hull_depth--;
		return false;		// never got out of the solid area
	}
		
//==================
// the other side of the node is solid, this is the impact point
//==================
	
	if (!side)
	{
		trace->plane.normal[0].value = plane->normal[0].value;
		trace->plane.normal[1].value = plane->normal[1].value;
		trace->plane.normal[2].value = plane->normal[2].value;
		
		trace->plane.dist.value = plane->dist.value;
	}
	else
	{
		trace->plane.normal[0].value = (int)(vec3_origin[0] * FP_SCALE) - plane->normal[0].value;
		trace->plane.normal[1].value = (int)(vec3_origin[1] * FP_SCALE) - plane->normal[1].value;
		trace->plane.normal[2].value = (int)(vec3_origin[2] * FP_SCALE) - plane->normal[2].value;
		
		trace->plane.dist.value = -plane->dist.value;
	}

	const int point_one = (int)(FP_SCALE * 0.1f);
	
	while (SV_HullPointContentsFP (hull, hull->firstclipnode, f_mid)
	== CONTENTS_SOLID)
	{ // shouldn't really happen, but does occasionally
		f_frac->value = f_frac->value - point_one;
		if (f_frac->value < 0)
		{
			trace->fraction = *f_midf;
			VectorCopy (f_mid, trace->endpos);
			Con_DPrintf ("backup past 0\n");
			hull_depth--;
			return false;
		}
		*f_midf = p1f + (p2f - p1f)**f_frac;
		for (i=0 ; i<3 ; i++)
			f_mid[i] = p1[i] + *f_frac*(p2[i] - p1[i]);
	}

	trace->fraction = *f_midf;
	VectorCopy (f_mid, trace->endpos);

	hull_depth--;
	return false;
}
#endif
//qboolean SV_RecursiveHullCheck (hull_t *hull, int num, float p1f, float p2f, vec3_t p1, vec3_t p2, trace_t *trace)
//{
//	dclipnode_t	*node;
//	mplane_t	*plane;
//	float		t1, t2;
//	float		frac;
//	int			i;
//	vec3_t		mid;
//	int			side;
//	float		midf;
//
//// check for empty
//	if (num < 0)
//	{
//		if (num != CONTENTS_SOLID)
//		{
//			trace->allsolid = false;
//			if (num == CONTENTS_EMPTY)
//				trace->inopen = true;
//			else
//				trace->inwater = true;
//		}
//		else
//			trace->startsolid = true;
//		return true;		// empty
//	}
//
//	if (num < hull->firstclipnode || num > hull->lastclipnode)
//		Sys_Error ("SV_RecursiveHullCheck: bad node number");
//
////
//// find the point distances
////
//	node = hull->clipnodes + num;
//	plane = hull->planes + node->planenum;
//
//	if (plane->type < 3)
//	{
//		t1 = p1[plane->type] - plane->dist;
//		t2 = p2[plane->type] - plane->dist;
//	}
//	else
//	{
//		t1 = DotProduct (plane->normal, p1) - plane->dist;
//		t2 = DotProduct (plane->normal, p2) - plane->dist;
//	}
//	
//#if 1
//	if (t1 >= 0 && t2 >= 0)
//		return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace);
//	if (t1 < 0 && t2 < 0)
//		return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace);
//#else
//	if ( (t1 >= DIST_EPSILON && t2 >= DIST_EPSILON) || (t2 > t1 && t1 >= 0) )
//		return SV_RecursiveHullCheck (hull, node->children[0], p1f, p2f, p1, p2, trace);
//	if ( (t1 <= -DIST_EPSILON && t2 <= -DIST_EPSILON) || (t2 < t1 && t1 <= 0) )
//		return SV_RecursiveHullCheck (hull, node->children[1], p1f, p2f, p1, p2, trace);
//#endif
//
//// put the crosspoint DIST_EPSILON pixels on the near side
//	if (t1 < 0)
//		frac = (t1 + DIST_EPSILON)/(t1-t2);
//	else
//		frac = (t1 - DIST_EPSILON)/(t1-t2);
//	if (frac < 0)
//		frac = 0;
//	if (frac > 1)
//		frac = 1;
//		
//	midf = p1f + (p2f - p1f)*frac;
//	for (i=0 ; i<3 ; i++)
//		mid[i] = p1[i] + frac*(p2[i] - p1[i]);
//
//	side = (t1 < 0);
//
//// move up to the node
//	if (!SV_RecursiveHullCheck (hull, node->children[side], p1f, midf, p1, mid, trace) )
//		return false;
//
//#ifdef PARANOID
//	if (SV_HullPointContents (sv_hullmodel, mid, node->children[side])
//	== CONTENTS_SOLID)
//	{
//		Con_Printf ("mid PointInHullSolid\n");
//		return false;
//	}
//#endif
//	
//	if (SV_HullPointContents (hull, node->children[side^1], mid)
//	!= CONTENTS_SOLID)
//// go past the node
//		return SV_RecursiveHullCheck (hull, node->children[side^1], midf, p2f, mid, p2, trace);
//	
//	if (trace->allsolid)
//		return false;		// never got out of the solid area
//		
////==================
//// the other side of the node is solid, this is the impact point
////==================
//	
//	if (!side)
//	{
//		VectorCopy (plane->normal, trace->plane.normal);
//		trace->plane.dist = plane->dist;
//	}
//	else
//	{
//		VectorSubtract (vec3_origin, plane->normal, trace->plane.normal);
//		trace->plane.dist = -plane->dist;
//	}
//
//	while (SV_HullPointContents (hull, hull->firstclipnode, mid)
//	== CONTENTS_SOLID)
//	{ // shouldn't really happen, but does occasionally
//		frac -= 0.1;
//		if (frac < 0)
//		{
//			trace->fraction = midf;
//			VectorCopy (mid, trace->endpos);
//			Con_DPrintf ("backup past 0\n");
//			return false;
//		}
//		midf = p1f + (p2f - p1f)*frac;
//		for (i=0 ; i<3 ; i++)
//			mid[i] = p1[i] + frac*(p2[i] - p1[i]);
//	}
//
//	trace->fraction = midf;
//	VectorCopy (mid, trace->endpos);
//
//	return false;
//}

#endif


/*
==================
SV_ClipMoveToEntity

Handles selection or creation of a clipping hull, and offseting (and
eventually rotation) of the end points
==================
*/
trace_t SV_ClipMoveToEntity (edict_t *ent, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end) __attribute__((section(".itcm"), long_call));
trace_t SV_ClipMoveToEntity (edict_t *ent, vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end)
{
	trace_t		trace;
	vec3_t		offset;
	vec3_t		start_l, end_l;
	hull_t		*hull;

// fill in a default trace
	ds_memset (&trace, 0, sizeof(trace_t));
	trace.fraction = 1;
#ifdef USE_EXTRA_RAM
	byte_write(&trace.allsolid, true);
#else
	trace.allsolid = true;
#endif
	VectorCopy (end, trace.endpos);

// get the clipping hull
	hull = SV_HullForEntity (ent, mins, maxs, offset);

	VectorSubtract (start, offset, start_l);
	VectorSubtract (end, offset, end_l);

#ifdef QUAKE2
	// rotate start and end into the models frame of reference
	if (ent->v.solid == SOLID_BSP && 
	(ent->v.angles[0] || ent->v.angles[1] || ent->v.angles[2]) )
	{
		vec3_t	a;
		vec3_t	forward, right, up;
		vec3_t	temp;

		AngleVectors (ent->v.angles, forward, right, up);

		VectorCopy (start_l, temp);
		start_l[0] = DotProduct (temp, forward);
		start_l[1] = -DotProduct (temp, right);
		start_l[2] = DotProduct (temp, up);

		VectorCopy (end_l, temp);
		end_l[0] = DotProduct (temp, forward);
		end_l[1] = -DotProduct (temp, right);
		end_l[2] = DotProduct (temp, up);
	}
#endif
// trace a line through the apropriate clipping hull
	bool result = SV_NonRecursiveHullCheck (hull, hull->firstclipnode, 0, 1, start_l, end_l, &trace);
//	printf("done\n");
//	fprintf(funny_fp, "result is %d\n", result);
//	fclose(funny_fp);
//	while(1);

//	vec3_f start_f, end_f;
//	
//	start_f.f[0] = start_l[0];
//	start_f.f[1] = start_l[1];
//	start_f.f[2] = start_l[2];
//	
//	end_f.f[0] = end_l[0];
//	end_f.f[1] = end_l[1];
//	end_f.f[2] = end_l[2];
//	
//	const fixed_point zero(0);
//	const fixed_point one(1);
//	
//	SV_RecursiveHullCheckFP (hull, hull->firstclipnode, &zero, &one, &start_f, &end_f, &trace);
	
	if (hull_depth != 0)
		Sys_Error("hull depth is not zero!\n");

#ifdef QUAKE2
	// rotate endpos back to world frame of reference
	if (ent->v.solid == SOLID_BSP && 
	(ent->v.angles[0] || ent->v.angles[1] || ent->v.angles[2]) )
	{
		vec3_t	a;
		vec3_t	forward, right, up;
		vec3_t	temp;

		if (trace.fraction != 1)
		{
			VectorSubtract (vec3_origin, ent->v.angles, a);
			AngleVectors (a, forward, right, up);

			VectorCopy (trace.endpos, temp);
			trace.endpos[0] = DotProduct (temp, forward);
			trace.endpos[1] = -DotProduct (temp, right);
			trace.endpos[2] = DotProduct (temp, up);

			VectorCopy (trace.plane.normal, temp);
			trace.plane.normal[0] = DotProduct (temp, forward);
			trace.plane.normal[1] = -DotProduct (temp, right);
			trace.plane.normal[2] = DotProduct (temp, up);
		}
	}
#endif

// fix trace up by the offset
	if (trace.fraction != 1)
		VectorAdd (trace.endpos, offset, trace.endpos);

// did we clip the move?
	if (trace.fraction < 1 || trace.startsolid  )
		trace.ent = ent;

	return trace;
}

trace_t SV_ClipMoveToEntityFP (edict_t *ent, fixed_point3 start, fixed_point3 mins, fixed_point3 maxs, fixed_point3 end) __attribute__((section(".itcm"), long_call));
trace_t SV_ClipMoveToEntityFP (edict_t *ent, fixed_point3 start, fixed_point3 mins, fixed_point3 maxs, fixed_point3 end)
{
	trace_t		trace;
	fixed_point3		offset;
	vec3_t		start_l, end_l;
	hull_t		*hull;

// fill in a default trace
	ds_memset (&trace, 0, sizeof(trace_t));
	trace.fraction = 1;
#ifdef USE_EXTRA_RAM
	byte_write(&trace.allsolid, true);
#else
	trace.allsolid = true;
#endif
	VectorCopy (end, trace.endpos);

// get the clipping hull
	hull = SV_HullForEntityFP (ent, mins, maxs, offset);

	VectorSubtract (start, offset, start_l);
	VectorSubtract (end, offset, end_l);

#ifdef QUAKE2
	// rotate start and end into the models frame of reference
	if (ent->v.solid == SOLID_BSP && 
	(ent->v.angles[0] || ent->v.angles[1] || ent->v.angles[2]) )
	{
		vec3_t	a;
		vec3_t	forward, right, up;
		vec3_t	temp;

		AngleVectors (ent->v.angles, forward, right, up);

		VectorCopy (start_l, temp);
		start_l[0] = DotProduct (temp, forward);
		start_l[1] = -DotProduct (temp, right);
		start_l[2] = DotProduct (temp, up);

		VectorCopy (end_l, temp);
		end_l[0] = DotProduct (temp, forward);
		end_l[1] = -DotProduct (temp, right);
		end_l[2] = DotProduct (temp, up);
	}
#endif
// trace a line through the apropriate clipping hull
	bool result = SV_NonRecursiveHullCheck (hull, hull->firstclipnode, 0, 1, start_l, end_l, &trace);
	
	if (hull_depth != 0)
		Sys_Error("hull depth is not zero!\n");

// fix trace up by the offset
	if (trace.fraction != 1)
		VectorAdd (trace.endpos, offset, trace.endpos);

// did we clip the move?
	if (trace.fraction < 1 || trace.startsolid  )
		trace.ent = ent;

	return trace;
}

//===========================================================================

/*
====================
SV_ClipToLinks

Mins and maxs enclose the entire area swept by the move
====================
*/
void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip ) __attribute__((section(".itcm"), long_call));
void SV_ClipToLinks ( areanode_t *node, moveclip_t *clip )
{
	link_t		*l, *next;
	edict_t		*touch;
	trace_t		trace;

// touch linked edicts
	for (l = node->solid_edicts.next ; l != &node->solid_edicts ; l = next)
	{
		next = l->next;
		touch = EDICT_FROM_AREA(l);
		if (touch->v.solid == SOLID_NOT)
			continue;
		if (touch == clip->passedict)
			continue;
		if (touch->v.solid == SOLID_TRIGGER)
			Sys_Error ("Trigger in clipping list");

		if (clip->type == MOVE_NOMONSTERS && touch->v.solid != SOLID_BSP)
			continue;

		if (clip->boxmins[0] > touch->v.absmax[0]
		|| clip->boxmins[1] > touch->v.absmax[1]
		|| clip->boxmins[2] > touch->v.absmax[2]
		|| clip->boxmaxs[0] < touch->v.absmin[0]
		|| clip->boxmaxs[1] < touch->v.absmin[1]
		|| clip->boxmaxs[2] < touch->v.absmin[2] )
			continue;

		if (clip->passedict && clip->passedict->v.size[0] && !touch->v.size[0])
			continue;	// points never interact

	// might intersect, so do an exact clip
		if (clip->trace.allsolid)
			return;
		if (clip->passedict)
		{
		 	if (PROG_TO_EDICT(touch->v.owner) == clip->passedict)
				continue;	// don't clip against own missiles
			if (PROG_TO_EDICT(clip->passedict->v.owner) == touch)
				continue;	// don't clip against owner
		}

		if ((int)touch->v.flags & FL_MONSTER)
			trace = SV_ClipMoveToEntityFP (touch, clip->start, clip->mins2, clip->maxs2, clip->end);
		else
			trace = SV_ClipMoveToEntityFP (touch, clip->start, clip->mins, clip->maxs, clip->end);
		if (trace.allsolid || trace.startsolid ||
		trace.fraction.value < clip->trace.fraction.value)
		{
			trace.ent = touch;
		 	if (clip->trace.startsolid)
			{
				clip->trace = trace;
#ifdef USE_EXTRA_RAM
				byte_write(&clip->trace.startsolid, true);
#else
				clip->trace.startsolid = true;
#endif
			}
			else
				clip->trace = trace;
		}
		else if (trace.startsolid)
			clip->trace.startsolid = true;
	}
	
// recurse down both sides
	if (node->axis == -1)
		return;

	if ( clip->boxmaxs[node->axis].value > node->dist.value )
		SV_ClipToLinks ( node->children[0], clip );
	if ( clip->boxmins[node->axis].value < node->dist.value )
		SV_ClipToLinks ( node->children[1], clip );
}


/*
==================
SV_MoveBounds
==================
*/
void SV_MoveBounds (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, vec3_t boxmins, vec3_t boxmaxs)
{
#if 0
// debug to test against everything
boxmins[0] = boxmins[1] = boxmins[2] = -9999;
boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999;
#else
	int		i;
	
	for (i=0 ; i<3 ; i++)
	{
		if (end[i] > start[i])
		{
			boxmins[i] = start[i] + mins[i] - 1;
			boxmaxs[i] = end[i] + maxs[i] + 1;
		}
		else
		{
			boxmins[i] = end[i] + mins[i] - 1;
			boxmaxs[i] = start[i] + maxs[i] + 1;
		}
	}
#endif
}

void SV_MoveBoundsFP (fixed_point3 start, fixed_point3 mins, fixed_point3 maxs, fixed_point3 end, fixed_point3 boxmins, fixed_point3 boxmaxs)
{
#if 0
// debug to test against everything
boxmins[0] = boxmins[1] = boxmins[2] = -9999;
boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999;
#else
	int		i;
	
	for (i=0 ; i<3 ; i++)
	{
		if (end[i] > start[i])
		{
			boxmins[i] = start[i] + mins[i] - 1;
			boxmaxs[i] = end[i] + maxs[i] + 1;
		}
		else
		{
			boxmins[i] = end[i] + mins[i] - 1;
			boxmaxs[i] = start[i] + maxs[i] + 1;
		}
	}
#endif
}

/*
==================
SV_Move
==================
*/
trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int type, edict_t *passedict) __attribute__((section(".itcm"), long_call));
trace_t SV_Move (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, int type, edict_t *passedict)
{
	moveclip_t	clip;
	int			i;

	ds_memset ( &clip, 0, sizeof ( moveclip_t ) );

// clip to world
	
	fixed_point f_start[3];
	fixed_point f_end[3];
	fixed_point f_mins[3];
	fixed_point f_maxs[3];
	
	for (int count = 0; count < 3; count++)
	{
		f_start[count] = start[count];
		f_end[count] = end[count];
		f_mins[count] = mins[count];
		f_maxs[count] = maxs[count];
	}
	
//	clip.trace = SV_ClipMoveToEntity ( sv.edicts, start, mins, maxs, end );
	clip.trace = SV_ClipMoveToEntityFP ( sv.edicts, f_start, f_mins, f_maxs, f_end );

	clip.start = f_start;
	clip.end = f_end;
	clip.mins = f_mins;
	clip.maxs = f_maxs;
	clip.type = type;
	clip.passedict = passedict;

	if (type == MOVE_MISSILE)
	{
		for (i=0 ; i<3 ; i++)
		{
			clip.mins2[i] = -15;
			clip.maxs2[i] = 15;
		}
	}
	else
	{
		VectorCopy (mins, clip.mins2);
		VectorCopy (maxs, clip.maxs2);
	}
	
// create the bounding box of the entire move
	SV_MoveBoundsFP ( f_start, clip.mins2, clip.maxs2, f_end, clip.boxmins, clip.boxmaxs );
	
//	for (int count = 0; count < 3; count++)
//	{
//		start[count] = f_start[count];
//		end[count] = f_end[count];
//		mins[count] = f_mins[count];
//		maxs[count] = f_maxs[count];
//	}

// clip to entities
	SV_ClipToLinks ( sv_areanodes, &clip );

	return clip.trace;
}
/*
qboolean SV_RecursiveHullCheckFP (hull_t *hull, int num, const fixed_point *p1f, const fixed_point *p2f, const vec3_f *p1, const vec3_f *p2, trace_t *trace)
{
	dclipnode_t	*node;
	mplane_t	*plane;
	int			i;
	int			side;
	
	vec3_f f_mid;
	fixed_point f_midf;
	
	fixed_point f_t1, f_t2;
	fixed_point f_frac;
	
	register unsigned int stack_ptr asm ("sp");
	
	if (stack_ptr < min_stack_pointer)
	{
//		printf("stack %08x, depth %d\n", stack_ptr, hull_depth + 1);
		min_stack_pointer = stack_ptr;
	}

	hull_depth++;

// check for empty
	if (num < 0)
	{
		if (num != CONTENTS_SOLID)
		{
//			trace->allsolid = false;
			byte_write(&trace->allsolid, false);
			if (num == CONTENTS_EMPTY)
				trace->inopen = true;
			else
				trace->inwater = true;
		}
		else
			trace->startsolid = true;
		
		hull_depth--;
		return true;		// empty
	}

	if (num < hull->firstclipnode || num > hull->lastclipnode)
		Sys_Error ("SV_RecursiveHullCheck: bad node number");

//
// find the point distances
//
	node = hull->clipnodes + num;
	plane = hull->planes + node->planenum;

	if (plane->type < 3)
	{
		f_t1.value = p1->f[plane->type].value - plane->dist.value;
		f_t2.value = p2->f[plane->type].value - plane->dist.value;
	}
	else
	{	
		f_t1.value = ((long long)plane->normal[0].value * (long long)p1->f[0].value
						+ (long long)plane->normal[1].value * (long long)p1->f[1].value
						+ (long long)plane->normal[2].value * (long long)p1->f[2].value) / FP_SCALE;
		f_t1.value -= plane->dist.value;
		
		f_t2.value = ((long long)plane->normal[0].value * (long long)p2->f[0].value
						+ (long long)plane->normal[1].value * (long long)p2->f[1].value
						+ (long long)plane->normal[2].value * (long long)p2->f[2].value) / FP_SCALE;
		f_t2.value -= plane->dist.value;
	}
	
	if (f_t1 >= 0 && f_t2 >= 0)
	{
		qboolean res = SV_RecursiveHullCheckFP (hull, node->children[0], p1f, p2f, p1, p2, trace);
		hull_depth--;
		return res;
	}
	if (f_t1 < 0 && f_t2 < 0)
	{
		qboolean res = SV_RecursiveHullCheckFP (hull, node->children[1], p1f, p2f, p1, p2, trace);
		hull_depth--;
		return res;
	}

	if (f_t1.value < 0)
	{
		f_frac.value = (((long long)f_t1.value + (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1.value-f_t2.value);
	}
	else
	{
		f_frac.value = (((long long)f_t1.value - (long long)DIST_EPSILON_FP) * (long long)FP_SCALE)/(f_t1.value-f_t2.value);
	}
	
	if (f_frac.value < 0)
		f_frac.value = 0;
	if (f_frac.value > FP_SCALE)
		f_frac.value = FP_SCALE;
		
//	f_midf = *(fixed_point *)p1f + (*(fixed_point *)p2f - *(fixed_point *)p1f)*f_frac;
	f_midf.value = p1f->value + (((long long)(p2f->value - p1f->value) * (long long)f_frac.value) >> FP_SCALE_SHIFT);
	for (i=0 ; i<3 ; i++)
//		f_mid.f[i] = (fixed_point)p1->f[i] + f_frac*((fixed_point)p2->f[i] - (fixed_point)p1->f[i]);
		f_mid.f[i].value = p1->f[i].value + (((long long)f_frac.value * (long long)p2->f[i].value) >> 13) - p1->f[i].value;

	side = (f_t1.value < 0);
	
// move up to the node
	if (!SV_RecursiveHullCheckFP (hull, node->children[side], p1f, &f_midf, p1, &f_mid, trace) )
	{
		hull_depth--;
		return false;
	}
	
	if (SV_HullPointContentsFP (hull, node->children[side^1], (fixed_point *)&f_mid)
	!= CONTENTS_SOLID)
// go past the node
	{
		qboolean res = SV_RecursiveHullCheckFP (hull, node->children[side^1], &f_midf, p2f, &f_mid, p2, trace);
		hull_depth--;
		return res;
	}
	
	if (trace->allsolid)
	{
		hull_depth--;
		return false;		// never got out of the solid area
	}
		
//==================
// the other side of the node is solid, this is the impact point
//==================
	
	if (!side)
	{
		trace->plane.normal[0].value = plane->normal[0].value;
		trace->plane.normal[1].value = plane->normal[1].value;
		trace->plane.normal[2].value = plane->normal[2].value;
		
		trace->plane.dist.value = plane->dist.value;
	}
	else
	{
		trace->plane.normal[0].value = (int)(vec3_origin[0] * FP_SCALE) - plane->normal[0].value;
		trace->plane.normal[1].value = (int)(vec3_origin[1] * FP_SCALE) - plane->normal[1].value;
		trace->plane.normal[2].value = (int)(vec3_origin[2] * FP_SCALE) - plane->normal[2].value;
		
		trace->plane.dist.value = -plane->dist.value;
	}

	const int point_one = (int)(FP_SCALE * 0.1f);
	
	while (SV_HullPointContentsFP (hull, hull->firstclipnode, (fixed_point *)&f_mid)
	== CONTENTS_SOLID)
	{ // shouldn't really happen, but does occasionally
		f_frac.value = f_frac.value - point_one;
		if (f_frac.value < 0)
		{
			trace->fraction = f_midf;
//			VectorCopy (f_mid, trace->endpos);
			trace->endpos[0] = f_mid.f[0]; trace->endpos[1] = f_mid.f[1]; trace->endpos[2] = f_mid.f[2];
			Con_DPrintf ("backup past 0\n");
			hull_depth--;
			return false;
		}
		f_midf = *(fixed_point *)p1f + (*(fixed_point *)p2f - *(fixed_point *)p1f)*f_frac;
		for (i=0 ; i<3 ; i++)
			f_mid.f[i] = (fixed_point)p1->f[i] + f_frac*((fixed_point)p2->f[i] - (fixed_point)p1->f[i]);
	}

	trace->fraction = f_midf;
//	VectorCopy (f_mid, trace->endpos);
	trace->endpos[0] = f_mid.f[0]; trace->endpos[1] = f_mid.f[1]; trace->endpos[2] = f_mid.f[2];

	hull_depth--;
	return false;
}*/
