/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   draw_column.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/05/04 13:51:59 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 13:52:01 by pblagoje         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

static void	draw_floor_ceiling(t_game *game, t_rcast *rcast, t_txt *txt)
{
	t_vec	plan;

	plan.start.x = rcast->ray_nb;
	plan.end.x = rcast->ray_nb;
	if (rcast->wall.vec.start.y > 0)
	{
		plan.start.y = rcast->screen_height;
		plan.end.y = rcast->wall.vec.start.y;
		draw_line(&game->img, &plan, txt->rgb_floor);
	}
	if (rcast->wall.vec.start.y < rcast->screen_height)
	{
		plan.start.y = rcast->wall.vec.end.y;
		plan.end.y = 0;
		draw_line(&game->img, &plan, txt->rgb_ceiling);
	}
}

static int	get_texture(t_img *img, int imgx, int j, int height)
{
	char	*color;
	int		y;
	int		position;

	y = ((long)j * (long)img->height) / height;
	position = y * img->szl + imgx * (img->bpp / 8);
	color = img->data + position;
	return (*(int *)color);
}

static void	draw_txt_column(t_game *game, t_wall *wall, t_img *txt_img)
{
	int	col;
	int	img_x;
	int	i;
	int	j;

	img_x = (wall->posx * txt_img->width) / game->rcast.cell;
	j = wall->limit;
	i = 0;
	while (j < wall->height - wall->limit)
	{
		col = get_texture(txt_img, img_x, j, wall->height);
		draw_pixel(&game->img, wall->vec.start.x, wall->vec.end.y + i, col);
		j++;
		i++;
	}
}

void	draw_column(t_game *game, t_rcast *rcast, t_wall *wall, t_txt *txt)
{
	draw_floor_ceiling(game, rcast, txt);
	if (!rcast->is_x && rcast->slope_y > 0)
		draw_txt_column(game, wall, &txt->img_n);
	else if (!rcast->is_x && rcast->slope_y < 0)
		draw_txt_column(game, wall, &txt->img_s);
	else if (rcast->is_x && rcast->slope_x > 0)
		draw_txt_column(game, wall, &txt->img_e);
	else if (rcast->is_x && rcast->slope_x < 0)
		draw_txt_column(game, wall, &txt->img_w);
}
