cub3d/src/parse.c
2025-04-18 16:18:24 +02:00

147 lines
3.3 KiB
C

/* ************************************************************************** */
/* */
/* :::::::: */
/* parse.c :+: :+: */
/* +:+ */
/* By: whaffman <whaffman@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2025/04/18 11:29:58 by whaffman #+# #+# */
/* Updated: 2025/04/18 15:20:37 by whaffman ######## odam.nl */
/* */
/* ************************************************************************** */
#include "cub3d.h"
#include "libft.h"
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
ssize_t get_file_size(const char *filename)
{
int fd;
ssize_t size;
fd = open(filename, O_RDONLY);
if (fd == -1)
return (-1);
size = read(fd, NULL, SIZE_MAX);
if (size == -1)
{
close(fd);
return (-1);
}
close(fd);
return (size);
}
char *read_map_file(const char *filename)
{
int fd;
ssize_t size;
ssize_t bytes_read;
char *buffer;
fd = open(filename, O_RDONLY);
if (fd == -1)
return (NULL);
size = get_file_size(filename);
if (size == -1)
return (close(fd), NULL);
buffer = malloc(size + 1);
if (!buffer)
return (close(fd), NULL);
bytes_read = read(fd, buffer, size);
if (bytes_read == -1)
{
free(buffer);
close(fd);
return (NULL);
}
buffer[bytes_read] = '\0';
close(fd);
return (buffer);
}
int is_map_line(const char *line)
{
if (!line || !*line)
return (FAILURE);
while (*line && ft_isspace(*line))
line++;
if (!*line)
return (FAILURE);
if (ft_strchr(line, '1'))
return (SUCCESS);
return (FAILURE);
}
int parse_color(const char *color_str)
{
}
int valid_color(char *str)
{
char **tokens;
int i;
tokens = ft_split(str, ',');
if (!tokens || !tokens[0] || !tokens[1] || tokens[2])
return (FAILURE);
i = 0;
while (tokens[i])
{
if (!ft_isdigit(tokens[i][0]))
return (FAILURE);
i++;
}
}
int parse_config_line(const char *line, t_map *map)
{
char **tokens;
tokens = ft_split(line, ' ');
if (!tokens || !tokens[0] || !tokens[1] || tokens[2])
return (FAILURE);
if (ft_strncmp(tokens[0], "NO", 2) == 0)
map->NO_texture = ft_strdup(tokens[1]);
else if (ft_strncmp(tokens[0], "SO", 2) == 0)
map->SO_texture = ft_strdup(tokens[1]);
else if (ft_strncmp(tokens[0], "WE", 2) == 0)
map->WE_texture = ft_strdup(tokens[1]);
else if (ft_strncmp(tokens[0], "EA", 2) == 0)
map->EA_texture = ft_strdup(tokens[1]);
else if (ft_strncmp(tokens[0], "F", 1) == 0)
map->floor_color = parse_color(tokens[1]);
else if (ft_strncmp(tokens[0], "C", 1) == 0)
map->ceiling_color = parse_color(tokens[1]);
else
{
ft_free_arr(tokens);
return (FAILURE);
}
ft_free_arr(tokens);
return (SUCCESS);
}
int parse_file(char *buffer, t_map *map)
{
char **lines;
lines = ft_split(buffer, '\n');
if (!lines)
return (FAILURE);
while (*lines && !is_map_line(*lines))
{
if (**lines && !parse_config_line(*lines, map))
return (free(lines), FAILURE);
lines++;
}
parse_map(lines, map);
free(lines);
return (SUCCESS);
}