# spritecache.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "gfx_type.h"
    00014 #include "fileio_func.h"
    00015 #include "spriteloader/grf.hpp"
    00016 #include "gfx_func.h"
    00017 #ifdef WITH_PNG
    00018 #include "spriteloader/png.hpp"
    00019 #endif /* WITH_PNG */
    00020 #include "blitter/factory.hpp"
    00021 #include "core/math_func.hpp"
    00022
    00023 #include "table/sprites.h"
    00024
    00025 /* Default of 4MB spritecache */
    00026 uint _sprite_cache_size = 4;
    00027
    00028 typedef SimpleTinyEnumT<SpriteType, byte> SpriteTypeByte;
    00029
    00030 struct SpriteCache {
    00031   void *ptr;
    00032   size_t file_pos;
    00033   uint32 id;
    00034   uint16 file_slot;
    00035   int16 lru;
    00036   SpriteTypeByte type;
    00037   bool warned;
    00038 };
    00039
    00040
    00041 static uint _spritecache_items = 0;
    00042 static SpriteCache *_spritecache = NULL;
    00043
    00044
    00045 static inline SpriteCache *GetSpriteCache(uint index)
    00046 {
    00047   return &_spritecache[index];
    00048 }
    00049
    00050 static inline bool IsMapgenSpriteID(SpriteID sprite)
    00051 {
    00052   return IsInsideMM(sprite, 4845, 4882);
    00053 }
    00054
    00055 static SpriteCache *AllocateSpriteCache(uint index)
    00056 {
    00057   if (index >= _spritecache_items) {
    00058     /* Add another 1024 items to the 'pool' */
    00059     uint items = Align(index + 1, 1024);
    00060
    00061     DEBUG(sprite, 4, "Increasing sprite cache to %u items (" PRINTF_SIZE " bytes)", items, items * sizeof(*_spritecache));
    00062
    00063     _spritecache = ReallocT(_spritecache, items);
    00064
    00065     /* Reset the new items and update the count */
    00066     memset(_spritecache + _spritecache_items, 0, (items - _spritecache_items) * sizeof(*_spritecache));
    00067     _spritecache_items = items;
    00068   }
    00069
    00070   return GetSpriteCache(index);
    00071 }
    00072
    00073
    00074 struct MemBlock {
    00075   size_t size;
    00076   byte data[];
    00077 };
    00078
    00079 static uint _sprite_lru_counter;
    00080 static MemBlock *_spritecache_ptr;
    00081 static int _compact_cache_counter;
    00082
    00083 static void CompactSpriteCache();
    00084
    00091 bool SkipSpriteData(byte type, uint16 num)
    00092 {
    00093   if (type & 2) {
    00094     FioSkipBytes(num);
    00095   } else {
    00096     while (num > 0) {
    00097       int8 i = FioReadByte();
    00098       if (i >= 0) {
    00099         int size = (i == 0) ? 0x80 : i;
    00100         if (size > num) return false;
    00101         num -= size;
    00102         FioSkipBytes(size);
    00103       } else {
    00104         i = -(i >> 3);
    00105         num -= i;
    00106         FioReadByte();
    00107       }
    00108     }
    00109   }
    00110   return true;
    00111 }
    00112
    00117 static SpriteType ReadSpriteHeaderSkipData()
    00118 {
    00119   uint16 num = FioReadWord();
    00120
    00121   if (num == 0) return ST_INVALID;
    00122
    00123   byte type = FioReadByte();
    00124   if (type == 0xFF) {
    00125     FioSkipBytes(num);
    00126     /* Some NewGRF files have "empty" pseudo-sprites which are 1
    00127      * byte long. Catch these so the sprites won't be displayed. */
    00128     return (num == 1) ? ST_INVALID : ST_RECOLOUR;
    00129   }
    00130
    00131   FioSkipBytes(7);
    00132   return SkipSpriteData(type, num - 8) ? ST_NORMAL : ST_INVALID;
    00133 }
    00134
    00135 /* Check if the given Sprite ID exists */
    00136 bool SpriteExists(SpriteID id)
    00137 {
    00138   /* Special case for Sprite ID zero -- its position is also 0... */
    00139   if (id == 0) return true;
    00140   if (id >= _spritecache_items) return false;
    00141   return !(GetSpriteCache(id)->file_pos == 0 && GetSpriteCache(id)->file_slot == 0);
    00142 }
    00143
    00144 static void *AllocSprite(size_t);
    00145
    00146 static void *ReadSprite(SpriteCache *sc, SpriteID id, SpriteType sprite_type)
    00147 {
    00148   uint8 file_slot = sc->file_slot;
    00149   size_t file_pos = sc->file_pos;
    00150
    00151   assert(IsMapgenSpriteID(id) == (sprite_type == ST_MAPGEN));
    00152   assert(sc->type == sprite_type);
    00153
    00154   DEBUG(sprite, 9, "Load sprite %d", id);
    00155
    00156   if (sprite_type == ST_NORMAL && BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 32) {
    00157 #ifdef WITH_PNG
    00158     /* Try loading 32bpp graphics in case we are 32bpp output */
    00159     SpriteLoaderPNG sprite_loader;
    00160     SpriteLoader::Sprite sprite;
    00161
    00162     if (sprite_loader.LoadSprite(&sprite, file_slot, sc->id, sprite_type)) {
    00163       sc->ptr = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, &AllocSprite);
    00164
    00165       return sc->ptr;
    00166     }
    00167     /* If the PNG couldn't be loaded, fall back to 8bpp grfs */
    00168 #else
    00169     static bool show_once = true;
    00170     if (show_once) {
    00171       DEBUG(misc, 0, "You are running a 32bpp blitter, but this build is without libpng support; falling back to 8bpp graphics");
    00172       show_once = false;
    00173     }
    00174 #endif /* WITH_PNG */
    00175   }
    00176
    00177   FioSeekToFile(file_slot, file_pos);
    00178
    00179   /* Read the size and type */
    00180   int num  = FioReadWord();
    00181   byte type = FioReadByte();
    00182
    00183   /* Type 0xFF indicates either a colourmap or some other non-sprite info */
    00184   assert((type == 0xFF) == (sprite_type == ST_RECOLOUR));
    00185   if (type == 0xFF) {
    00186     /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
    00187      * number of recolour sprites that are 17 bytes that only exist in DOS
    00188      * GRFs which are the same as 257 byte recolour sprites, but with the last
    00189      * 240 bytes zeroed.  */
    00190     static const int RECOLOUR_SPRITE_SIZE = 257;
    00191     byte *dest = (byte *)AllocSprite(max(RECOLOUR_SPRITE_SIZE, num));
    00192
    00193     sc->ptr = dest;
    00194
    00195     if (_palette_remap_grf[sc->file_slot]) {
    00196       byte *dest_tmp = AllocaM(byte, max(RECOLOUR_SPRITE_SIZE, num));
    00197
    00198       /* Only a few recolour sprites are less than 257 bytes */
    00199       if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
    00200       FioReadBlock(dest_tmp, num);
    00201
    00202       /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
    00203       for (int i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
    00204         dest[i] = _palette_remap[dest_tmp[_palette_reverse_remap[i - 1] + 1]];
    00205       }
    00206     } else {
    00207       FioReadBlock(dest, num);
    00208     }
    00209
    00210     return sc->ptr;
    00211   }
    00212
    00213   /* Ugly hack to work around the problem that the old landscape
    00214    *  generator assumes that those sprites are stored uncompressed in
    00215    *  the memory, and they are only read directly by the code, never
    00216    *  send to the blitter. So do not send it to the blitter (which will
    00217    *  result in a data array in the format the blitter likes most), but
    00218    *  read the data directly from disk and store that as sprite.
    00219    * Ugly: yes. Other solution: no. Blame the original author or
    00220    *  something ;) The image should really have been a data-stream
    00221    *  (so type = 0xFF basicly). */
    00222   if (sprite_type == ST_MAPGEN) {
    00223     uint height = FioReadByte();
    00224     uint width  = FioReadWord();
    00225     Sprite *sprite;
    00226     byte *dest;
    00227
    00228     num = width * height;
    00229     sprite = (Sprite *)AllocSprite(sizeof(*sprite) + num);
    00230     sc->ptr = sprite;
    00231     sprite->height = height;
    00232     sprite->width  = width;
    00233     sprite->x_offs = FioReadWord();
    00234     sprite->y_offs = FioReadWord();
    00235
    00236     dest = sprite->data;
    00237     while (num > 0) {
    00238       int8 i = FioReadByte();
    00239       if (i >= 0) {
    00240         num -= i;
    00241         for (; i > 0; --i) *dest++ = FioReadByte();
    00242       } else {
    00243         const byte *rel = dest - (((i & 7) << 8) | FioReadByte());
    00244         i = -(i >> 3);
    00245         num -= i;
    00246         for (; i > 0; --i) *dest++ = *rel++;
    00247       }
    00248     }
    00249
    00250     sc->type = sprite_type;
    00251
    00252     return sc->ptr;
    00253   }
    00254
    00255   assert(sprite_type == ST_NORMAL || sprite_type == ST_FONT);
    00256
    00257   SpriteLoaderGrf sprite_loader;
    00258   SpriteLoader::Sprite sprite;
    00259
    00260   if (!sprite_loader.LoadSprite(&sprite, file_slot, file_pos, sprite_type)) {
    00261     if (id == SPR_IMG_QUERY) usererror("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
    00262     return (void*)GetRawSprite(SPR_IMG_QUERY, ST_NORMAL);
    00263   }
    00264   sc->ptr = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, &AllocSprite);
    00265
    00266   return sc->ptr;
    00267 }
    00268
    00269
    00270 bool LoadNextSprite(int load_index, byte file_slot, uint file_sprite_id)
    00271 {
    00272   size_t file_pos = FioGetPos();
    00273
    00274   SpriteType type = ReadSpriteHeaderSkipData();
    00275
    00276   if (type == ST_INVALID) return false;
    00277
    00278   if (load_index >= MAX_SPRITES) {
    00279     usererror("Tried to load too many sprites (#%d; max %d)", load_index, MAX_SPRITES);
    00280   }
    00281
    00282   bool is_mapgen = IsMapgenSpriteID(load_index);
    00283
    00284   if (is_mapgen) {
    00285     if (type != ST_NORMAL) usererror("Uhm, would you be so kind not to load a NewGRF that changes the type of the map generator sprites?");
    00286     type = ST_MAPGEN;
    00287   }
    00288
    00289   SpriteCache *sc = AllocateSpriteCache(load_index);
    00290   sc->file_slot = file_slot;
    00291   sc->file_pos = file_pos;
    00292   sc->ptr = NULL;
    00293   sc->lru = 0;
    00294   sc->id = file_sprite_id;
    00295   sc->type = type;
    00296   sc->warned = false;
    00297
    00298   return true;
    00299 }
    00300
    00301
    00302 void DupSprite(SpriteID old_spr, SpriteID new_spr)
    00303 {
    00304   SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
    00305   SpriteCache *scold = GetSpriteCache(old_spr);
    00306
    00307   scnew->file_slot = scold->file_slot;
    00308   scnew->file_pos = scold->file_pos;
    00309   scnew->ptr = NULL;
    00310   scnew->id = scold->id;
    00311   scnew->type = scold->type;
    00312   scnew->warned = false;
    00313 }
    00314
    00321 static const size_t S_FREE_MASK = sizeof(size_t) - 1;
    00322
    00323 /* to make sure nobody adds things to MemBlock without checking S_FREE_MASK first */
    00324 assert_compile(sizeof(MemBlock) == sizeof(size_t));
    00325 /* make sure it's a power of two */
    00326 assert_compile((sizeof(size_t) & (sizeof(size_t) - 1)) == 0);
    00327
    00328 static inline MemBlock *NextBlock(MemBlock *block)
    00329 {
    00330   return (MemBlock*)((byte*)block + (block->size & ~S_FREE_MASK));
    00331 }
    00332
    00333 static size_t GetSpriteCacheUsage()
    00334 {
    00335   size_t tot_size = 0;
    00336   MemBlock *s;
    00337
    00338   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
    00339     if (!(s->size & S_FREE_MASK)) tot_size += s->size;
    00340   }
    00341
    00342   return tot_size;
    00343 }
    00344
    00345
    00346 void IncreaseSpriteLRU()
    00347 {
    00348   /* Increase all LRU values */
    00349   if (_sprite_lru_counter > 16384) {
    00350     SpriteID i;
    00351
    00352     DEBUG(sprite, 3, "Fixing lru %u, inuse=" PRINTF_SIZE, _sprite_lru_counter, GetSpriteCacheUsage());
    00353
    00354     for (i = 0; i != _spritecache_items; i++) {
    00355       SpriteCache *sc = GetSpriteCache(i);
    00356       if (sc->ptr != NULL) {
    00357         if (sc->lru >= 0) {
    00358           sc->lru = -1;
    00359         } else if (sc->lru != -32768) {
    00360           sc->lru--;
    00361         }
    00362       }
    00363     }
    00364     _sprite_lru_counter = 0;
    00365   }
    00366
    00367   /* Compact sprite cache every now and then. */
    00368   if (++_compact_cache_counter >= 740) {
    00369     CompactSpriteCache();
    00370     _compact_cache_counter = 0;
    00371   }
    00372 }
    00373
    00376 static void CompactSpriteCache()
    00377 {
    00378   MemBlock *s;
    00379
    00380   DEBUG(sprite, 3, "Compacting sprite cache, inuse=" PRINTF_SIZE, GetSpriteCacheUsage());
    00381
    00382   for (s = _spritecache_ptr; s->size != 0;) {
    00383     if (s->size & S_FREE_MASK) {
    00384       MemBlock *next = NextBlock(s);
    00385       MemBlock temp;
    00386       SpriteID i;
    00387
    00388       /* Since free blocks are automatically coalesced, this should hold true. */
    00389       assert(!(next->size & S_FREE_MASK));
    00390
    00391       /* If the next block is the sentinel block, we can safely return */
    00392       if (next->size == 0) break;
    00393
    00394       /* Locate the sprite belonging to the next pointer. */
    00395       for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
    00396         assert(i != _spritecache_items);
    00397       }
    00398
    00399       GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
    00400       /* Swap this and the next block */
    00401       temp = *s;
    00402       memmove(s, next, next->size);
    00403       s = NextBlock(s);
    00404       *s = temp;
    00405
    00406       /* Coalesce free blocks */
    00407       while (NextBlock(s)->size & S_FREE_MASK) {
    00408         s->size += NextBlock(s)->size & ~S_FREE_MASK;
    00409       }
    00410     } else {
    00411       s = NextBlock(s);
    00412     }
    00413   }
    00414 }
    00415
    00416 static void DeleteEntryFromSpriteCache()
    00417 {
    00418   SpriteID i;
    00419   uint best = UINT_MAX;
    00420   MemBlock *s;
    00421   int cur_lru;
    00422
    00423   DEBUG(sprite, 3, "DeleteEntryFromSpriteCache, inuse=" PRINTF_SIZE, GetSpriteCacheUsage());
    00424
    00425   cur_lru = 0xffff;
    00426   for (i = 0; i != _spritecache_items; i++) {
    00427     SpriteCache *sc = GetSpriteCache(i);
    00428     if (sc->ptr != NULL && sc->lru < cur_lru) {
    00429       cur_lru = sc->lru;
    00430       best = i;
    00431     }
    00432   }
    00433
    00434   /* Display an error message and die, in case we found no sprite at all.
    00435    * This shouldn't really happen, unless all sprites are locked. */
    00436   if (best == UINT_MAX) error("Out of sprite memory");
    00437
    00438   /* Mark the block as free (the block must be in use) */
    00439   s = (MemBlock*)GetSpriteCache(best)->ptr - 1;
    00440   assert(!(s->size & S_FREE_MASK));
    00441   s->size |= S_FREE_MASK;
    00442   GetSpriteCache(best)->ptr = NULL;
    00443
    00444   /* And coalesce adjacent free blocks */
    00445   for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
    00446     if (s->size & S_FREE_MASK) {
    00447       while (NextBlock(s)->size & S_FREE_MASK) {
    00448         s->size += NextBlock(s)->size & ~S_FREE_MASK;
    00449       }
    00450     }
    00451   }
    00452 }
    00453
    00454 static void *AllocSprite(size_t mem_req)
    00455 {
    00456   mem_req += sizeof(MemBlock);
    00457
    00458   /* Align this to correct boundary. This also makes sure at least one
    00459    * bit is not used, so we can use it for other things. */
    00460   mem_req = Align(mem_req, S_FREE_MASK + 1);
    00461
    00462   for (;;) {
    00463     MemBlock *s;
    00464
    00465     for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
    00466       if (s->size & S_FREE_MASK) {
    00467         size_t cur_size = s->size & ~S_FREE_MASK;
    00468
    00469         /* Is the block exactly the size we need or
    00470          * big enough for an additional free block? */
    00471         if (cur_size == mem_req ||
    00472             cur_size >= mem_req + sizeof(MemBlock)) {
    00473           /* Set size and in use */
    00474           s->size = mem_req;
    00475
    00476           /* Do we need to inject a free block too? */
    00477           if (cur_size != mem_req) {
    00478             NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
    00479           }
    00480
    00481           return s->data;
    00482         }
    00483       }
    00484     }
    00485
    00486     /* Reached sentinel, but no block found yet. Delete some old entry. */
    00487     DeleteEntryFromSpriteCache();
    00488   }
    00489 }
    00490
    00498 static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc)
    00499 {
    00500   static const char * const sprite_types[] = {
    00501     "normal",        // ST_NORMAL
    00502     "map generator", // ST_MAPGEN
    00503     "character",     // ST_FONT
    00504     "recolour",      // ST_RECOLOUR
    00505   };
    00506
    00507   SpriteType available = sc->type;
    00508   if (requested == ST_FONT && available == ST_NORMAL) {
    00509     if (sc->ptr == NULL) sc->type = ST_FONT;
    00510     return GetRawSprite(sprite, sc->type);
    00511   }
    00512
    00513   byte warning_level = sc->warned ? 6 : 0;
    00514   sc->warned = true;
    00515   DEBUG(sprite, warning_level, "Tried to load %s sprite #%d as a %s sprite. Probable cause: NewGRF interference", sprite_types[available], sprite, sprite_types[requested]);
    00516
    00517   switch (requested) {
    00518     case ST_NORMAL:
    00519       if (sprite == SPR_IMG_QUERY) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'query' sprite a non-normal sprite?");
    00520       /* FALLTHROUGH */
    00521     case ST_FONT:
    00522       return GetRawSprite(SPR_IMG_QUERY, ST_NORMAL);
    00523     case ST_RECOLOUR:
    00524       if (sprite == PALETTE_TO_DARK_BLUE) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'PALETTE_TO_DARK_BLUE' sprite a non-remap sprite?");
    00525       return GetRawSprite(PALETTE_TO_DARK_BLUE, ST_RECOLOUR);
    00526     case ST_MAPGEN:
    00527       /* this shouldn't happen, overriding of ST_MAPGEN sprites is checked in LoadNextSprite()
    00528        * (the only case the check fails is when these sprites weren't even loaded...) */
    00529     default:
    00530       NOT_REACHED();
    00531   }
    00532 }
    00533
    00534 void *GetRawSprite(SpriteID sprite, SpriteType type)
    00535 {
    00536   assert(IsMapgenSpriteID(sprite) == (type == ST_MAPGEN));
    00537   assert(type < ST_INVALID);
    00538
    00539   if (!SpriteExists(sprite)) {
    00540     DEBUG(sprite, 1, "Tried to load non-existing sprite #%d. Probable cause: Wrong/missing NewGRFs", sprite);
    00541
    00542     /* SPR_IMG_QUERY is a BIG FAT RED ? */
    00543     sprite = SPR_IMG_QUERY;
    00544   }
    00545
    00546   SpriteCache *sc = GetSpriteCache(sprite);
    00547
    00548   if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc);
    00549
    00550   /* Update LRU */
    00551   sc->lru = ++_sprite_lru_counter;
    00552
    00553   void *p = sc->ptr;
    00554
    00555   /* Load the sprite, if it is not loaded, yet */
    00556   if (p == NULL) p = ReadSprite(sc, sprite, type);
    00557
    00558   return p;
    00559 }
    00560
    00561
    00562 void GfxInitSpriteMem()
    00563 {
    00564   /* initialize sprite cache heap */
    00565   if (_spritecache_ptr == NULL) _spritecache_ptr = (MemBlock*)MallocT<byte>(_sprite_cache_size * 1024 * 1024);
    00566
    00567   /* A big free block */
    00568   _spritecache_ptr->size = ((_sprite_cache_size * 1024 * 1024) - sizeof(MemBlock)) | S_FREE_MASK;
    00569   /* Sentinel block (identified by size == 0) */
    00570   NextBlock(_spritecache_ptr)->size = 0;
    00571
    00572   /* Reset the spritecache 'pool' */
    00573   free(_spritecache);
    00574   _spritecache_items = 0;
    00575   _spritecache = NULL;
    00576
    00577   _compact_cache_counter = 0;
    00578 }
    00579
    00580 /* static */ ReusableBuffer<SpriteLoader::CommonPixel> SpriteLoader::Sprite::buffer;