/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   draw.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: erey-bet <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/05/11 14:41:48 by erey-bet          #+#    #+#             */
/*   Updated: 2023/05/11 16:05:42 by erey-bet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "game.h"

void	draw_texture(t_game *game, t_dda *dda, int x)
{
	t_texture_draw	tex;
	int				y;

	tex.texture = game->textures[get_texture_side(dda)];
	if (dda->side == 0)
		tex.wall_x = game->ply.pos_y + dda->perp_wall_dist * game->ray.dir_y;
	else
		tex.wall_x = game->ply.pos_x + dda->perp_wall_dist * game->ray.dir_x;
	tex.wall_x -= floor(tex.wall_x);
	tex.x = (int)(tex.wall_x * (double)tex.texture->width);
	if ((dda->side == 0 && game->ray.dir_x > 0)
		|| (dda->side == 1 && game->ray.dir_y < 0))
		tex.x = tex.texture->width - tex.x - 1;
	tex.step = 1.0 * tex.texture->height / dda->line_height;
	tex.pos = (dda->draw_start - game->window->height
			/ 2 + dda->line_height / 2) * tex.step;
	y = dda->draw_start;
	while (y < dda->draw_end && y < HEIGHT)
	{
		tex.y = (int)tex.pos & (tex.texture->height - 1);
		tex.pos += tex.step;
		mlx_put_pixel(game->window, x, y++,
			get_pixel_color(tex.texture, tex.x, tex.y));
	}
}

void	draw(t_game *game, t_dda *dda, int x)
{
	int	y;

	y = -1;
	while (++y < dda->draw_start)
		mlx_put_pixel(game->window, x, y, game->map.color_bot);
	draw_texture(game, dda, x);
	y = dda->draw_end - 1;
	while (++y < HEIGHT && y > 0)
		mlx_put_pixel(game->window, x, y, game->map.color_top);
}
