Add ScriptStoryPageElementList to get the contents of a page
[openttd/fttd.git] / src / gfxinit.cpp
blob109db2e08ad9c7a81dc901e4d4f826a7a5a3402a
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 "fontcache.h"
17 #include "gfx_func.h"
18 #include "transparency.h"
19 #include "blitter/factory.hpp"
20 #include "video/video_driver.hpp"
22 /* The type of set we're replacing */
23 #define SET_TYPE "graphics"
24 #include "base_media_func.h"
26 #include "table/sprites.h"
28 /** Whether the given NewGRFs must get a palette remap from windows to DOS or not. */
29 bool _palette_remap_grf[MAX_FILE_SLOTS];
31 #include "table/landscape_sprite.h"
33 /** Offsets for loading the different "replacement" sprites in the files. */
34 static const SpriteID * const _landscape_spriteindexes[] = {
35 _landscape_spriteindexes_arctic,
36 _landscape_spriteindexes_tropic,
37 _landscape_spriteindexes_toyland,
40 /**
41 * Load an old fashioned GRF file.
42 * @param filename The name of the file to open.
43 * @param load_index The offset of the first sprite.
44 * @param file_index The Fio offset to load the file in.
45 * @return The number of loaded sprites.
47 static uint LoadGrfFile(const char *filename, uint load_index, int file_index)
49 uint load_index_org = load_index;
50 uint sprite_id = 0;
52 FioOpenFile(file_index, filename, BASESET_DIR);
54 DEBUG(sprite, 2, "Reading grf-file '%s'", filename);
56 byte container_ver = GetGRFContainerVersion();
57 if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename);
58 ReadGRFSpriteOffsets(container_ver);
59 if (container_ver >= 2) {
60 /* Read compression. */
61 byte compression = FioReadByte();
62 if (compression != 0) usererror("Unsupported compression format");
65 while (LoadNextSprite(load_index, file_index, sprite_id, container_ver)) {
66 load_index++;
67 sprite_id++;
68 if (load_index >= MAX_SPRITES) {
69 usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
72 DEBUG(sprite, 2, "Currently %i sprites are loaded", load_index);
74 return load_index - load_index_org;
77 /**
78 * Load an old fashioned GRF file to replace already loaded sprites.
79 * @param filename The name of the file to open.
80 * @param index_tlb The offsets of each of the sprites.
81 * @param file_index The Fio offset to load the file in.
82 * @return The number of loaded sprites.
84 static void LoadGrfFileIndexed(const char *filename, const SpriteID *index_tbl, int file_index)
86 uint start;
87 uint sprite_id = 0;
89 FioOpenFile(file_index, filename, BASESET_DIR);
91 DEBUG(sprite, 2, "Reading indexed grf-file '%s'", filename);
93 byte container_ver = GetGRFContainerVersion();
94 if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename);
95 ReadGRFSpriteOffsets(container_ver);
96 if (container_ver >= 2) {
97 /* Read compression. */
98 byte compression = FioReadByte();
99 if (compression != 0) usererror("Unsupported compression format");
102 while ((start = *index_tbl++) != END) {
103 uint end = *index_tbl++;
105 do {
106 bool b = LoadNextSprite(start, file_index, sprite_id, container_ver);
107 assert(b);
108 sprite_id++;
109 } while (++start <= end);
114 * Checks whether the MD5 checksums of the files are correct.
116 * @note Also checks sample.cat and other required non-NewGRF GRFs for corruption.
118 void CheckExternalFiles()
120 if (BaseGraphics::GetUsedSet() == NULL || BaseSounds::GetUsedSet() == NULL) return;
122 const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
124 DEBUG(grf, 1, "Using the %s base graphics set", used_set->name);
126 static const size_t ERROR_MESSAGE_LENGTH = 256;
127 static const size_t MISSING_FILE_MESSAGE_LENGTH = 128;
129 /* Allocate for a message for each missing file and for one error
130 * message per set.
132 char error_msg[MISSING_FILE_MESSAGE_LENGTH * (GraphicsSet::NUM_FILES + SoundsSet::NUM_FILES) + 2 * ERROR_MESSAGE_LENGTH];
133 error_msg[0] = '\0';
134 char *add_pos = error_msg;
135 const char *last = lastof(error_msg);
137 if (used_set->GetNumInvalid() != 0) {
138 /* Not all files were loaded successfully, see which ones */
139 add_pos += seprintf(add_pos, last, "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", used_set->name);
140 for (uint i = 0; i < GraphicsSet::NUM_FILES; i++) {
141 MD5File::ChecksumResult res = GraphicsSet::CheckMD5(&used_set->files[i], BASESET_DIR);
142 if (res != MD5File::CR_MATCH) add_pos += seprintf(add_pos, last, "\t%s is %s (%s)\n", used_set->files[i].filename, res == MD5File::CR_MISMATCH ? "corrupt" : "missing", used_set->files[i].missing_warning);
144 add_pos += seprintf(add_pos, last, "\n");
147 const SoundsSet *sounds_set = BaseSounds::GetUsedSet();
148 if (sounds_set->GetNumInvalid() != 0) {
149 add_pos += seprintf(add_pos, last, "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", sounds_set->name);
151 assert_compile(SoundsSet::NUM_FILES == 1);
152 /* No need to loop each file, as long as there is only a single
153 * sound file. */
154 add_pos += seprintf(add_pos, last, "\t%s is %s (%s)\n", sounds_set->files->filename, SoundsSet::CheckMD5(sounds_set->files, BASESET_DIR) == MD5File::CR_MISMATCH ? "corrupt" : "missing", sounds_set->files->missing_warning);
157 if (add_pos != error_msg) ShowInfoF("%s", error_msg);
160 /** Actually load the sprite tables. */
161 static void LoadSpriteTables()
163 memset(_palette_remap_grf, 0, sizeof(_palette_remap_grf));
164 uint i = FIRST_GRF_SLOT;
165 const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
167 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
168 LoadGrfFile(used_set->files[GFT_BASE].filename, 0, i++);
171 * The second basic file always starts at the given location and does
172 * contain a different amount of sprites depending on the "type"; DOS
173 * has a few sprites less. However, we do not care about those missing
174 * sprites as they are not shown anyway (logos in intro game).
176 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
177 LoadGrfFile(used_set->files[GFT_LOGOS].filename, 4793, i++);
180 * Load additional sprites for climates other than temperate.
181 * This overwrites some of the temperate sprites, such as foundations
182 * and the ground sprites.
184 if (_settings_game.game_creation.landscape != LT_TEMPERATE) {
185 _palette_remap_grf[i] = (PAL_DOS != used_set->palette);
186 LoadGrfFileIndexed(
187 used_set->files[GFT_ARCTIC + _settings_game.game_creation.landscape - 1].filename,
188 _landscape_spriteindexes[_settings_game.game_creation.landscape - 1],
193 /* Initialize the unicode to sprite mapping table */
194 InitializeUnicodeGlyphMap();
197 * Load the base NewGRF with OTTD required graphics as first NewGRF.
198 * However, we do not want it to show up in the list of used NewGRFs,
199 * so we have to manually add it, and then remove it later.
201 GRFConfig *top = _grfconfig;
202 GRFConfig *master = new GRFConfig(used_set->files[GFT_EXTRA].filename);
204 /* We know the palette of the base set, so if the base NewGRF is not
205 * setting one, use the palette of the base set and not the global
206 * one which might be the wrong palette for this base NewGRF.
207 * The value set here might be overridden via action14 later. */
208 switch (used_set->palette) {
209 case PAL_DOS: master->palette |= GRFP_GRF_DOS; break;
210 case PAL_WINDOWS: master->palette |= GRFP_GRF_WINDOWS; break;
211 default: break;
213 FillGRFDetails(master, false, BASESET_DIR);
215 ClrBit(master->flags, GCF_INIT_ONLY);
216 master->next = top;
217 _grfconfig = master;
219 LoadNewGRF(SPR_NEWGRFS_BASE, i);
221 /* Free and remove the top element. */
222 delete master;
223 _grfconfig = top;
228 * Check blitter needed by NewGRF config and switch if needed.
229 * @return False when nothing changed, true otherwise.
231 static bool SwitchNewGRFBlitter()
233 /* Never switch if the blitter was specified by the user. */
234 if (!_blitter_autodetected) return false;
236 /* Null driver => dedicated server => do nothing. */
237 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return false;
239 /* Get preferred depth. */
240 uint depth_wanted_by_base = BaseGraphics::GetUsedSet()->blitter == BLT_32BPP ? 32 : 8;
241 uint depth_wanted_by_grf = 8;
242 for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
243 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND || HasBit(c->flags, GCF_INIT_ONLY)) continue;
244 if (c->palette & GRFP_BLT_32BPP) depth_wanted_by_grf = 32;
247 /* Search the best blitter. */
248 struct {
249 const char *name;
250 uint animation; ///< 0: no support, 1: do support, 2: both
251 uint min_base_depth, max_base_depth, min_grf_depth, max_grf_depth;
252 } replacement_blitters[] = {
253 #ifdef WITH_SSE
254 { "32bpp-sse4", 0, 32, 32, 8, 32 },
255 { "32bpp-ssse3", 0, 32, 32, 8, 32 },
256 { "32bpp-sse2", 0, 32, 32, 8, 32 },
257 { "32bpp-sse4-anim", 1, 32, 32, 8, 32 },
258 #endif
259 { "8bpp-optimized", 2, 8, 8, 8, 8 },
260 { "32bpp-optimized", 0, 8, 32, 8, 32 },
261 { "32bpp-anim", 1, 8, 32, 8, 32 },
264 const bool animation_wanted = HasBit(_display_opt, DO_FULL_ANIMATION);
265 const char *cur_blitter = BlitterFactory::GetCurrentBlitter()->GetName();
267 for (uint i = 0; i < lengthof(replacement_blitters); i++) {
268 if (animation_wanted && (replacement_blitters[i].animation == 0)) continue;
269 if (!animation_wanted && (replacement_blitters[i].animation == 1)) continue;
271 if (!IsInsideMM(depth_wanted_by_base, replacement_blitters[i].min_base_depth, replacement_blitters[i].max_base_depth + 1)) continue;
272 if (!IsInsideMM(depth_wanted_by_grf, replacement_blitters[i].min_grf_depth, replacement_blitters[i].max_grf_depth + 1)) continue;
273 const char *repl_blitter = replacement_blitters[i].name;
275 if (strcmp(repl_blitter, cur_blitter) == 0) return false;
276 if (BlitterFactory::GetBlitterFactory(repl_blitter) == NULL) continue;
278 DEBUG(misc, 1, "Switching blitter from '%s' to '%s'... ", cur_blitter, repl_blitter);
279 Blitter *new_blitter = BlitterFactory::SelectBlitter(repl_blitter);
280 if (new_blitter == NULL) NOT_REACHED();
281 DEBUG(misc, 1, "Successfully switched to %s.", repl_blitter);
282 break;
285 if (!_video_driver->AfterBlitterChange()) {
286 /* Failed to switch blitter, let's hope we can return to the old one. */
287 if (BlitterFactory::SelectBlitter(cur_blitter) == NULL || !_video_driver->AfterBlitterChange()) usererror("Failed to reinitialize video driver. Specify a fixed blitter in the config");
290 return true;
293 /** Check whether we still use the right blitter, or use another (better) one. */
294 void CheckBlitter()
296 if (!SwitchNewGRFBlitter()) return;
298 ClearFontCache();
299 GfxClearSpriteCache();
302 /** Initialise and load all the sprites. */
303 void GfxLoadSprites()
305 DEBUG(sprite, 2, "Loading sprite set %d", _settings_game.game_creation.landscape);
307 SwitchNewGRFBlitter();
308 ClearFontCache();
309 GfxInitSpriteMem();
310 LoadSpriteTables();
311 GfxInitPalettes();
313 UpdateCursorSize();
316 bool GraphicsSet::FillSetDetails(IniFile *ini, const char *path, const char *full_filename)
318 bool ret = this->BaseSet<GraphicsSet, MAX_GFT, true>::FillSetDetails(ini, path, full_filename, false);
319 if (ret) {
320 IniGroup *metadata = ini->GetGroup("metadata");
321 IniItem *item;
323 fetch_metadata("palette");
324 this->palette = (*item->value == 'D' || *item->value == 'd') ? PAL_DOS : PAL_WINDOWS;
326 /* Get optional blitter information. */
327 item = metadata->GetItem("blitter", false);
328 this->blitter = (item != NULL && *item->value == '3') ? BLT_32BPP : BLT_8BPP;
330 return ret;
334 * Calculate and check the MD5 hash of the supplied GRF.
335 * @param file The file get the hash of.
336 * @param subdir The sub directory to get the files from.
337 * @return
338 * - #CR_MATCH if the MD5 hash matches
339 * - #CR_MISMATCH if the MD5 does not match
340 * - #CR_NO_FILE if the file misses
342 /* static */ MD5File::ChecksumResult GraphicsSet::CheckMD5(const MD5File *file, Subdirectory subdir)
344 size_t size = 0;
345 FILE *f = FioFOpenFile(file->filename, "rb", subdir, &size);
346 if (f == NULL) return MD5File::CR_NO_FILE;
348 size_t max = GRFGetSizeOfDataSection(f);
350 FioFCloseFile(f);
352 return file->CheckMD5(subdir, max);
357 * Calculate and check the MD5 hash of the supplied filename.
358 * @param subdir The sub directory to get the files from
359 * @param max_size Only calculate the hash for this many bytes from the file start.
360 * @return
361 * - #CR_MATCH if the MD5 hash matches
362 * - #CR_MISMATCH if the MD5 does not match
363 * - #CR_NO_FILE if the file misses
365 MD5File::ChecksumResult MD5File::CheckMD5(Subdirectory subdir, size_t max_size) const
367 size_t size;
368 FILE *f = FioFOpenFile(this->filename, "rb", subdir, &size);
370 if (f == NULL) return CR_NO_FILE;
372 size = min(size, max_size);
374 Md5 checksum;
375 uint8 buffer[1024];
376 uint8 digest[16];
377 size_t len;
379 while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
380 size -= len;
381 checksum.Append(buffer, len);
384 FioFCloseFile(f);
386 checksum.Finish(digest);
387 return memcmp(this->hash, digest, sizeof(this->hash)) == 0 ? CR_MATCH : CR_MISMATCH;
390 /** Names corresponding to the GraphicsFileType */
391 static const char * const _graphics_file_names[] = { "base", "logos", "arctic", "tropical", "toyland", "extra" };
393 /** Implementation */
394 template <class T, size_t Tnum_files, bool Tsearch_in_tars>
395 /* static */ const char * const *BaseSet<T, Tnum_files, Tsearch_in_tars>::file_names = _graphics_file_names;
397 template <class Tbase_set>
398 /* static */ bool BaseMedia<Tbase_set>::DetermineBestSet()
400 if (BaseMedia<Tbase_set>::used_set != NULL) return true;
402 const Tbase_set *best = NULL;
403 for (const Tbase_set *c = BaseMedia<Tbase_set>::available_sets; c != NULL; c = c->next) {
404 /* Skip unusable sets */
405 if (c->GetNumMissing() != 0) continue;
407 if (best == NULL ||
408 (best->fallback && !c->fallback) ||
409 best->valid_files < c->valid_files ||
410 (best->valid_files == c->valid_files && (
411 (best->shortname == c->shortname && best->version < c->version) ||
412 (best->palette != PAL_DOS && c->palette == PAL_DOS)))) {
413 best = c;
417 BaseMedia<Tbase_set>::used_set = best;
418 return BaseMedia<Tbase_set>::used_set != NULL;
421 template <class Tbase_set>
422 /* static */ const char *BaseMedia<Tbase_set>::GetExtension()
424 return ".obg"; // OpenTTD Base Graphics
427 INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia<GraphicsSet>, GraphicsSet)