/ src / render_texture.c
render_texture.c
 1  /* ************************************************************************** */
 2  /*                                                                            */
 3  /*                                                        :::      ::::::::   */
 4  /*   render_texture.c                                   :+:      :+:    :+:   */
 5  /*                                                    +:+ +:+         +:+     */
 6  /*   By: ll-hotel <ll-hotel@student.42.fr>          +#+  +:+       +#+        */
 7  /*                                                +#+#+#+#+#+   +#+           */
 8  /*   Created: 2024/09/08 20:33:16 by ll-hotel          #+#    #+#             */
 9  /*   Updated: 2024/11/12 17:53:02 by omougel          ###   ########.fr       */
10  /*                                                                            */
11  /* ************************************************************************** */
12  
13  #include "cub3D.h"
14  #include "ft_basics.h"
15  #include "img_put_pixel.h"
16  #include <math.h>
17  
18  static t_img	*find_texture(t_cube *cube, t_hitside side);
19  static int		find_tex_x(t_ray *ray, t_cube *cube, t_img *texture);
20  
21  void	render_texture(t_ray *ray, t_cube *cube, int x)
22  {
23  	t_img *const	texture = find_texture(cube, ray->side);
24  	float const		y_ratio = (float)texture->height / ray->wall_height;
25  	int const		tex_x = find_tex_x(ray, cube, texture);
26  	float			y_pos_in_wall;
27  	int				y;
28  
29  	y_pos_in_wall = ft_max(0, ray->wall_height - SCREEN_HEIGHT) * y_ratio * 0.5;
30  	y = ray->drawstart - 1;
31  	while (++y < ray->drawend)
32  	{
33  		img_put_pixel(&cube->mlx.img, y, x, \
34  				img_get_pixel(texture, floorf(y_pos_in_wall), tex_x));
35  		y_pos_in_wall += y_ratio;
36  	}
37  }
38  
39  static t_img	*find_texture(t_cube *cube, t_hitside side)
40  {
41  	if (side == NORTH)
42  		return (&cube->no_texture);
43  	if (side == SOUTH)
44  		return (&cube->so_texture);
45  	if (side == EAST)
46  		return (&cube->ea_texture);
47  	return (&cube->we_texture);
48  }
49  
50  static int	find_tex_x(t_ray *ray, t_cube *cube, t_img *texture)
51  {
52  	float	wall_x;
53  	int		tex_x;
54  
55  	if (ray->side == EAST || ray->side == WEST)
56  		wall_x = (cube->player.pos.y - ray->perpwalldist * ray->dir.y);
57  	else
58  		wall_x = (cube->player.pos.x - ray->perpwalldist * ray->dir.x);
59  	wall_x = ft_absf(wall_x);
60  	wall_x -= floorf(wall_x);
61  	if (ray->side == NORTH || ray->side == EAST)
62  		wall_x = 1.f - wall_x;
63  	tex_x = floorf(wall_x * texture->width);
64  	return (tex_x);
65  }