Debian Codegraph @

src/gengine/ResImagePack.cpp

raw
1 /*
2 * Copyright (C) 2004 Ivo Danihelka ([email protected])
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 */
9 #include "ResImagePack.h"
10
11 #include "Path.h"
12 #include "ImgException.h"
13 #include "SDLException.h"
14 #include "OptionAgent.h"
15 #include "Log.h"
16
17 #include "SDL_image.h"
18
19 // The set cache size allows to contain all fish images and animations
20 // from level 'barrel'.
21 ResCache<SDL_Surface*> *ResImagePack::CACHE = new ResCache<SDL_Surface*>(
22 265, new ResImagePack(false));
23
24 //-----------------------------------------------------------------
25 ResImagePack::ResImagePack(bool caching_enabled) {
26 m_caching_enabled = false;
27 if (caching_enabled) {
28 m_caching_enabled = OptionAgent::agent()->getAsBool(
29 "cache_images", true);
30 }
31 }
32 //-----------------------------------------------------------------
33 /**
34 * Load unshared image from file
35 * and convert image to diplayformat.
36 *
37 * @return loaded surface
38 * @throws ImgException when image cannot be loaded
39 * @throws SDLException when image cannot be converted
40 */
41 SDL_Surface *
42 ResImagePack::loadImage(const Path &file)
43 {
44 SDL_Surface *raw_image = IMG_Load(file.getNative().c_str());
45 if (NULL == raw_image) {
46 throw ImgException(ExInfo("Load")
47 .addInfo("file", file.getNative()));
48 }
49
50 SDL_Surface *surface = SDL_DisplayFormatAlpha(raw_image);
51 if (NULL == surface) {
52 throw SDLException(ExInfo("DisplayFormat")
53 .addInfo("file", file.getNative()));
54 }
55 SDL_FreeSurface(raw_image);
56
57 return surface;
58 }
59 //-----------------------------------------------------------------
60 /**
61 * Store image from file.
62 *
63 * @throws ImgException when image cannot be loaded
64 * @throws SDLException when image cannot be converted
65 */
66 void
67 ResImagePack::addImage(const std::string &name, const Path &file)
68 {
69 SDL_Surface *surface;
70 if (m_caching_enabled) {
71 surface = CACHE->get(file.getPosixName());
72 if (!surface) {
73 surface = loadImage(file);
74 CACHE->put(file.getPosixName(), surface);
75 }
76 } else {
77 surface = loadImage(file);
78 }
79
80 addRes(name, surface);
81 }
82 //-----------------------------------------------------------------
83 void
84 ResImagePack::unloadRes(SDL_Surface *res)
85 {
86 if (m_caching_enabled) {
87 CACHE->release(res);
88 } else {
89 SDL_FreeSurface(res);
90 }
91 }
92