8c9ee813992035ee3958f27dbda53a505b88b65b
[supertux.git] / lib / special / sprite_manager.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <iostream>
22 #include <sstream>
23 #include <stdexcept>
24
25 #include "utils/lispreader.h"
26 #include "sprite_manager.h"
27 #include "sprite_data.h"
28 #include "sprite.h"
29
30 namespace SuperTux
31 {
32
33 SpriteManager::SpriteManager(const std::string& filename)
34 {
35   load_resfile(filename);
36 }
37
38 SpriteManager::~SpriteManager()
39 {
40   for(Sprites::iterator i = sprites.begin(); i != sprites.end(); ++i) {
41     delete i->second;
42   }
43 }
44
45 void
46 SpriteManager::load_resfile(const std::string& filename)
47 {
48   lisp_object_t* root_obj = lisp_read_from_file(filename);
49   if (!root_obj)
50     {
51       std::cout << "SpriteManager: Couldn't load: " << filename << std::endl;
52       return;
53     }
54
55   lisp_object_t* cur = root_obj;
56
57   if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-resources") != 0)
58     return;
59   cur = lisp_cdr(cur);
60
61   while(cur) {
62     lisp_object_t* el = lisp_car(cur);
63
64     if (strcmp(lisp_symbol(lisp_car(el)), "sprite") == 0) {
65       SpriteData* spritedata = new SpriteData(lisp_cdr(el));
66
67       Sprites::iterator i = sprites.find(spritedata->get_name());
68       if (i == sprites.end()) {
69         sprites[spritedata->get_name()] = spritedata;
70       } else {
71         delete i->second;
72         i->second = spritedata;
73         std::cout << "Warning: dulpicate entry: '" << spritedata->get_name()
74           << "' in spritefile." << std::endl;
75       }
76     } else {
77       std::cout << "SpriteManager: Unknown tag in spritefile.\n";
78     }
79
80     cur = lisp_cdr(cur);
81   }
82
83   lisp_free(root_obj);
84 }
85
86 Sprite*
87 SpriteManager::create(const std::string& name)
88 {
89   Sprites::iterator i = sprites.find(name);
90   if(i == sprites.end()) {
91     std::stringstream msg;
92     msg << "Sprite '" << name << "' not found.";
93     throw std::runtime_error(msg.str());
94   }
95   return new Sprite(*i->second);
96 }
97
98 }
99