// View.c

#include "ult_64.h"

#include "view.h"


SView
	*View = NULL;


void View_Calc( SCamera *camera, s32 fov_x, s32 fov_y, SView *view )
{
	matrix
		mtx;
	vector16
		vec,
		norm,
		campos;

	view->Camera = *camera;

	campos.x = (s16)camera->x;
	campos.y = (s16)camera->y;
	campos.z = (s16)camera->z;


	MakeMatPRH( &view->Cam2World, camera->Pitch, 0, camera->Yaw );

	view->World2Cam = view->Cam2World;
	MatInvert( &view->World2Cam );



	MakeMatPRH( &mtx, 0, 0, (fov_x<<15)/360 );
	vec.x = (1<<14);
	vec.y = 0;
	vec.z = 0;
	Vec16MulMat( &vec, &mtx, &vec );

	norm.x = vec.x;
	norm.y = vec.y;
	norm.z = vec.z;
	Vec16MulMat( &norm, &view->Cam2World, (vector16 *)&view->Left.x );
	view->Left.d = -DotProduct( &campos, (vector16 *)&view->Left.x );

	norm.x = -vec.x;
	norm.y = vec.y;
	norm.z = vec.z;
	Vec16MulMat( &norm, &view->Cam2World, (vector16 *)&view->Right.x );
	view->Right.d = -DotProduct( &campos, (vector16 *)&view->Right.x );


	MakeMatPRH( &mtx, (fov_y<<15)/360, 0, 0 );
	vec.x = 0;
	vec.y = (1<<14);
	vec.z = 0;
	Vec16MulMat( &vec, &mtx, &vec );

	norm.x = vec.x;
	norm.y = vec.y;
	norm.z = vec.z;
	Vec16MulMat( &norm, &view->Cam2World, (vector16 *)&view->Bot.x );
	view->Bot.d = -DotProduct( &campos, (vector16 *)&view->Bot.x );

	norm.x = vec.x;
	norm.y = -vec.y;
	norm.z = vec.z;
	Vec16MulMat( &norm, &view->Cam2World, (vector16 *)&view->Top.x );
	view->Top.d = -DotProduct( &campos, (vector16 *)&view->Top.x );


	norm.x = 0;
	norm.y = 0;
	norm.z = (1<<14);
	Vec16MulMat( &norm, &view->Cam2World, (vector16 *)&view->Front.x );
	view->Front.d = -DotProduct( &campos, (vector16 *)&view->Front.x );
	view->Front.d -= 64;
}


s32 View_Inside( vector16 *vec, s32 radius )
{
	s32
		d;

	d = DotProduct( vec, (vector16 *)&View->Front.x );
	d += View->Front.d;
	if (d < -radius)
		return( FALSE );

	d = DotProduct( vec, (vector16 *)&View->Left.x );
	d += View->Left.d;
	if (d < -radius)
		return( FALSE );

	d = DotProduct( vec, (vector16 *)&View->Right.x );
	d += View->Right.d;
	if (d < -radius)
		return( FALSE );

	d = DotProduct( vec, (vector16 *)&View->Top.x );
	d += View->Top.d;
	if (d < -radius)
		return( FALSE );

	d = DotProduct( vec, (vector16 *)&View->Bot.x );
	d += View->Bot.d;
	if (d < -radius)
		return( FALSE );


	return( TRUE );
}
