Further cleanups to texture caching, from bug 523:
[supertux.git] / src / video / texture_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 "video/texture_manager.hpp"
18
19 #include <SDL_image.h>
20 #include <assert.h>
21 #include <iostream>
22 #include <sstream>
23 #include <stdexcept>
24
25 #include "math/rect.hpp"
26 #include "physfs/physfs_sdl.hpp"
27 #include "util/file_system.hpp"
28 #include "util/log.hpp"
29 #include "video/sdl_surface_ptr.hpp"
30 #include "video/texture.hpp"
31 #include "video/video_systems.hpp"
32
33 #ifdef HAVE_OPENGL
34 #include "video/gl/gl_texture.hpp"
35 #endif
36
37 TextureManager::TextureManager() :
38   image_textures()
39 #ifdef HAVE_OPENGL
40   ,textures(),
41   saved_textures()
42 #endif
43 {
44 }
45
46 TextureManager::~TextureManager()
47 {
48   for(ImageTextures::iterator i = image_textures.begin(); i != image_textures.end(); ++i)
49   {
50     if(!i->second.expired())
51     {
52       log_warning << "Texture '" << i->first << "' not freed" << std::endl;
53     }
54   }
55   image_textures.clear();
56 }
57
58 TexturePtr
59 TextureManager::get(const std::string& _filename)
60 {
61   std::string filename = FileSystem::normalize(_filename);
62   ImageTextures::iterator i = image_textures.find(filename);
63
64   TexturePtr texture;
65   if(i != image_textures.end())
66     texture = i->second.lock();
67
68   if(!texture) {
69     texture = create_image_texture(filename);
70     texture->cache_filename = filename;
71     image_textures[filename] = texture;
72   }
73
74   return texture;
75 }
76
77 TexturePtr
78 TextureManager::get(const std::string& filename, const Rect& rect)
79 {
80   // FIXME: implement caching
81   return create_image_texture(filename, rect);
82 }
83
84 void
85 TextureManager::reap_cache_entry(const std::string& filename)
86 {
87   ImageTextures::iterator i = image_textures.find(filename);
88   assert(i != image_textures.end());
89   assert(i->second.expired());
90   image_textures.erase(i);
91 }
92
93 #ifdef HAVE_OPENGL
94 void
95 TextureManager::register_texture(GLTexture* texture)
96 {
97   textures.insert(texture);
98 }
99
100 void
101 TextureManager::remove_texture(GLTexture* texture)
102 {
103   textures.erase(texture);
104 }
105 #endif
106
107 TexturePtr
108 TextureManager::create_image_texture(const std::string& filename, const Rect& rect)
109 {
110   try 
111   {
112     return create_image_texture_raw(filename, rect);
113   }
114   catch(const std::exception& err)
115   {
116     log_warning << "Couldn't load texture '" << filename << "' (now using dummy texture): " << err.what() << std::endl;
117     return create_dummy_texture();
118   }
119 }
120
121 TexturePtr
122 TextureManager::create_image_texture_raw(const std::string& filename, const Rect& rect)
123 {
124   SDLSurfacePtr image(IMG_Load_RW(get_physfs_SDLRWops(filename), 1));
125   if (!image)
126   {
127     std::ostringstream msg;
128     msg << "Couldn't load image '" << filename << "' :" << SDL_GetError();
129     throw std::runtime_error(msg.str());
130   }
131   else
132   {
133     SDLSurfacePtr subimage(SDL_CreateRGBSurfaceFrom(static_cast<uint8_t*>(image->pixels) + 
134                                                     rect.top * image->pitch + 
135                                                     rect.left * image->format->BytesPerPixel, 
136
137                                                     rect.get_width(), rect.get_height(),
138                                                     image->format->BitsPerPixel,
139                                                     image->pitch,
140                                                     image->format->Rmask,
141                                                     image->format->Gmask,
142                                                     image->format->Bmask,
143                                                     image->format->Amask));
144     if (!subimage)
145     {
146       throw std::runtime_error("SDL_CreateRGBSurfaceFrom() call failed");
147     }
148     else
149     {
150       if (image->format->palette)
151       { // copy the image palette to subimage if present
152         SDL_SetColors(subimage.get(), image->format->palette->colors, 0, image->format->palette->ncolors);
153       }
154
155       return VideoSystem::new_texture(subimage.get());
156     }
157   }
158 }
159
160 TexturePtr
161 TextureManager::create_image_texture(const std::string& filename)
162 {
163   try 
164   {
165     return create_image_texture_raw(filename);
166   }
167   catch (const std::exception& err)
168   {
169     log_warning << "Couldn't load texture '" << filename << "' (now using dummy texture): " << err.what() << std::endl;
170     return create_dummy_texture();
171   }
172 }
173
174 TexturePtr
175 TextureManager::create_image_texture_raw(const std::string& filename)
176 {
177   SDLSurfacePtr image(IMG_Load_RW(get_physfs_SDLRWops(filename), 1));
178   if (!image) 
179   {
180     std::ostringstream msg;
181     msg << "Couldn't load image '" << filename << "' :" << SDL_GetError();
182     throw std::runtime_error(msg.str());
183   }
184   else
185   {
186     return VideoSystem::new_texture(image.get());
187   }
188 }
189
190 TexturePtr
191 TextureManager::create_dummy_texture()
192 {
193   const std::string dummy_texture_fname = "images/engine/missing.png";
194  
195   // on error, try loading placeholder file
196   try 
197   {
198     TexturePtr tex = create_image_texture_raw(dummy_texture_fname);
199     return tex;
200   }
201   catch (const std::exception& err) 
202   {
203     // on error (when loading placeholder), try using empty surface,
204     // when that fails to, just give up
205     SDLSurfacePtr image(SDL_CreateRGBSurface(0, 1024, 1024, 8, 0, 0, 0, 0));
206     if (!image)
207     {
208       throw err;
209     }
210     else
211     {
212       log_warning << "Couldn't load texture '" << dummy_texture_fname << "' (now using empty one): " << err.what() << std::endl;
213       return VideoSystem::new_texture(image.get());
214     }
215   }
216 }
217
218 #ifdef HAVE_OPENGL
219 void
220 TextureManager::save_textures()
221 {
222 #ifdef GL_PACK_ROW_LENGTH
223   /* all this stuff is not support by OpenGL ES */
224   glPixelStorei(GL_PACK_ROW_LENGTH, 0);
225   glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
226   glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
227   glPixelStorei(GL_PACK_SKIP_ROWS, 0);
228   glPixelStorei(GL_PACK_SKIP_IMAGES, 0);
229 #endif
230
231   glPixelStorei(GL_PACK_ALIGNMENT, 1);
232   for(Textures::iterator i = textures.begin(); i != textures.end(); ++i) {
233     save_texture(*i);
234   }
235   for(ImageTextures::iterator i = image_textures.begin();
236       i != image_textures.end(); ++i) {
237     save_texture(dynamic_cast<GLTexture*>(i->second.lock().get()));
238   }
239 }
240
241 void
242 TextureManager::save_texture(GLTexture* texture)
243 {
244   SavedTexture saved_texture;
245   saved_texture.texture = texture;
246   glBindTexture(GL_TEXTURE_2D, texture->get_handle());
247
248   //this doesn't work with OpenGL ES (but we don't need it on the GP2X anyway)
249 #ifndef GL_VERSION_ES_CM_1_0
250   glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH,
251                            &saved_texture.width);
252   glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT,
253                            &saved_texture.height);
254   glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_BORDER,
255                            &saved_texture.border);
256   glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
257                       &saved_texture.min_filter);
258   glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
259                       &saved_texture.mag_filter);
260   glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
261                       &saved_texture.wrap_s);
262   glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
263                       &saved_texture.wrap_t);
264
265   size_t pixelssize = saved_texture.width * saved_texture.height * 4;
266   saved_texture.pixels = new char[pixelssize];
267
268   glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE,
269                 saved_texture.pixels);
270 #endif
271
272   saved_textures.push_back(saved_texture);
273
274   glDeleteTextures(1, &(texture->get_handle()));
275   texture->set_handle(0);
276
277   assert_gl("retrieving texture for save");
278 }
279
280 void
281 TextureManager::reload_textures()
282 {
283 #ifdef GL_UNPACK_ROW_LENGTH
284   /* OpenGL ES doesn't support these */
285   glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
286   glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
287   glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
288   glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
289   glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0);
290 #endif
291   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
292
293   for(std::vector<SavedTexture>::iterator i = saved_textures.begin();
294       i != saved_textures.end(); ++i) {
295     SavedTexture& saved_texture = *i;
296
297     GLuint handle;
298     glGenTextures(1, &handle);
299     assert_gl("creating texture handle");
300
301     glBindTexture(GL_TEXTURE_2D, handle);
302     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
303                  saved_texture.width, saved_texture.height,
304                  saved_texture.border, GL_RGBA,
305                  GL_UNSIGNED_BYTE, saved_texture.pixels);
306     delete[] saved_texture.pixels;
307     assert_gl("uploading texture pixel data");
308
309     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
310                     saved_texture.min_filter);
311     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
312                     saved_texture.mag_filter);
313     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
314                     saved_texture.wrap_s);
315     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
316                     saved_texture.wrap_t);
317
318     assert_gl("setting texture_params");
319     saved_texture.texture->set_handle(handle);
320   }
321
322   saved_textures.clear();
323 }
324 #endif
325
326 /* EOF */