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