Let HandleWindowDragging return a boolean status
[openttd/fttd.git] / src / gfxinit.cpp
blob44fbafd0933356e2345f0c266d7303f19b4705bd
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 GRFHeader header;
60 if (!ReadGRFHeader (&header)) {
61 usererror ("Base grf '%s' is corrupt", filename);
64 ReadGRFSpriteOffsets (&header);
66 while (LoadNextSprite (load_index, file_index, sprite_id, header.version)) {
67 load_index++;
68 sprite_id++;
69 if (load_index >= MAX_SPRITES) {
70 usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
73 DEBUG(sprite, 2, "Currently %i sprites are loaded", load_index);
75 return load_index - load_index_org;
78 /**
79 * Load an old fashioned GRF file to replace already loaded sprites.
80 * @param filename The name of the file to open.
81 * @param index_tlb The offsets of each of the sprites.
82 * @param file_index The Fio offset to load the file in.
83 * @return The number of loaded sprites.
85 static void LoadGrfFileIndexed(const char *filename, const SpriteID *index_tbl, int file_index)
87 uint start;
88 uint sprite_id = 0;
90 FioOpenFile(file_index, filename, BASESET_DIR);
92 DEBUG(sprite, 2, "Reading indexed grf-file '%s'", filename);
94 GRFHeader header;
95 if (!ReadGRFHeader (&header)) {
96 usererror ("Base grf '%s' is corrupt", filename);
99 ReadGRFSpriteOffsets (&header);
101 while ((start = *index_tbl++) != END) {
102 uint end = *index_tbl++;
104 do {
105 bool b = LoadNextSprite (start, file_index, sprite_id, header.version);
106 assert(b);
107 sprite_id++;
108 } while (++start <= end);
113 * Set the graphics set to be used.
114 * @param name of the set to use
115 * @return true if it could be loaded
117 bool BaseGraphics::SetSet (const char *name)
119 if (!BaseMedia<GraphicsSet>::SetSet (name)) return false;
121 const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
122 if (used_set == NULL) return true;
124 DEBUG(grf, 1, "Using the %s base graphics set", used_set->get_name());
126 if (used_set->GetNumInvalid() != 0) {
127 /* Not all files were loaded successfully, see which ones */
128 sstring<1024> error_msg;
129 for (uint i = 0; i < GraphicsSet::NUM_FILES; i++) {
130 GraphicsSet::FileDesc::Status status = used_set->files[i].status;
131 if (status != GraphicsSet::FileDesc::MATCH) {
132 error_msg.append_fmt ("\t%s is %s (%s)\n",
133 used_set->files[i].filename,
134 status == GraphicsSet::FileDesc::MISMATCH ? "corrupt" : "missing",
135 used_set->files[i].missing_warning);
138 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());
141 return true;
145 * Set the sounds set to be used.
146 * @param name of the set to use
147 * @return true if it could be loaded
149 bool BaseSounds::SetSet (const char *name)
151 if (!BaseMedia<SoundsSet>::SetSet (name)) return false;
153 const SoundsSet *sounds_set = BaseSounds::GetUsedSet();
154 if (sounds_set == NULL) return true;
156 if (sounds_set->GetNumInvalid() != 0) {
157 assert_compile(SoundsSet::NUM_FILES == 1);
158 /* No need to loop each file, as long as there is only a single
159 * sound file. */
160 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",
161 sounds_set->get_name(), sounds_set->files->filename,
162 sounds_set->files->status == SoundsSet::FileDesc::MISMATCH ? "corrupt" : "missing",
163 sounds_set->files->missing_warning);
166 return true;
169 /** Actually load the sprite tables. */
170 static void LoadSpriteTables()
172 memset(_palette_remap_grf, 0, sizeof(_palette_remap_grf));
173 uint i = FIRST_GRF_SLOT;
174 const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
176 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
177 LoadGrfFile(used_set->files[GFT_BASE].filename, 0, i++);
180 * The second basic file always starts at the given location and does
181 * contain a different amount of sprites depending on the "type"; DOS
182 * has a few sprites less. However, we do not care about those missing
183 * sprites as they are not shown anyway (logos in intro game).
185 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
186 LoadGrfFile(used_set->files[GFT_LOGOS].filename, 4793, i++);
189 * Load additional sprites for climates other than temperate.
190 * This overwrites some of the temperate sprites, such as foundations
191 * and the ground sprites.
193 if (_settings_game.game_creation.landscape != LT_TEMPERATE) {
194 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
195 LoadGrfFileIndexed(
196 used_set->files[GFT_ARCTIC + _settings_game.game_creation.landscape - 1].filename,
197 _landscape_spriteindexes[_settings_game.game_creation.landscape - 1],
202 /* Initialize the unicode to sprite mapping table */
203 InitializeUnicodeGlyphMap();
206 * Load the base and extra NewGRF with OTTD required graphics as first NewGRF.
207 * However, we do not want it to show up in the list of used NewGRFs,
208 * so we have to manually add it, and then remove it later.
210 GRFConfig *top = _grfconfig;
212 /* Default extra graphics */
213 GRFConfig *master = new GRFConfig("OPENTTD.GRF");
214 master->palette |= GRFP_GRF_DOS;
215 FillGRFDetails(master, false, BASESET_DIR);
216 ClrBit(master->flags, GCF_INIT_ONLY);
218 /* Baseset extra graphics */
219 GRFConfig *extra = new GRFConfig(used_set->files[GFT_EXTRA].filename);
221 /* We know the palette of the base set, so if the base NewGRF is not
222 * setting one, use the palette of the base set and not the global
223 * one which might be the wrong palette for this base NewGRF.
224 * The value set here might be overridden via action14 later. */
225 switch (used_set->palette) {
226 case PAL_DOS: extra->palette |= GRFP_GRF_DOS; break;
227 case PAL_WINDOWS: extra->palette |= GRFP_GRF_WINDOWS; break;
228 default: break;
230 FillGRFDetails(extra, false, BASESET_DIR);
231 ClrBit(extra->flags, GCF_INIT_ONLY);
233 extra->next = top;
234 master->next = extra;
235 _grfconfig = master;
237 LoadNewGRF(SPR_NEWGRFS_BASE, i, 2);
239 uint total_extra_graphics = SPR_NEWGRFS_BASE - SPR_OPENTTD_BASE;
240 _missing_extra_graphics = GetSpriteCountForSlot(i, SPR_OPENTTD_BASE, SPR_NEWGRFS_BASE);
241 DEBUG(sprite, 1, "%u extra sprites, %u from baseset, %u from fallback", total_extra_graphics, total_extra_graphics - _missing_extra_graphics, _missing_extra_graphics);
243 /* The original baseset extra graphics intentionally make use of the fallback graphics.
244 * Let's say everything which provides less than 500 sprites misses the rest intentionally. */
245 if (500 + _missing_extra_graphics > total_extra_graphics) _missing_extra_graphics = 0;
247 /* Free and remove the top element. */
248 delete extra;
249 delete master;
250 _grfconfig = top;
255 * Select the blitter needed by NewGRF config.
256 * @return The blitter to switch to.
258 static const Blitter::Info *SelectNewGRFBlitter (void)
260 /* Get preferred depth.
261 * - base_wants_32bpp: Depth required by the baseset, i.e. the majority of the sprites.
262 * - grf_wants_32bpp: Depth required by some NewGRF.
263 * Both can force using a 32bpp blitter. base_wants_32bpp is used to select
264 * between multiple 32bpp blitters, which perform differently with 8bpp sprites.
266 bool base_wants_32bpp = BaseGraphics::GetUsedSet()->blitter == BLT_32BPP;
267 bool grf_wants_32bpp;
268 if (_support8bpp == S8BPP_NONE) {
269 grf_wants_32bpp = true;
270 } else {
271 grf_wants_32bpp = false;
272 for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
273 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND || HasBit(c->flags, GCF_INIT_ONLY)) continue;
274 if (c->palette & GRFP_BLT_32BPP) {
275 grf_wants_32bpp = true;
276 break;
281 /* Search the best blitter. */
282 return Blitter::choose (HasBit(_display_opt, DO_FULL_ANIMATION),
283 base_wants_32bpp, grf_wants_32bpp);
287 * Check blitter needed by NewGRF config and switch if needed.
288 * @return False when nothing changed, true otherwise.
290 static bool SwitchNewGRFBlitter()
292 /* Never switch if the blitter was specified by the user. */
293 if (!Blitter::autodetected) return false;
295 /* Null driver => dedicated server => do nothing. */
296 if (Blitter::get()->screen_depth == 0) return false;
298 const Blitter::Info *repl = SelectNewGRFBlitter();
299 /* The replacement blitter should always be available. */
300 assert (repl != NULL);
301 const Blitter::Info *cur = Blitter::get();
302 if (repl == cur) return false;
304 DEBUG(misc, 1, "Switching blitter from '%s' to '%s'... ", cur->name, repl->name);
305 if (!VideoDriver::GetActiveDriver()->SwitchBlitter (repl)) {
306 usererror ("Failed to reinitialize video driver. Specify a fixed blitter in the config.");
309 return true;
312 /** Check whether we still use the right blitter, or use another (better) one. */
313 void CheckBlitter()
315 if (!SwitchNewGRFBlitter()) return;
317 ClearFontCache();
318 GfxClearSpriteCache();
319 ReInitAllWindows();
322 /** Initialise and load all the sprites. */
323 void GfxLoadSprites()
325 DEBUG(sprite, 2, "Loading sprite set %d", _settings_game.game_creation.landscape);
327 SwitchNewGRFBlitter();
328 ClearFontCache();
329 GfxInitSpriteMem();
330 LoadSpriteTables();
331 GfxInitPalettes();
333 UpdateCursorSize();
336 bool GraphicsSet::FillSetDetails(IniFile *ini, const char *path, const char *full_filename)
338 bool ret = this->BaseSet<GraphicsSet, MAX_GFT>::FillSetDetails (ini, path, full_filename, false);
339 if (ret) {
340 const IniGroup *metadata = ini->get_group ("metadata");
341 const IniItem *item;
343 item = this->fetch_metadata (metadata, "palette", full_filename);
344 if (item == NULL) return false;
345 this->palette = (*item->value == 'D' || *item->value == 'd') ? PAL_DOS : PAL_WINDOWS;
347 /* Get optional blitter information. */
348 item = metadata->find ("blitter");
349 this->blitter = (item != NULL && *item->value == '3') ? BLT_32BPP : BLT_8BPP;
351 return ret;
355 * Calculate and check the MD5 hash of the supplied file.
356 * @param f The file to check.
357 * @param hash The hash to check against.
358 * @param size Use only this many bytes from the file.
359 * @return Whether the file matches the given hash.
361 static bool check_md5 (FILE *f, const byte (&hash) [16], size_t size)
363 Md5 checksum;
364 byte buffer[1024];
366 while (size != 0) {
367 size_t len = fread (buffer, 1, min (size, sizeof(buffer)), f);
368 if (len == 0) break;
369 size -= len;
370 checksum.Append (buffer, len);
373 FioFCloseFile(f);
375 byte digest[16];
376 checksum.Finish (digest);
377 return memcmp (hash, digest, sizeof(hash)) == 0;
381 * Calculate and check the MD5 hash of the supplied GRF.
382 * @param file The file get the hash of.
383 * @return
384 * - #MATCH if the MD5 hash matches
385 * - #MISMATCH if the MD5 does not match
386 * - #MISSING if the file misses
388 /* static */ GraphicsSet::FileDesc::Status GraphicsSet::CheckMD5 (const FileDesc *file)
390 size_t size = 0;
391 FILE *f = FioFOpenFile (file->filename, "rb", BASESET_DIR, &size);
392 if (f == NULL) return FileDesc::MISSING;
394 size = min (size, GRFGetSizeOfDataSection (f));
396 fseek (f, 0, SEEK_SET);
398 return check_md5 (f, file->hash, size) ?
399 FileDesc::MATCH : FileDesc::MISMATCH;
403 * Calculate and check the MD5 hash of the supplied file.
404 * @param file The file get the hash of.
405 * @return
406 * - #MATCH if the MD5 hash matches
407 * - #MISMATCH if the MD5 does not match
408 * - #MISSING if the file misses
410 BaseSetDesc::FileDesc::Status BaseSetDesc::CheckMD5 (const FileDesc *file)
412 size_t size;
413 FILE *f = FioFOpenFile (file->filename, "rb", BASESET_DIR, &size);
415 if (f == NULL) return FileDesc::MISSING;
417 return check_md5 (f, file->hash, size) ?
418 FileDesc::MATCH : FileDesc::MISMATCH;
421 /** Names corresponding to the GraphicsFileType */
422 const char * const GraphicsSet::file_names [MAX_GFT] =
423 { "base", "logos", "arctic", "tropical", "toyland", "extra" };
425 INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia<GraphicsSet>, GraphicsSet)