summaryrefslogtreecommitdiff
path: root/spritesheet.c
blob: dcf47808679e303379862046bfc4a1fb04728319 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   spritesheet.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: kdx    <kdx   @student.42angouleme.fr      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/10/12 09:43:47 by kdx               #+#    #+#             */
/*   Updated: 2022/10/12 10:25:23 by kdx              ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft/libft.h"
#include "spritesheet.h"
#include "sprite.h"
#include "map.h"

static t_sprite	*load_sprite(t_sily *sily, char *path)
{
	return (sprite_load(sily, path, TSIZE, TSIZE));
}

t_spritesheet	*spritesheet_load(t_sily *sily, const char *pattern,
					size_t frames)
{
	t_spritesheet	*sheet;
	size_t			i;
	char			*path;
	char			*path_x;

	if (frames > 10 || ft_strchr(pattern, 'X') == NULL)
		return (NULL);
	path = ft_strdup(pattern);
	if (path == NULL)
		return (NULL);
	path_x = ft_strchr(path, 'X');
	if (ft_alloc(&sheet, sizeof(t_spritesheet)))
		return (ft_free(path));
	i = -1;
	while (++i < frames)
	{
		*path_x = '0' + i;
		sheet->frame[sheet->frame_count] = load_sprite(sily, path);
		if (sheet->frame[sheet->frame_count] == NULL)
			ft_free(path);
		if (sheet->frame[sheet->frame_count++] == NULL)
			return (spritesheet_destroy(sily, sheet));
	}
	ft_free(path);
	return (sheet);
}

void	*spritesheet_destroy(t_sily *sily, t_spritesheet *sheet)
{
	if (sheet != NULL)
	{
		while (sheet->frame_count-- > 0)
			sprite_destroy(sily, sheet->frame[sheet->frame_count]);
		ft_free(sheet);
	}
	return (NULL);
}