#include "fdf.h"

void	recalculate_trnsf_matrs(t_map *map)
{
//	free(map->trnsf->xr);
//	free(map->trnsf->zr);
//	free(map->trnsf->yr);
//	free(map->trnsf->sc);
	mat4_x_rot(map->trnsf->xr, INIT_X + map->x_rot);
	mat4_z_rot(map->trnsf->zr, INIT_Z + map->z_rot);
	mat4_y_rot(map->trnsf->yr, INIT_Y + map->y_rot);
	mat4_scale(map->trnsf->sc,
			   INIT_X_SCALE * map->scale[0],
			   INIT_Y_SCALE * map->scale[1],
			   INIT_Z_SCALE * map->scale[2]);
}

void	initial_trnsf_mats(t_FDF *FDF)
{
	t_trnsf		*tf;

	tf = trnsf_mat_init();
	tf->vp = viewport_mat_init(FDF->w_width, FDF->w_height);
	tf->pr = orth_mat_init(
			((FDF->map->y_max > FDF->map->x_max) ?
			 FDF->map->y_max: FDF->map->x_max) + 2,
			((FDF->map->y_max > FDF->map->x_max) ?
			 FDF->map->y_max: FDF->map->x_max) + 2,
			FDF->map->z_max + 2);
	mat4_translate(
			tf->tr,
			(float)((FDF->map->y_max > FDF->map->x_max) ?
					FDF->map->y_max: FDF->map->x_max) / 2.0f,
			(float)((FDF->map->y_max > FDF->map->x_max) ?
					FDF->map->y_max: FDF->map->x_max) / 2.0f,
			(float)FDF->map->z_max / 2.0f);

	mat4_x_rot(tf->xr, INIT_X);
	mat4_z_rot(tf->zr, INIT_Z);
	mat4_y_rot(tf->yr, INIT_Y);
	mat4_scale(tf->sc, INIT_X_SCALE, INIT_Y_SCALE, INIT_Z_SCALE);
	FDF->map->trnsf = tf;
}

void	viewport_projection_translate(t_trnsf *tf)
{
	t_mat4 *tmp;

	tmp = tf->vp_pr_tr;
	tf->vp_pr_tr = mat4_mult(tf->vp, tf->pr);
	free(tmp);
	tmp = tf->vp_pr_tr;
	tf->vp_pr_tr = mat4_mult(tf->tr, tf->vp_pr_tr);
	free(tmp);
}

void	mat4_mult_chain(t_trnsf *tf)
{
	t_mat4		*tmp;

	tmp = tf->fin;
	tf->fin = mat4_mult(tf->zr, tf->vp_pr_tr);
	free(tmp);
	tmp = tf->fin;
	tf->fin = mat4_mult(tf->xr, tf->fin);
	free(tmp);
	tmp = tf->fin;
	tf->fin = mat4_mult(tf->yr, tf->fin);
	free(tmp);
	tmp = tf->fin;
	tf->fin = mat4_mult(tf->sc, tf->fin);
	free(tmp);
}