/* light.cpp
	Sydney Paul   sepaul   CPSC 1020 Section 003
	Majoring Assignment #3
*/


#include "ray.h"
#include "math.h"

static pparm_t light_parse[] = 
{
	{"location",3,sizeof(double),"%lf",0},
	{"emissivity",3,sizeof(double),"%lf",0}
};
#define NUM_ATTRS (sizeof(light_parse) / sizeof(pparm_t))

light_t::light_t(FILE *in, model_t *model, int attrmax)
{
	int mask;
	int count;
	char attrname[NAME_LEN];
	
	cookie = LGT_COOKIE;
	
	count = fscanf(in,"%s",name);
	assert(count == 1);
	fscanf(in,"%s",attrname);
	assert(attrname[0] == '{');
	
	light_parse[0].loc = &location;
	light_parse[1].loc = &emissivity;
	mask = parser(in,light_parse,NUM_ATTRS,attrmax);
	assert(mask != 0);
	
	model->lgts->add((void *)this);
}

void light_list_print(model_t *model, FILE *out)
{
	light_t *light;
	list_t *list= model->lgts;
	list->reset();
	
	while(list->not_end())
	{
		light = (light_t *)list->get_entity();
		light->printer(out);
		list->next_link();
	}
}

void light_t::printer(FILE *out)
{
	fprintf(out, "%-12s %s \n", "light", name);
	fprintf(out, "%-12s %5.1lf %5.1lf %5.1lf\n", "location", location.x,location.y,location.z);
	fprintf(out, " %-12s %5.1lf %5.1lf %5.1lf\n", "emissivity", emissivity.r,emissivity.g,emissivity.b);
}

// Getter functions

void light_t::getemiss(drgb_t *emiss)
{
	pix_copy(&emissivity, emiss);
}

void light_t::getloc(vec_t *loc)
{
	vec_copy(&location,loc);
}
	

void light_t::illuminate(model_t *model, vec_t *base, object_t *hitobj, drgb_t *pixel)
{
	vec_t dir;
	object_t *obj;
	double close, cos, dist;
	drgb_t diffuse = {0.0,0.0,0.0};
	
	vec_t lasthit,lastnorm;
	
	hitobj->getlast_hitpt(&lasthit);
	//vec_t location = getloc(&location);
	vec_diff(&lasthit,&location,&dir);
	dist = vec_len(&dir);
	vec_unit(&dir,&dir);
	hitobj->getlast_normal(&lastnorm);
	
	cos = vec_dot(&lastnorm,&dir);
	if (cos <= 0.0)
	{
		return;
	}
	
	obj = find_closest_object(model,&lasthit,&dir,hitobj,&close);
	if ((obj != NULL) && (close < dist))
	{
		return;
	}
	
	hitobj->getdiffuse(&diffuse);
	//double temp3;
	pix_prod(&emissivity,&diffuse,&diffuse);
	//temp3 = cos/dist;
	pix_scale(cos/dist,&diffuse,&diffuse);
	
	pix_sum(pixel,&diffuse,pixel); 
	
	
	
	


}


		

	
	
	
	
	
	
	

