#include "fdf.h"

t_color	color_init(int red, int green, int blue)
{
	t_color c;

	c.red = red;
	c.blue = blue;
	c.green = green;
	return (c);
}

t_color	color_lerp(t_color c1, t_color c2, double step)
{
	t_color new;
	double 	red;
	double	green;
	double	blue;

	red = (double)(c2.red - c1.red) * step + c1.red;
	green = (double)(c2.green - c1.green) * step  + c1.green;
	blue = (double)(c2.blue - c1.blue) * step + c1.blue;
	new.red = (int)red;
	new.green = (int)green;
	new.blue = (int)blue;
	return (new);
}

int 	color_to_int(t_color c)
{
	return ((c.red << 16) | (c.green << 8) | c.blue);
}

t_color int_to_color(int c)
{
	t_color new;

	new.blue = c & 0x0000FF;
	new.green = (c >> 8) & 0x0000FF;
	new.red = (c >> 16 ) & 0x0000FF;
	return (new);
}

t_color	choose_color(t_line *line, t_swap *s)
{
	t_color c;
	float 	z1;
	float 	z2;

	z1 = line->p1.z;
	z2 = line->p2.z;
	if (s->swap_z)
		if (z2 == 0)
			c = int_to_color(color_to_int(line->p2.color));
		else
			c = color_lerp(line->p2.color, line->p1.color, z1 / z2);
	else
		if (z2 == 0)
			c = int_to_color(color_to_int(line->p1.color));
		else
			c = color_lerp(line->p1.color, line->p2.color, z1 / z2);
	return (c);
}

void	first_color(t_pnt *pnt, float z, t_map *map)
{
	int 	low_color;
	int 	high_color;

	low_color = (map->low == NULL) ? COLOR1 : color_to_int(*map->low);
	high_color = (map->high == NULL) ? COLOR2 : color_to_int(*map->high);
	if (z == 0)
		pnt->color = int_to_color(low_color);
	if (z == map->z_max - map->z_min)
		pnt->color = int_to_color(high_color);
	else
		pnt->color = color_lerp(
				int_to_color(low_color),
				int_to_color(high_color), fabs(z / (map->z_max - map->z_min)));
}
