summaryrefslogtreecommitdiffstats
path: root/src/resources/image.c
blob: 820d9aad8cef95ca4436dce77a317677279da63f (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * Copyright (C) 2013  Patrick "P. J." McDermott
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <SDL.h>
#include <SDL_image.h>
#include <config.h>
#include "../logging.h"
#include "image.h"
#include "resource.h"

struct resource_table img_res;

struct image *
img_png_get(const char *path)
{
	SDL_RWops *rwops;
	struct image *img;

	img = (struct image *) resource_get(&img_res, path);
	if (img != NULL) {
		resource_use((struct resource *) img);
		return img;
	}

	img = resource_alloc(path, sizeof(*img));
	rwops = SDL_RWFromFile(path, "rb");
	img->image = IMG_LoadPNG_RW(rwops);
	if (!img->image) {
		err(1, "Failed to load image \"%s\" (%s)",
				path, IMG_GetError());
	}

#ifdef DEBUG_PALETTES
	{
		SDL_Palette *pal;
		int col_i;

		debug("Palette for image \"%s\"\n", path);
		pal = img->image->format->palette;
		for (col_i = 0; col_i < pal->ncolors; ++col_i) {
			debug("    Color %3.3d: 0x%2.2x%2.2x%2.2x",
					col_i,
					pal->colors[col_i].r,
					pal->colors[col_i].g,
					pal->colors[col_i].b);
		}
	}
#endif

	resource_use((struct resource *) img);
	resource_add(&img_res, path, (struct resource *) img);

	return img;
}

void
img_png_free(struct image *image)
{
	SDL_Surface *data;

	if (image == NULL) {
		return;
	}

	data = image->image;
	if (resource_free(&img_res, (struct resource *) image)) {
		SDL_FreeSurface(data);
	}
}