Translations update
[openttd/fttd.git] / src / gfxinit.cpp
blobd219b823de5b7b60efe735c211bdbb3d061f9701
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file gfxinit.cpp Initializing of the (GRF) graphics. */
12 #include "stdafx.h"
13 #include "fios.h"
14 #include "newgrf.h"
15 #include "3rdparty/md5/md5.h"
16 #include "font.h"
17 #include "gfx_func.h"
18 #include "transparency.h"
19 #include "blitter/blitter.h"
20 #include "video/video_driver.hpp"
21 #include "window_func.h"
22 #include "base_media_func.h"
24 /* The type of set we're replacing */
25 const char GraphicsSet::set_type[] = "graphics";
27 const char GraphicsSet::extension[] = ".obg"; // OpenTTD Base Graphics
29 #include "table/sprites.h"
31 /** Whether the given NewGRFs must get a palette remap from windows to DOS or not. */
32 bool _palette_remap_grf[MAX_FILE_SLOTS];
34 #include "table/landscape_sprite.h"
36 /** Offsets for loading the different "replacement" sprites in the files. */
37 static const SpriteID * const _landscape_spriteindexes[] = {
38 _landscape_spriteindexes_arctic,
39 _landscape_spriteindexes_tropic,
40 _landscape_spriteindexes_toyland,
43 /**
44 * Load an old fashioned GRF file.
45 * @param filename The name of the file to open.
46 * @param load_index The offset of the first sprite.
47 * @param file_index The Fio offset to load the file in.
48 * @return The number of loaded sprites.
50 static uint LoadGrfFile(const char *filename, uint load_index, int file_index)
52 uint load_index_org = load_index;
53 uint sprite_id = 0;
55 FioOpenFile(file_index, filename, BASESET_DIR);
57 DEBUG(sprite, 2, "Reading grf-file '%s'", filename);
59 byte container_ver = GetGRFContainerVersion();
60 if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename);
61 ReadGRFSpriteOffsets(container_ver);
62 if (container_ver >= 2) {
63 /* Read compression. */
64 byte compression = FioReadByte();
65 if (compression != 0) usererror("Unsupported compression format");
68 while (LoadNextSprite(load_index, file_index, sprite_id, container_ver)) {
69 load_index++;
70 sprite_id++;
71 if (load_index >= MAX_SPRITES) {
72 usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
75 DEBUG(sprite, 2, "Currently %i sprites are loaded", load_index);
77 return load_index - load_index_org;
80 /**
81 * Load an old fashioned GRF file to replace already loaded sprites.
82 * @param filename The name of the file to open.
83 * @param index_tlb The offsets of each of the sprites.
84 * @param file_index The Fio offset to load the file in.
85 * @return The number of loaded sprites.
87 static void LoadGrfFileIndexed(const char *filename, const SpriteID *index_tbl, int file_index)
89 uint start;
90 uint sprite_id = 0;
92 FioOpenFile(file_index, filename, BASESET_DIR);
94 DEBUG(sprite, 2, "Reading indexed grf-file '%s'", filename);
96 byte container_ver = GetGRFContainerVersion();
97 if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename);
98 ReadGRFSpriteOffsets(container_ver);
99 if (container_ver >= 2) {
100 /* Read compression. */
101 byte compression = FioReadByte();
102 if (compression != 0) usererror("Unsupported compression format");
105 while ((start = *index_tbl++) != END) {
106 uint end = *index_tbl++;
108 do {
109 bool b = LoadNextSprite(start, file_index, sprite_id, container_ver);
110 assert(b);
111 sprite_id++;
112 } while (++start <= end);
117 * Set the graphics set to be used.
118 * @param name of the set to use
119 * @return true if it could be loaded
121 bool BaseGraphics::SetSet (const char *name)
123 if (!BaseMedia<GraphicsSet>::SetSet (name)) return false;
125 const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
126 if (used_set == NULL) return true;
128 DEBUG(grf, 1, "Using the %s base graphics set", used_set->get_name());
130 if (used_set->GetNumInvalid() != 0) {
131 /* Not all files were loaded successfully, see which ones */
132 sstring<1024> error_msg;
133 for (uint i = 0; i < GraphicsSet::NUM_FILES; i++) {
134 GraphicsSet::FileDesc::Status status = used_set->files[i].status;
135 if (status != GraphicsSet::FileDesc::MATCH) {
136 error_msg.append_fmt ("\t%s is %s (%s)\n",
137 used_set->files[i].filename,
138 status == GraphicsSet::FileDesc::MISMATCH ? "corrupt" : "missing",
139 used_set->files[i].missing_warning);
142 ShowInfoF ("Trying to load graphics set '%s', but it is incomplete. The game will probably not run correctly until you properly install this set or select another one. See section 4.1 of readme.txt.\n\nThe following files are corrupted or missing:\n%s", used_set->get_name(), error_msg.c_str());
145 return true;
149 * Set the sounds set to be used.
150 * @param name of the set to use
151 * @return true if it could be loaded
153 bool BaseSounds::SetSet (const char *name)
155 if (!BaseMedia<SoundsSet>::SetSet (name)) return false;
157 const SoundsSet *sounds_set = BaseSounds::GetUsedSet();
158 if (sounds_set == NULL) return true;
160 if (sounds_set->GetNumInvalid() != 0) {
161 assert_compile(SoundsSet::NUM_FILES == 1);
162 /* No need to loop each file, as long as there is only a single
163 * sound file. */
164 ShowInfoF ("Trying to load sound set '%s', but it is incomplete. The game will probably not run correctly until you properly install this set or select another one. See section 4.1 of readme.txt.\n\nThe following files are corrupted or missing:\n\t%s is %s (%s)\n",
165 sounds_set->get_name(), sounds_set->files->filename,
166 sounds_set->files->status == SoundsSet::FileDesc::MISMATCH ? "corrupt" : "missing",
167 sounds_set->files->missing_warning);
170 return true;
173 /** Actually load the sprite tables. */
174 static void LoadSpriteTables()
176 memset(_palette_remap_grf, 0, sizeof(_palette_remap_grf));
177 uint i = FIRST_GRF_SLOT;
178 const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
180 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
181 LoadGrfFile(used_set->files[GFT_BASE].filename, 0, i++);
184 * The second basic file always starts at the given location and does
185 * contain a different amount of sprites depending on the "type"; DOS
186 * has a few sprites less. However, we do not care about those missing
187 * sprites as they are not shown anyway (logos in intro game).
189 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
190 LoadGrfFile(used_set->files[GFT_LOGOS].filename, 4793, i++);
193 * Load additional sprites for climates other than temperate.
194 * This overwrites some of the temperate sprites, such as foundations
195 * and the ground sprites.
197 if (_settings_game.game_creation.landscape != LT_TEMPERATE) {
198 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
199 LoadGrfFileIndexed(
200 used_set->files[GFT_ARCTIC + _settings_game.game_creation.landscape - 1].filename,
201 _landscape_spriteindexes[_settings_game.game_creation.landscape - 1],
206 /* Initialize the unicode to sprite mapping table */
207 InitializeUnicodeGlyphMap();
210 * Load the base and extra NewGRF with OTTD required graphics as first NewGRF.
211 * However, we do not want it to show up in the list of used NewGRFs,
212 * so we have to manually add it, and then remove it later.
214 GRFConfig *top = _grfconfig;
216 /* Default extra graphics */
217 GRFConfig *master = new GRFConfig("OPENTTD.GRF");
218 master->palette |= GRFP_GRF_DOS;
219 FillGRFDetails(master, false, BASESET_DIR);
220 ClrBit(master->flags, GCF_INIT_ONLY);
222 /* Baseset extra graphics */
223 GRFConfig *extra = new GRFConfig(used_set->files[GFT_EXTRA].filename);
225 /* We know the palette of the base set, so if the base NewGRF is not
226 * setting one, use the palette of the base set and not the global
227 * one which might be the wrong palette for this base NewGRF.
228 * The value set here might be overridden via action14 later. */
229 switch (used_set->palette) {
230 case PAL_DOS: extra->palette |= GRFP_GRF_DOS; break;
231 case PAL_WINDOWS: extra->palette |= GRFP_GRF_WINDOWS; break;
232 default: break;
234 FillGRFDetails(extra, false, BASESET_DIR);
235 ClrBit(extra->flags, GCF_INIT_ONLY);
237 extra->next = top;
238 master->next = extra;
239 _grfconfig = master;
241 LoadNewGRF(SPR_NEWGRFS_BASE, i, 2);
243 uint total_extra_graphics = SPR_NEWGRFS_BASE - SPR_OPENTTD_BASE;
244 _missing_extra_graphics = GetSpriteCountForSlot(i, SPR_OPENTTD_BASE, SPR_NEWGRFS_BASE);
245 DEBUG(sprite, 1, "%u extra sprites, %u from baseset, %u from fallback", total_extra_graphics, total_extra_graphics - _missing_extra_graphics, _missing_extra_graphics);
247 /* The original baseset extra graphics intentionally make use of the fallback graphics.
248 * Let's say everything which provides less than 500 sprites misses the rest intentionally. */
249 if (500 + _missing_extra_graphics > total_extra_graphics) _missing_extra_graphics = 0;
251 /* Free and remove the top element. */
252 delete extra;
253 delete master;
254 _grfconfig = top;
259 * Select the blitter needed by NewGRF config.
260 * @return The blitter to switch to.
262 static const Blitter::Info *SelectNewGRFBlitter (void)
264 /* Get preferred depth.
265 * - base_wants_32bpp: Depth required by the baseset, i.e. the majority of the sprites.
266 * - grf_wants_32bpp: Depth required by some NewGRF.
267 * Both can force using a 32bpp blitter. base_wants_32bpp is used to select
268 * between multiple 32bpp blitters, which perform differently with 8bpp sprites.
270 bool base_wants_32bpp = BaseGraphics::GetUsedSet()->blitter == BLT_32BPP;
271 bool grf_wants_32bpp;
272 if (_support8bpp == S8BPP_NONE) {
273 grf_wants_32bpp = true;
274 } else {
275 grf_wants_32bpp = false;
276 for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
277 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND || HasBit(c->flags, GCF_INIT_ONLY)) continue;
278 if (c->palette & GRFP_BLT_32BPP) {
279 grf_wants_32bpp = true;
280 break;
285 /* Search the best blitter. */
286 return Blitter::choose (HasBit(_display_opt, DO_FULL_ANIMATION),
287 base_wants_32bpp, grf_wants_32bpp);
291 * Check blitter needed by NewGRF config and switch if needed.
292 * @return False when nothing changed, true otherwise.
294 static bool SwitchNewGRFBlitter()
296 /* Never switch if the blitter was specified by the user. */
297 if (!Blitter::autodetected) return false;
299 /* Null driver => dedicated server => do nothing. */
300 if (Blitter::get()->screen_depth == 0) return false;
302 const Blitter::Info *repl = SelectNewGRFBlitter();
303 /* The replacement blitter should always be available. */
304 assert (repl != NULL);
305 const Blitter::Info *cur = Blitter::get();
306 if (repl == cur) return false;
308 DEBUG(misc, 1, "Switching blitter from '%s' to '%s'... ", cur->name, repl->name);
309 if (!VideoDriver::GetActiveDriver()->SwitchBlitter (repl)) {
310 usererror ("Failed to reinitialize video driver. Specify a fixed blitter in the config.");
313 return true;
316 /** Check whether we still use the right blitter, or use another (better) one. */
317 void CheckBlitter()
319 if (!SwitchNewGRFBlitter()) return;
321 ClearFontCache();
322 GfxClearSpriteCache();
323 ReInitAllWindows();
326 /** Initialise and load all the sprites. */
327 void GfxLoadSprites()
329 DEBUG(sprite, 2, "Loading sprite set %d", _settings_game.game_creation.landscape);
331 SwitchNewGRFBlitter();
332 ClearFontCache();
333 GfxInitSpriteMem();
334 LoadSpriteTables();
335 GfxInitPalettes();
337 UpdateCursorSize();
340 bool GraphicsSet::FillSetDetails(IniFile *ini, const char *path, const char *full_filename)
342 bool ret = this->BaseSet<GraphicsSet, MAX_GFT>::FillSetDetails (ini, path, full_filename, false);
343 if (ret) {
344 const IniGroup *metadata = ini->get_group ("metadata");
345 const IniItem *item;
347 item = this->fetch_metadata (metadata, "palette", full_filename);
348 if (item == NULL) return false;
349 this->palette = (*item->value == 'D' || *item->value == 'd') ? PAL_DOS : PAL_WINDOWS;
351 /* Get optional blitter information. */
352 item = metadata->find ("blitter");
353 this->blitter = (item != NULL && *item->value == '3') ? BLT_32BPP : BLT_8BPP;
355 return ret;
359 * Calculate and check the MD5 hash of the supplied file.
360 * @param f The file to check.
361 * @param hash The hash to check against.
362 * @param size Use only this many bytes from the file.
363 * @return Whether the file matches the given hash.
365 static bool check_md5 (FILE *f, const byte (&hash) [16], size_t size)
367 Md5 checksum;
368 byte buffer[1024];
370 while (size != 0) {
371 size_t len = fread (buffer, 1, min (size, sizeof(buffer)), f);
372 if (len == 0) break;
373 size -= len;
374 checksum.Append (buffer, len);
377 FioFCloseFile(f);
379 byte digest[16];
380 checksum.Finish (digest);
381 return memcmp (hash, digest, sizeof(hash)) == 0;
385 * Calculate and check the MD5 hash of the supplied GRF.
386 * @param file The file get the hash of.
387 * @return
388 * - #MATCH if the MD5 hash matches
389 * - #MISMATCH if the MD5 does not match
390 * - #MISSING if the file misses
392 /* static */ GraphicsSet::FileDesc::Status GraphicsSet::CheckMD5 (const FileDesc *file)
394 size_t size = 0;
395 FILE *f = FioFOpenFile (file->filename, "rb", BASESET_DIR, &size);
396 if (f == NULL) return FileDesc::MISSING;
398 size = min (size, GRFGetSizeOfDataSection (f));
400 fseek (f, 0, SEEK_SET);
402 return check_md5 (f, file->hash, size) ?
403 FileDesc::MATCH : FileDesc::MISMATCH;
407 * Calculate and check the MD5 hash of the supplied file.
408 * @param file The file get the hash of.
409 * @return
410 * - #MATCH if the MD5 hash matches
411 * - #MISMATCH if the MD5 does not match
412 * - #MISSING if the file misses
414 BaseSetDesc::FileDesc::Status BaseSetDesc::CheckMD5 (const FileDesc *file)
416 size_t size;
417 FILE *f = FioFOpenFile (file->filename, "rb", BASESET_DIR, &size);
419 if (f == NULL) return FileDesc::MISSING;
421 return check_md5 (f, file->hash, size) ?
422 FileDesc::MATCH : FileDesc::MISMATCH;
425 /** Names corresponding to the GraphicsFileType */
426 const char * const GraphicsSet::file_names [MAX_GFT] =
427 { "base", "logos", "arctic", "tropical", "toyland", "extra" };
429 INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia<GraphicsSet>, GraphicsSet)