Replaced more lisp::Lisp/lisp::Writer with Reader/Writer
[supertux.git] / src / sprite / sprite_manager.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
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 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include "sprite/sprite_manager.hpp"
18
19 #include "lisp/parser.hpp"
20 #include "sprite/sprite.hpp"
21 #include "util/file_system.hpp"
22 #include "util/reader.hpp"
23
24 SpriteManager* sprite_manager = NULL;
25
26 SpriteManager::SpriteManager() :
27   sprites()
28 {
29 }
30
31 SpriteManager::~SpriteManager()
32 {
33   for(Sprites::iterator i = sprites.begin(); i != sprites.end(); ++i) {
34     delete i->second;
35   }
36 }
37
38 std::auto_ptr<Sprite>
39 SpriteManager::create(const std::string& name)
40 {
41   Sprites::iterator i = sprites.find(name);
42   SpriteData* data;
43   if(i == sprites.end()) {
44     // try loading the spritefile
45     data = load(name);
46     if(data == NULL) {
47       std::stringstream msg;
48       msg << "Sprite '" << name << "' not found.";
49       throw std::runtime_error(msg.str());
50     }
51   } else {
52     data = i->second;
53   }
54
55   return std::auto_ptr<Sprite>(new Sprite(*data));
56 }
57
58 SpriteData*
59 SpriteManager::load(const std::string& filename)
60 {
61   lisp::Parser parser;
62   const lisp::Lisp* root;
63
64   try {
65     root = parser.parse(filename);
66   } catch(const std::exception& e) {
67     std::ostringstream msg;
68     msg << "Parse error when trying to load sprite '" << filename
69         << "': " << e.what() << "\n";
70     throw std::runtime_error(msg.str());
71   }
72
73   const lisp::Lisp* sprite = root->get_lisp("supertux-sprite");
74   if(!sprite) {
75     std::ostringstream msg;
76     msg << "'" << filename << "' is not a supertux-sprite file";
77     throw std::runtime_error(msg.str());
78   }
79
80   std::auto_ptr<SpriteData> data (
81     new SpriteData(*sprite, FileSystem::dirname(filename)) );
82   sprites[filename] = data.release();
83
84   return sprites[filename];
85 }
86
87 /* EOF */