Cub3D
Loading...
Searching...
No Matches
get_map_data.c
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* get_map_data.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: hnagasak <hnagasak@student.42tokyo.jp> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2024/11/03 21:37:36 by kamitsui #+# #+# */
9/* Updated: 2024/12/20 17:59:52 by kamitsui ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "cub3d.h"
14
15t_map_size get_map_size(char **lines)
16{
17 size_t rows;
18 size_t cols;
19 size_t tmp_len;
20
21 rows = 0;
22 cols = 0;
23 while (lines[rows] != NULL)
24 {
25 tmp_len = ft_strlen(lines[rows]);
26 if (tmp_len > cols)
27 cols = tmp_len;
28 rows++;
29 }
30 return ((t_map_size){.rows = rows, .cols = cols});
31}
32
33char **allocate_map(t_map_size map_size)
34{
35 size_t i;
36 size_t rows;
37 size_t cols;
38 char **array;
39
40 rows = map_size.rows;
41 cols = map_size.cols;
42 array = (char **)malloc((rows + 1) * sizeof(char *));
43 if (array == NULL)
44 return (NULL);
45 i = 0;
46 while (i < rows)
47 {
48 array[i] = (char *)malloc((cols + 1) * sizeof(char));
49 if (array[i] == NULL)
50 {
51 free_double_pointer_n(array, i);
52 return (NULL);
53 }
54 i++;
55 }
56 return (array);
57}
58
59static void copy_and_pad_lines(char **src, char **dst, size_t max_len)
60{
61 size_t len;
62 size_t i;
63
64 i = 0;
65 while (src[i] != NULL)
66 {
67 len = ft_strlen(src[i]);
68 ft_memset(dst[i], ' ', max_len);
69 ft_memcpy(dst[i], src[i], len);
70 dst[i][max_len] = '\0';
71 i++;
72 }
73 dst[i] = NULL;
74}
75
76static char **convert_str2array(const char *str_map)
77{
78 t_map_size map_size;
79 char **array;
80 char **lines;
81
82 lines = split_lines(str_map);
83 if (lines == NULL)
84 return (NULL);
85 map_size = get_map_size(lines);
86 array = allocate_map(map_size);
87 if (array == NULL)
88 {
89 free_double_pointer(lines);
90 return (NULL);
91 }
92 copy_and_pad_lines(lines, array, map_size.cols);
93 free_double_pointer(lines);
94 return (array);
95}
96
97int get_map_data(const char *line, t_parse *parse)
98{
99 int count;
100 t_map *map;
101
102 map = &parse->game->map;
103 map->data = convert_str2array(line);
104 if (map->data == NULL)
105 {
106 ft_eprintf("Error: convert_str2array() fail\n");
107 return (EXIT_FAILURE);
108 }
109 map->width = ft_strlen(map->data[0]);
110 count = 0;
111 while (map->data[count] != NULL)
112 count++;
113 map->height = count;
114 parse->flag |= BIT_INIT_MAP;
115 return (EXIT_SUCCESS);
116}
117 //debug_map_data(*map, "get_map_data()");
game map
Definition type_cub3d.h:237