2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 /** @file gfxinit.cpp Initializing of the (GRF) graphics. */
13 #include "3rdparty/md5/md5.h"
14 #include "fontcache.h"
16 #include "transparency.h"
17 #include "blitter/factory.hpp"
18 #include "video/video_driver.hpp"
19 #include "window_func.h"
21 /* The type of set we're replacing */
22 #define SET_TYPE "graphics"
23 #include "base_media_func.h"
25 #include "table/sprites.h"
27 #include "safeguards.h"
29 /** Whether the given NewGRFs must get a palette remap from windows to DOS or not. */
30 bool _palette_remap_grf
[MAX_FILE_SLOTS
];
32 #include "table/landscape_sprite.h"
34 /** Offsets for loading the different "replacement" sprites in the files. */
35 static const SpriteID
* const _landscape_spriteindexes
[] = {
36 _landscape_spriteindexes_arctic
,
37 _landscape_spriteindexes_tropic
,
38 _landscape_spriteindexes_toyland
,
42 * Load an old fashioned GRF file.
43 * @param filename The name of the file to open.
44 * @param load_index The offset of the first sprite.
45 * @param file_index The Fio offset to load the file in.
46 * @return The number of loaded sprites.
48 static uint
LoadGrfFile(const char *filename
, uint load_index
, int file_index
)
50 uint load_index_org
= load_index
;
53 FioOpenFile(file_index
, filename
, BASESET_DIR
);
55 DEBUG(sprite
, 2, "Reading grf-file '%s'", filename
);
57 byte container_ver
= GetGRFContainerVersion();
58 if (container_ver
== 0) usererror("Base grf '%s' is corrupt", filename
);
59 ReadGRFSpriteOffsets(container_ver
);
60 if (container_ver
>= 2) {
61 /* Read compression. */
62 byte compression
= FioReadByte();
63 if (compression
!= 0) usererror("Unsupported compression format");
66 while (LoadNextSprite(load_index
, file_index
, sprite_id
, container_ver
)) {
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
;
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_tbl 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
)
90 FioOpenFile(file_index
, filename
, BASESET_DIR
);
92 DEBUG(sprite
, 2, "Reading indexed grf-file '%s'", filename
);
94 byte container_ver
= GetGRFContainerVersion();
95 if (container_ver
== 0) usererror("Base grf '%s' is corrupt", filename
);
96 ReadGRFSpriteOffsets(container_ver
);
97 if (container_ver
>= 2) {
98 /* Read compression. */
99 byte compression
= FioReadByte();
100 if (compression
!= 0) usererror("Unsupported compression format");
103 while ((start
= *index_tbl
++) != END
) {
104 uint end
= *index_tbl
++;
107 bool b
= LoadNextSprite(start
, file_index
, sprite_id
, container_ver
);
110 } while (++start
<= end
);
115 * Checks whether the MD5 checksums of the files are correct.
117 * @note Also checks sample.cat and other required non-NewGRF GRFs for corruption.
119 void CheckExternalFiles()
121 if (BaseGraphics::GetUsedSet() == nullptr || BaseSounds::GetUsedSet() == nullptr) return;
123 const GraphicsSet
*used_set
= BaseGraphics::GetUsedSet();
125 DEBUG(grf
, 1, "Using the %s base graphics set", used_set
->name
);
127 static const size_t ERROR_MESSAGE_LENGTH
= 256;
128 static const size_t MISSING_FILE_MESSAGE_LENGTH
= 128;
130 /* Allocate for a message for each missing file and for one error
133 char error_msg
[MISSING_FILE_MESSAGE_LENGTH
* (GraphicsSet::NUM_FILES
+ SoundsSet::NUM_FILES
) + 2 * ERROR_MESSAGE_LENGTH
];
135 char *add_pos
= error_msg
;
136 const char *last
= lastof(error_msg
);
138 if (used_set
->GetNumInvalid() != 0) {
139 /* Not all files were loaded successfully, see which ones */
140 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.md.\n\nThe following files are corrupted or missing:\n", used_set
->name
);
141 for (uint i
= 0; i
< GraphicsSet::NUM_FILES
; i
++) {
142 MD5File::ChecksumResult res
= GraphicsSet::CheckMD5(&used_set
->files
[i
], BASESET_DIR
);
143 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
);
145 add_pos
+= seprintf(add_pos
, last
, "\n");
148 const SoundsSet
*sounds_set
= BaseSounds::GetUsedSet();
149 if (sounds_set
->GetNumInvalid() != 0) {
150 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.md.\n\nThe following files are corrupted or missing:\n", sounds_set
->name
);
152 assert_compile(SoundsSet::NUM_FILES
== 1);
153 /* No need to loop each file, as long as there is only a single
155 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
);
158 if (add_pos
!= error_msg
) ShowInfoF("%s", error_msg
);
161 /** Actually load the sprite tables. */
162 static void LoadSpriteTables()
164 memset(_palette_remap_grf
, 0, sizeof(_palette_remap_grf
));
165 uint i
= FIRST_GRF_SLOT
;
166 const GraphicsSet
*used_set
= BaseGraphics::GetUsedSet();
168 _palette_remap_grf
[i
] = (PAL_DOS
!= used_set
->palette
);
169 LoadGrfFile(used_set
->files
[GFT_BASE
].filename
, 0, i
++);
172 * The second basic file always starts at the given location and does
173 * contain a different amount of sprites depending on the "type"; DOS
174 * has a few sprites less. However, we do not care about those missing
175 * sprites as they are not shown anyway (logos in intro game).
177 _palette_remap_grf
[i
] = (PAL_DOS
!= used_set
->palette
);
178 LoadGrfFile(used_set
->files
[GFT_LOGOS
].filename
, 4793, i
++);
181 * Load additional sprites for climates other than temperate.
182 * This overwrites some of the temperate sprites, such as foundations
183 * and the ground sprites.
185 if (_settings_game
.game_creation
.landscape
!= LT_TEMPERATE
) {
186 _palette_remap_grf
[i
] = (PAL_DOS
!= used_set
->palette
);
188 used_set
->files
[GFT_ARCTIC
+ _settings_game
.game_creation
.landscape
- 1].filename
,
189 _landscape_spriteindexes
[_settings_game
.game_creation
.landscape
- 1],
194 /* Initialize the unicode to sprite mapping table */
195 InitializeUnicodeGlyphMap();
198 * Load the base and extra NewGRF with OTTD required graphics as first NewGRF.
199 * However, we do not want it to show up in the list of used NewGRFs,
200 * so we have to manually add it, and then remove it later.
202 GRFConfig
*top
= _grfconfig
;
204 /* Default extra graphics */
205 GRFConfig
*master
= new GRFConfig("OPENTTD.GRF");
206 master
->palette
|= GRFP_GRF_DOS
;
207 FillGRFDetails(master
, false, BASESET_DIR
);
208 ClrBit(master
->flags
, GCF_INIT_ONLY
);
210 /* Baseset extra graphics */
211 GRFConfig
*extra
= new GRFConfig(used_set
->files
[GFT_EXTRA
].filename
);
213 /* We know the palette of the base set, so if the base NewGRF is not
214 * setting one, use the palette of the base set and not the global
215 * one which might be the wrong palette for this base NewGRF.
216 * The value set here might be overridden via action14 later. */
217 switch (used_set
->palette
) {
218 case PAL_DOS
: extra
->palette
|= GRFP_GRF_DOS
; break;
219 case PAL_WINDOWS
: extra
->palette
|= GRFP_GRF_WINDOWS
; break;
222 FillGRFDetails(extra
, false, BASESET_DIR
);
223 ClrBit(extra
->flags
, GCF_INIT_ONLY
);
226 master
->next
= extra
;
229 LoadNewGRF(SPR_NEWGRFS_BASE
, i
, 2);
231 uint total_extra_graphics
= SPR_NEWGRFS_BASE
- SPR_OPENTTD_BASE
;
232 _missing_extra_graphics
= GetSpriteCountForSlot(i
, SPR_OPENTTD_BASE
, SPR_NEWGRFS_BASE
);
233 DEBUG(sprite
, 1, "%u extra sprites, %u from baseset, %u from fallback", total_extra_graphics
, total_extra_graphics
- _missing_extra_graphics
, _missing_extra_graphics
);
235 /* The original baseset extra graphics intentionally make use of the fallback graphics.
236 * Let's say everything which provides less than 500 sprites misses the rest intentionally. */
237 if (500 + _missing_extra_graphics
> total_extra_graphics
) _missing_extra_graphics
= 0;
239 /* Free and remove the top element. */
247 * Check blitter needed by NewGRF config and switch if needed.
248 * @return False when nothing changed, true otherwise.
250 static bool SwitchNewGRFBlitter()
252 /* Never switch if the blitter was specified by the user. */
253 if (!_blitter_autodetected
) return false;
255 /* Null driver => dedicated server => do nothing. */
256 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return false;
258 /* Get preferred depth.
259 * - depth_wanted_by_base: Depth required by the baseset, i.e. the majority of the sprites.
260 * - depth_wanted_by_grf: Depth required by some NewGRF.
261 * Both can force using a 32bpp blitter. depth_wanted_by_base is used to select
262 * between multiple 32bpp blitters, which perform differently with 8bpp sprites.
264 uint depth_wanted_by_base
= BaseGraphics::GetUsedSet()->blitter
== BLT_32BPP
? 32 : 8;
265 uint depth_wanted_by_grf
= _support8bpp
== S8BPP_NONE
? 32 : 8;
266 for (GRFConfig
*c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
267 if (c
->status
== GCS_DISABLED
|| c
->status
== GCS_NOT_FOUND
|| HasBit(c
->flags
, GCF_INIT_ONLY
)) continue;
268 if (c
->palette
& GRFP_BLT_32BPP
) depth_wanted_by_grf
= 32;
271 /* Search the best blitter. */
272 static const struct {
274 uint animation
; ///< 0: no support, 1: do support, 2: both
275 uint min_base_depth
, max_base_depth
, min_grf_depth
, max_grf_depth
;
276 } replacement_blitters
[] = {
278 { "32bpp-sse4", 0, 32, 32, 8, 32 },
279 { "32bpp-ssse3", 0, 32, 32, 8, 32 },
280 { "32bpp-sse2", 0, 32, 32, 8, 32 },
281 { "32bpp-sse4-anim", 1, 32, 32, 8, 32 },
283 { "8bpp-optimized", 2, 8, 8, 8, 8 },
284 { "32bpp-optimized", 0, 8, 32, 8, 32 },
286 { "32bpp-sse2-anim", 1, 8, 32, 8, 32 },
288 { "32bpp-anim", 1, 8, 32, 8, 32 },
291 const bool animation_wanted
= HasBit(_display_opt
, DO_FULL_ANIMATION
);
292 const char *cur_blitter
= BlitterFactory::GetCurrentBlitter()->GetName();
294 VideoDriver::GetInstance()->AcquireBlitterLock();
296 for (uint i
= 0; i
< lengthof(replacement_blitters
); i
++) {
297 if (animation_wanted
&& (replacement_blitters
[i
].animation
== 0)) continue;
298 if (!animation_wanted
&& (replacement_blitters
[i
].animation
== 1)) continue;
300 if (!IsInsideMM(depth_wanted_by_base
, replacement_blitters
[i
].min_base_depth
, replacement_blitters
[i
].max_base_depth
+ 1)) continue;
301 if (!IsInsideMM(depth_wanted_by_grf
, replacement_blitters
[i
].min_grf_depth
, replacement_blitters
[i
].max_grf_depth
+ 1)) continue;
302 const char *repl_blitter
= replacement_blitters
[i
].name
;
304 if (strcmp(repl_blitter
, cur_blitter
) == 0) {
305 VideoDriver::GetInstance()->ReleaseBlitterLock();
308 if (BlitterFactory::GetBlitterFactory(repl_blitter
) == nullptr) continue;
310 DEBUG(misc
, 1, "Switching blitter from '%s' to '%s'... ", cur_blitter
, repl_blitter
);
311 Blitter
*new_blitter
= BlitterFactory::SelectBlitter(repl_blitter
);
312 if (new_blitter
== nullptr) NOT_REACHED();
313 DEBUG(misc
, 1, "Successfully switched to %s.", repl_blitter
);
317 if (!VideoDriver::GetInstance()->AfterBlitterChange()) {
318 /* Failed to switch blitter, let's hope we can return to the old one. */
319 if (BlitterFactory::SelectBlitter(cur_blitter
) == nullptr || !VideoDriver::GetInstance()->AfterBlitterChange()) usererror("Failed to reinitialize video driver. Specify a fixed blitter in the config");
322 VideoDriver::GetInstance()->ReleaseBlitterLock();
327 /** Check whether we still use the right blitter, or use another (better) one. */
330 if (!SwitchNewGRFBlitter()) return;
333 GfxClearSpriteCache();
337 /** Initialise and load all the sprites. */
338 void GfxLoadSprites()
340 DEBUG(sprite
, 2, "Loading sprite set %d", _settings_game
.game_creation
.landscape
);
342 SwitchNewGRFBlitter();
351 bool GraphicsSet::FillSetDetails(IniFile
*ini
, const char *path
, const char *full_filename
)
353 bool ret
= this->BaseSet
<GraphicsSet
, MAX_GFT
, true>::FillSetDetails(ini
, path
, full_filename
, false);
355 IniGroup
*metadata
= ini
->GetGroup("metadata");
358 fetch_metadata("palette");
359 this->palette
= (*item
->value
== 'D' || *item
->value
== 'd') ? PAL_DOS
: PAL_WINDOWS
;
361 /* Get optional blitter information. */
362 item
= metadata
->GetItem("blitter", false);
363 this->blitter
= (item
!= nullptr && *item
->value
== '3') ? BLT_32BPP
: BLT_8BPP
;
369 * Calculate and check the MD5 hash of the supplied GRF.
370 * @param file The file get the hash of.
371 * @param subdir The sub directory to get the files from.
373 * - #CR_MATCH if the MD5 hash matches
374 * - #CR_MISMATCH if the MD5 does not match
375 * - #CR_NO_FILE if the file misses
377 /* static */ MD5File::ChecksumResult
GraphicsSet::CheckMD5(const MD5File
*file
, Subdirectory subdir
)
380 FILE *f
= FioFOpenFile(file
->filename
, "rb", subdir
, &size
);
381 if (f
== nullptr) return MD5File::CR_NO_FILE
;
383 size_t max
= GRFGetSizeOfDataSection(f
);
387 return file
->CheckMD5(subdir
, max
);
392 * Calculate and check the MD5 hash of the supplied filename.
393 * @param subdir The sub directory to get the files from
394 * @param max_size Only calculate the hash for this many bytes from the file start.
396 * - #CR_MATCH if the MD5 hash matches
397 * - #CR_MISMATCH if the MD5 does not match
398 * - #CR_NO_FILE if the file misses
400 MD5File::ChecksumResult
MD5File::CheckMD5(Subdirectory subdir
, size_t max_size
) const
403 FILE *f
= FioFOpenFile(this->filename
, "rb", subdir
, &size
);
405 if (f
== nullptr) return CR_NO_FILE
;
407 size
= min(size
, max_size
);
414 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, f
)) != 0 && size
!= 0) {
416 checksum
.Append(buffer
, len
);
421 checksum
.Finish(digest
);
422 return memcmp(this->hash
, digest
, sizeof(this->hash
)) == 0 ? CR_MATCH
: CR_MISMATCH
;
425 /** Names corresponding to the GraphicsFileType */
426 static const char * const _graphics_file_names
[] = { "base", "logos", "arctic", "tropical", "toyland", "extra" };
428 /** Implementation */
429 template <class T
, size_t Tnum_files
, bool Tsearch_in_tars
>
430 /* static */ const char * const *BaseSet
<T
, Tnum_files
, Tsearch_in_tars
>::file_names
= _graphics_file_names
;
432 template <class Tbase_set
>
433 /* static */ bool BaseMedia
<Tbase_set
>::DetermineBestSet()
435 if (BaseMedia
<Tbase_set
>::used_set
!= nullptr) return true;
437 const Tbase_set
*best
= nullptr;
438 for (const Tbase_set
*c
= BaseMedia
<Tbase_set
>::available_sets
; c
!= nullptr; c
= c
->next
) {
439 /* Skip unusable sets */
440 if (c
->GetNumMissing() != 0) continue;
442 if (best
== nullptr ||
443 (best
->fallback
&& !c
->fallback
) ||
444 best
->valid_files
< c
->valid_files
||
445 (best
->valid_files
== c
->valid_files
&& (
446 (best
->shortname
== c
->shortname
&& best
->version
< c
->version
) ||
447 (best
->palette
!= PAL_DOS
&& c
->palette
== PAL_DOS
)))) {
452 BaseMedia
<Tbase_set
>::used_set
= best
;
453 return BaseMedia
<Tbase_set
>::used_set
!= nullptr;
456 template <class Tbase_set
>
457 /* static */ const char *BaseMedia
<Tbase_set
>::GetExtension()
459 return ".obg"; // OpenTTD Base Graphics
462 INSTANTIATE_BASE_MEDIA_METHODS(BaseMedia
<GraphicsSet
>, GraphicsSet
)