42_cub3d/map1.c
2024-10-15 18:23:16 +02:00

123 lines
2.9 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* map1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcolonna <mcolonna@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/01 17:12:58 by mcolonna #+# #+# */
/* Updated: 2024/10/15 17:22:53 by mcolonna ### ########.fr */
/* */
/* ************************************************************************** */
#include "map.h"
#include "map_utils.h"
#include "stream.h"
#include "read_all_text.h"
#include "libft.h"
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
static bool map_from_file2(t_map *dest, t_stream *stream, int fd)
{
bool success;
stream->i = 0;
success = read_map(dest, stream);
if (success)
{
success = check_map(dest);
if (!success)
map_destroy(dest);
}
close(fd);
free((void *)stream->str);
map_init_objects(dest);
return (success);
}
bool map_from_file(t_map *dest, const char *file)
{
int fd;
t_stream stream;
if (ft_strncmp(file + ft_strlen(file) - 4, ".cub", 5))
{
write_err("File extension must be .cub\n", NULL);
return (false);
}
fd = open(file, O_RDONLY);
if (fd < 0)
{
write_err("Can't open '", file, "': ", strerror(errno), "\n",
NULL);
return (false);
}
stream.str = read_all_text(fd);
if (!stream.str)
{
write_err("Can't read file.\n", NULL);
close(fd);
return (false);
}
return (map_from_file2(dest, &stream, fd));
}
void map_destroy(t_map *map)
{
free((void *)map->texture_east);
free((void *)map->texture_west);
free((void *)map->texture_north);
free((void *)map->texture_south);
free(map->cases);
}
static bool check_map2(const t_map *map, unsigned int x, unsigned int y)
{
unsigned int x2;
unsigned int y2;
const t_map_case *c;
c = &map->cases[y * map->width + x];
if (c->inside && c->wall != WALL)
{
if (x == 0 || x == map->width - 1
|| y == 0 || y == map->height - 1)
return (write_err("Map is not surrounded by walls\n", NULL), false);
x2 = x - 2;
while (++x2 < x + 2)
{
y2 = y - 2;
while (++y2 < y + 2)
{
if (x < map->width && y < map->height
&& !map->cases[y2 * map->width + x2].inside)
return (write_err("Map is not surrounded by walls\n", NULL),
false);
}
}
}
return (true);
}
// TODO check player
bool check_map(const t_map *map)
{
unsigned int x;
unsigned int y;
x = -1;
while (++x < map->width)
{
y = -1;
while (++y < map->height)
{
if (!check_map2(map, x, y))
return (false);
}
}
return (true);
}