/* select.c: evertyhing concerning the selection of patches (by pointing
 * to them and clicking a mouse button) and what to do with the selected
 * patch. */

#include "select.h"
#include "ray.h"
#include "camera.h"
#include "scene.h"
#include "render.h"
#include "canvas.h"
#include "error.h"

static void (*SelectPatchCallbackProc)(PATCH *patch, POINT *hitp);

void SelectPatchSetCallback(void (*proc)(PATCH *patch, POINT *hitp))
{
	SelectPatchCallbackProc = proc;
}

void SelectPatch(int pixx, int pixy)
{
	RAY ray;
	float v, h, x, y, dist;
	PATCH *hit;
	POINT hitp;

	CanvasPullMode();

/* something wrong with this, but I still have to take a look at it, can't be hard to
 * fix however */
       	h = 2. * tan(Camera.hfov * M_PI/180.) / (float)(Camera.hres-1);
       	v = 2. * tan(Camera.vfov * M_PI/180.) / (float)(Camera.vres-1);
	x = h * ((float)pixx - (float)(Camera.hres-1)/2.);
	y = v * ((float)pixy - (float)(Camera.vres-1)/2.);

	ray.pos = Camera.eyep;
	VECTORCOMB3(Camera.Z, x, Camera.X, y, Camera.Y, ray.dir);
	VECTORNORMALIZE(ray.dir);

	dist = HUGE;
	if ((hit = GeomListIntersect(World, &ray, 0., &dist, FALSE)) &&
	    (hit->twosided || VECTORDOTPRODUCT(ray.dir, hit->norm)<0.)) {		
		RenderElementOutline(hit);		
		VECTORSUMSCALED(ray.pos, dist, ray.dir, hitp);
		SelectPatchCallbackProc(hit, &hitp);
	} else 
		Error(NULL, "No surfaces there.");
}


