OpenTTD Source 20250524-master-gc366e6a48e
spritecache.cpp
Go to the documentation of this file.
1/*
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/>.
6 */
7
10#include "stdafx.h"
12#include "spriteloader/grf.hpp"
14#include "gfx_func.h"
15#include "error.h"
16#include "error_func.h"
17#include "strings_func.h"
18#include "zoom_func.h"
19#include "settings_type.h"
20#include "blitter/factory.hpp"
21#include "core/math_func.hpp"
23#include "spritecache.h"
25
26#include "table/sprites.h"
27#include "table/strings.h"
29
30#include "safeguards.h"
31
32/* Default of 4MB spritecache */
33uint _sprite_cache_size = 4;
34
35
36static std::vector<SpriteCache> _spritecache;
37static std::vector<std::unique_ptr<SpriteFile>> _sprite_files;
38
39static inline SpriteCache *GetSpriteCache(uint index)
40{
41 return &_spritecache[index];
42}
43
44SpriteCache *AllocateSpriteCache(uint index)
45{
46 if (index >= _spritecache.size()) {
47 /* Add another 1024 items to the 'pool' */
48 uint items = Align(index + 1, 1024);
49
50 Debug(sprite, 4, "Increasing sprite cache to {} items ({} bytes)", items, items * sizeof(SpriteCache));
51
52 _spritecache.resize(items);
53 }
54
55 return GetSpriteCache(index);
56}
57
63static SpriteFile *GetCachedSpriteFileByName(const std::string &filename)
64{
65 for (auto &f : _sprite_files) {
66 if (f->GetFilename() == filename) {
67 return f.get();
68 }
69 }
70 return nullptr;
71}
72
77std::span<const std::unique_ptr<SpriteFile>> GetCachedSpriteFiles()
78{
79 return _sprite_files;
80}
81
89SpriteFile &OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
90{
91 SpriteFile *file = GetCachedSpriteFileByName(filename);
92 if (file == nullptr) {
93 file = _sprite_files.insert(std::end(_sprite_files), std::make_unique<SpriteFile>(filename, subdir, palette_remap))->get();
94 } else {
95 file->SeekToBegin();
96 }
97 return *file;
98}
99
100struct MemBlock {
101 size_t size;
102 uint8_t data[];
103};
104
105static uint _sprite_lru_counter;
106static MemBlock *_spritecache_ptr;
107static uint _allocated_sprite_cache_size = 0;
108static int _compact_cache_counter;
109
110static void CompactSpriteCache();
111
118bool SkipSpriteData(SpriteFile &file, uint8_t type, uint16_t num)
119{
120 if (type & 2) {
121 file.SkipBytes(num);
122 } else {
123 while (num > 0) {
124 int8_t i = file.ReadByte();
125 if (i >= 0) {
126 int size = (i == 0) ? 0x80 : i;
127 if (size > num) return false;
128 num -= size;
129 file.SkipBytes(size);
130 } else {
131 i = -(i >> 3);
132 num -= i;
133 file.ReadByte();
134 }
135 }
136 }
137 return true;
138}
139
140/* Check if the given Sprite ID exists */
141bool SpriteExists(SpriteID id)
142{
143 if (id >= _spritecache.size()) return false;
144
145 /* Special case for Sprite ID zero -- its position is also 0... */
146 if (id == 0) return true;
147 return !(GetSpriteCache(id)->file_pos == 0 && GetSpriteCache(id)->file == nullptr);
148}
149
156{
157 if (!SpriteExists(sprite)) return SpriteType::Invalid;
158 return GetSpriteCache(sprite)->type;
159}
160
167{
168 if (!SpriteExists(sprite)) return nullptr;
169 return GetSpriteCache(sprite)->file;
170}
171
178{
179 if (!SpriteExists(sprite)) return 0;
180 return GetSpriteCache(sprite)->id;
181}
182
190uint GetSpriteCountForFile(const std::string &filename, SpriteID begin, SpriteID end)
191{
192 SpriteFile *file = GetCachedSpriteFileByName(filename);
193 if (file == nullptr) return 0;
194
195 uint count = 0;
196 for (SpriteID i = begin; i != end; i++) {
197 if (SpriteExists(i)) {
198 SpriteCache *sc = GetSpriteCache(i);
199 if (sc->file == file) {
200 count++;
201 Debug(sprite, 4, "Sprite: {}", i);
202 }
203 }
204 }
205 return count;
206}
207
217{
218 return static_cast<SpriteID>(_spritecache.size());
219}
220
221static bool ResizeSpriteIn(SpriteLoader::SpriteCollection &sprite, ZoomLevel src, ZoomLevel tgt)
222{
223 uint8_t scaled_1 = AdjustByZoom(1, src - tgt);
224 const auto &src_sprite = sprite[src];
225 auto &dest_sprite = sprite[tgt];
226
227 /* Check for possible memory overflow. */
228 if (src_sprite.width * scaled_1 > UINT16_MAX || src_sprite.height * scaled_1 > UINT16_MAX) return false;
229
230 dest_sprite.width = src_sprite.width * scaled_1;
231 dest_sprite.height = src_sprite.height * scaled_1;
232 dest_sprite.x_offs = src_sprite.x_offs * scaled_1;
233 dest_sprite.y_offs = src_sprite.y_offs * scaled_1;
234 dest_sprite.colours = src_sprite.colours;
235
236 dest_sprite.AllocateData(tgt, static_cast<size_t>(dest_sprite.width) * dest_sprite.height);
237
238 SpriteLoader::CommonPixel *dst = dest_sprite.data;
239 for (int y = 0; y < dest_sprite.height; y++) {
240 const SpriteLoader::CommonPixel *src_ln = &src_sprite.data[y / scaled_1 * src_sprite.width];
241 for (int x = 0; x < dest_sprite.width; x++) {
242 *dst = src_ln[x / scaled_1];
243 dst++;
244 }
245 }
246
247 return true;
248}
249
250static void ResizeSpriteOut(SpriteLoader::SpriteCollection &sprite, ZoomLevel zoom)
251{
252 const auto &root_sprite = sprite.Root();
253 const auto &src_sprite = sprite[zoom - 1];
254 auto &dest_sprite = sprite[zoom];
255
256 /* Algorithm based on 32bpp_Optimized::ResizeSprite() */
257 dest_sprite.width = UnScaleByZoom(root_sprite.width, zoom);
258 dest_sprite.height = UnScaleByZoom(root_sprite.height, zoom);
259 dest_sprite.x_offs = UnScaleByZoom(root_sprite.x_offs, zoom);
260 dest_sprite.y_offs = UnScaleByZoom(root_sprite.y_offs, zoom);
261 dest_sprite.colours = root_sprite.colours;
262
263 dest_sprite.AllocateData(zoom, static_cast<size_t>(dest_sprite.height) * dest_sprite.width);
264
265 SpriteLoader::CommonPixel *dst = dest_sprite.data;
266 const SpriteLoader::CommonPixel *src = src_sprite.data;
267 [[maybe_unused]] const SpriteLoader::CommonPixel *src_end = src + src_sprite.height * src_sprite.width;
268
269 for (uint y = 0; y < dest_sprite.height; y++) {
270 const SpriteLoader::CommonPixel *src_ln = src + src_sprite.width;
271 assert(src_ln <= src_end);
272 for (uint x = 0; x < dest_sprite.width; x++) {
273 assert(src < src_ln);
274 if (src + 1 != src_ln && (src + 1)->a != 0) {
275 *dst = *(src + 1);
276 } else {
277 *dst = *src;
278 }
279 dst++;
280 src += 2;
281 }
282 src = src_ln + src_sprite.width;
283 }
284}
285
286static bool PadSingleSprite(SpriteLoader::Sprite *sprite, ZoomLevel zoom, uint pad_left, uint pad_top, uint pad_right, uint pad_bottom)
287{
288 uint width = sprite->width + pad_left + pad_right;
289 uint height = sprite->height + pad_top + pad_bottom;
290
291 if (width > UINT16_MAX || height > UINT16_MAX) return false;
292
293 /* Copy source data and reallocate sprite memory. */
294 size_t sprite_size = static_cast<size_t>(sprite->width) * sprite->height;
295 std::vector<SpriteLoader::CommonPixel> src_data(sprite->data, sprite->data + sprite_size);
296 sprite->AllocateData(zoom, static_cast<size_t>(width) * height);
297
298 /* Copy with padding to destination. */
299 SpriteLoader::CommonPixel *src = src_data.data();
300 SpriteLoader::CommonPixel *data = sprite->data;
301 for (uint y = 0; y < height; y++) {
302 if (y < pad_top || pad_bottom + y >= height) {
303 /* Top/bottom padding. */
304 std::fill_n(data, width, SpriteLoader::CommonPixel{});
305 data += width;
306 } else {
307 if (pad_left > 0) {
308 /* Pad left. */
309 std::fill_n(data, pad_left, SpriteLoader::CommonPixel{});
310 data += pad_left;
311 }
312
313 /* Copy pixels. */
314 std::copy_n(src, sprite->width, data);
315 src += sprite->width;
316 data += sprite->width;
317
318 if (pad_right > 0) {
319 /* Pad right. */
320 std::fill_n(data, pad_right, SpriteLoader::CommonPixel{});
321 data += pad_right;
322 }
323 }
324 }
325
326 /* Update sprite size. */
327 sprite->width = width;
328 sprite->height = height;
329 sprite->x_offs -= pad_left;
330 sprite->y_offs -= pad_top;
331
332 return true;
333}
334
335static bool PadSprites(SpriteLoader::SpriteCollection &sprite, ZoomLevels sprite_avail, SpriteEncoder *encoder)
336{
337 /* Get minimum top left corner coordinates. */
338 int min_xoffs = INT32_MAX;
339 int min_yoffs = INT32_MAX;
340 for (ZoomLevel zoom = ZoomLevel::Begin; zoom != ZoomLevel::End; zoom++) {
341 if (sprite_avail.Test(zoom)) {
342 min_xoffs = std::min(min_xoffs, ScaleByZoom(sprite[zoom].x_offs, zoom));
343 min_yoffs = std::min(min_yoffs, ScaleByZoom(sprite[zoom].y_offs, zoom));
344 }
345 }
346
347 /* Get maximum dimensions taking necessary padding at the top left into account. */
348 int max_width = INT32_MIN;
349 int max_height = INT32_MIN;
350 for (ZoomLevel zoom = ZoomLevel::Begin; zoom != ZoomLevel::End; zoom++) {
351 if (sprite_avail.Test(zoom)) {
352 max_width = std::max(max_width, ScaleByZoom(sprite[zoom].width + sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom), zoom));
353 max_height = std::max(max_height, ScaleByZoom(sprite[zoom].height + sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom), zoom));
354 }
355 }
356
357 /* Align height and width if required to match the needs of the sprite encoder. */
358 uint align = encoder->GetSpriteAlignment();
359 if (align != 0) {
360 max_width = Align(max_width, align);
361 max_height = Align(max_height, align);
362 }
363
364 /* Pad sprites where needed. */
365 for (ZoomLevel zoom = ZoomLevel::Begin; zoom != ZoomLevel::End; zoom++) {
366 if (sprite_avail.Test(zoom)) {
367 auto &cur_sprite = sprite[zoom];
368 /* Scaling the sprite dimensions in the blitter is done with rounding up,
369 * so a negative padding here is not an error. */
370 int pad_left = std::max(0, cur_sprite.x_offs - UnScaleByZoom(min_xoffs, zoom));
371 int pad_top = std::max(0, cur_sprite.y_offs - UnScaleByZoom(min_yoffs, zoom));
372 int pad_right = std::max(0, UnScaleByZoom(max_width, zoom) - cur_sprite.width - pad_left);
373 int pad_bottom = std::max(0, UnScaleByZoom(max_height, zoom) - cur_sprite.height - pad_top);
374
375 if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) {
376 if (!PadSingleSprite(&cur_sprite, zoom, pad_left, pad_top, pad_right, pad_bottom)) return false;
377 }
378 }
379 }
380
381 return true;
382}
383
384static bool ResizeSprites(SpriteLoader::SpriteCollection &sprite, ZoomLevels sprite_avail, SpriteEncoder *encoder)
385{
386 /* Create a fully zoomed image if it does not exist */
387 ZoomLevel first_avail;
388 for (ZoomLevel zoom = ZoomLevel::Min; zoom <= ZoomLevel::Max; ++zoom) {
389 if (!sprite_avail.Test(zoom)) continue;
390 first_avail = zoom;
391 if (zoom != ZoomLevel::Min) {
392 if (!ResizeSpriteIn(sprite, zoom, ZoomLevel::Min)) return false;
393 sprite_avail.Set(ZoomLevel::Min);
394 }
395 break;
396 }
397
398 /* Pad sprites to make sizes match. */
399 if (!PadSprites(sprite, sprite_avail, encoder)) return false;
400
401 /* Create other missing zoom levels */
402 for (ZoomLevel zoom = ZoomLevel::Begin; zoom != ZoomLevel::End; zoom++) {
403 if (zoom == ZoomLevel::Min) continue;
404
405 if (sprite_avail.Test(zoom)) {
406 /* Check that size and offsets match the fully zoomed image. */
407 [[maybe_unused]] const auto &root_sprite = sprite[ZoomLevel::Min];
408 [[maybe_unused]] const auto &dest_sprite = sprite[zoom];
409 assert(dest_sprite.width == UnScaleByZoom(root_sprite.width, zoom));
410 assert(dest_sprite.height == UnScaleByZoom(root_sprite.height, zoom));
411 assert(dest_sprite.x_offs == UnScaleByZoom(root_sprite.x_offs, zoom));
412 assert(dest_sprite.y_offs == UnScaleByZoom(root_sprite.y_offs, zoom));
413 } else {
414 /* Zoom level is not available, or unusable, so create it */
415 ResizeSpriteOut(sprite, zoom);
416 }
417 }
418
419 /* Replace sprites with higher resolution than the desired maximum source resolution with scaled up sprites, if not already done. */
420 if (first_avail < _settings_client.gui.sprite_zoom_min) {
421 for (ZoomLevel zoom = std::min(ZoomLevel::Normal, _settings_client.gui.sprite_zoom_min); zoom > ZoomLevel::Min; --zoom) {
422 ResizeSpriteIn(sprite, zoom, zoom - 1);
423 }
424 }
425
426 return true;
427}
428
437static void *ReadRecolourSprite(SpriteFile &file, size_t file_pos, uint num, SpriteAllocator &allocator)
438{
439 /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
440 * number of recolour sprites that are 17 bytes that only exist in DOS
441 * GRFs which are the same as 257 byte recolour sprites, but with the last
442 * 240 bytes zeroed. */
443 static const uint RECOLOUR_SPRITE_SIZE = 257;
444 uint8_t *dest = allocator.Allocate<uint8_t>(std::max(RECOLOUR_SPRITE_SIZE, num));
445
446 file.SeekTo(file_pos, SEEK_SET);
447 if (file.NeedsPaletteRemap()) {
448 uint8_t *dest_tmp = new uint8_t[std::max(RECOLOUR_SPRITE_SIZE, num)];
449
450 /* Only a few recolour sprites are less than 257 bytes */
451 if (num < RECOLOUR_SPRITE_SIZE) std::fill_n(dest_tmp, RECOLOUR_SPRITE_SIZE, 0);
452 file.ReadBlock(dest_tmp, num);
453
454 /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
455 for (uint i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
456 dest[i] = _palmap_w2d[dest_tmp[_palmap_d2w[i - 1] + 1]];
457 }
458 delete[] dest_tmp;
459 } else {
460 file.ReadBlock(dest, num);
461 }
462
463 return dest;
464}
465
475static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, SpriteAllocator &allocator, SpriteEncoder *encoder)
476{
477 /* Use current blitter if no other sprite encoder is given. */
478 if (encoder == nullptr) encoder = BlitterFactory::GetCurrentBlitter();
479
480 SpriteFile &file = *sc->file;
481 size_t file_pos = sc->file_pos;
482
483 assert(sprite_type != SpriteType::Recolour);
484 assert(IsMapgenSpriteID(id) == (sprite_type == SpriteType::MapGen));
485 assert(sc->type == sprite_type);
486
487 Debug(sprite, 9, "Load sprite {}", id);
488
490 ZoomLevels sprite_avail;
491 ZoomLevels avail_8bpp;
492 ZoomLevels avail_32bpp;
493
494 SpriteLoaderGrf sprite_loader(file.GetContainerVersion());
495 if (sprite_type != SpriteType::MapGen && encoder->Is32BppSupported()) {
496 /* Try for 32bpp sprites first. */
497 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, true, sc->control_flags, avail_8bpp, avail_32bpp);
498 }
499 if (sprite_avail.None()) {
500 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, false, sc->control_flags, avail_8bpp, avail_32bpp);
501 if (sprite_type == SpriteType::Normal && avail_32bpp.Any() && !encoder->Is32BppSupported() && sprite_avail.None()) {
502 /* No 8bpp available, try converting from 32bpp. */
503 SpriteLoaderMakeIndexed make_indexed(sprite_loader);
504 sprite_avail = make_indexed.LoadSprite(sprite, file, file_pos, sprite_type, true, sc->control_flags, sprite_avail, avail_32bpp);
505 }
506 }
507
508 if (sprite_avail.None()) {
509 if (sprite_type == SpriteType::MapGen) return nullptr;
510 if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
511 return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder);
512 }
513
514 if (sprite_type == SpriteType::MapGen) {
515 /* Ugly hack to work around the problem that the old landscape
516 * generator assumes that those sprites are stored uncompressed in
517 * the memory, and they are only read directly by the code, never
518 * send to the blitter. So do not send it to the blitter (which will
519 * result in a data array in the format the blitter likes most), but
520 * extract the data directly and store that as sprite.
521 * Ugly: yes. Other solution: no. Blame the original author or
522 * something ;) The image should really have been a data-stream
523 * (so type = 0xFF basically). */
524 const auto &root_sprite = sprite.Root();
525 uint num = root_sprite.width * root_sprite.height;
526
527 Sprite *s = allocator.Allocate<Sprite>(sizeof(*s) + num);
528 s->width = root_sprite.width;
529 s->height = root_sprite.height;
530 s->x_offs = root_sprite.x_offs;
531 s->y_offs = root_sprite.y_offs;
532
533 SpriteLoader::CommonPixel *src = root_sprite.data;
534 uint8_t *dest = reinterpret_cast<uint8_t *>(s->data);
535 while (num-- > 0) {
536 *dest++ = src->m;
537 src++;
538 }
539
540 return s;
541 }
542
543 if (!ResizeSprites(sprite, sprite_avail, encoder)) {
544 if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't resize the fallback sprite. What should I do?");
545 return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder);
546 }
547
548 if (sprite_type == SpriteType::Font && _font_zoom != ZoomLevel::Min) {
549 /* Make ZoomLevel::Min be ZOOM_LVL_GUI */
550 sprite[ZoomLevel::Min] = sprite[_font_zoom];
551 }
552
553 return encoder->Encode(sprite_type, sprite, allocator);
554}
555
557 size_t file_pos;
558 uint8_t control_flags;
559};
560
562static std::map<uint32_t, GrfSpriteOffset> _grf_sprite_offsets;
563
569size_t GetGRFSpriteOffset(uint32_t id)
570{
571 return _grf_sprite_offsets.find(id) != _grf_sprite_offsets.end() ? _grf_sprite_offsets[id].file_pos : SIZE_MAX;
572}
573
579{
580 _grf_sprite_offsets.clear();
581
582 if (file.GetContainerVersion() >= 2) {
583 /* Seek to sprite section of the GRF. */
584 size_t data_offset = file.ReadDword();
585 size_t old_pos = file.GetPos();
586 file.SeekTo(data_offset, SEEK_CUR);
587
588 GrfSpriteOffset offset = { 0, 0 };
589
590 /* Loop over all sprite section entries and store the file
591 * offset for each newly encountered ID. */
592 SpriteID id, prev_id = 0;
593 while ((id = file.ReadDword()) != 0) {
594 if (id != prev_id) {
595 _grf_sprite_offsets[prev_id] = offset;
596 offset.file_pos = file.GetPos() - 4;
597 offset.control_flags = 0;
598 }
599 prev_id = id;
600 uint length = file.ReadDword();
601 if (length > 0) {
602 SpriteComponents colour{file.ReadByte()};
603 length--;
604 if (length > 0) {
605 uint8_t zoom = file.ReadByte();
606 length--;
607 if (colour != SpriteComponents{} && zoom == 0) { // ZoomLevel::Normal (normal zoom)
610 }
611 if (colour != SpriteComponents{} && zoom == 2) { // ZoomLevel::In2x (2x zoomed in)
613 }
614 }
615 }
616 file.SkipBytes(length);
617 }
618 if (prev_id != 0) _grf_sprite_offsets[prev_id] = offset;
619
620 /* Continue processing the data section. */
621 file.SeekTo(old_pos, SEEK_SET);
622 }
623}
624
625
634bool LoadNextSprite(SpriteID load_index, SpriteFile &file, uint file_sprite_id)
635{
636 size_t file_pos = file.GetPos();
637
638 /* Read sprite header. */
639 uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
640 if (num == 0) return false;
641 uint8_t grf_type = file.ReadByte();
642
643 SpriteType type;
644 void *data = nullptr;
645 uint8_t control_flags = 0;
646 if (grf_type == 0xFF) {
647 /* Some NewGRF files have "empty" pseudo-sprites which are 1
648 * byte long. Catch these so the sprites won't be displayed. */
649 if (num == 1) {
650 file.ReadByte();
651 return false;
652 }
653 file_pos = file.GetPos();
655 file.SkipBytes(num);
656 } else if (file.GetContainerVersion() >= 2 && grf_type == 0xFD) {
657 if (num != 4) {
658 /* Invalid sprite section include, ignore. */
659 file.SkipBytes(num);
660 return false;
661 }
662 /* It is not an error if no sprite with the provided ID is found in the sprite section. */
663 auto iter = _grf_sprite_offsets.find(file.ReadDword());
664 if (iter != _grf_sprite_offsets.end()) {
665 file_pos = iter->second.file_pos;
666 control_flags = iter->second.control_flags;
667 } else {
668 file_pos = SIZE_MAX;
669 }
670 type = SpriteType::Normal;
671 } else {
672 file.SkipBytes(7);
673 type = SkipSpriteData(file, grf_type, num - 8) ? SpriteType::Normal : SpriteType::Invalid;
674 /* Inline sprites are not supported for container version >= 2. */
675 if (file.GetContainerVersion() >= 2) return false;
676 }
677
678 if (type == SpriteType::Invalid) return false;
679
680 if (load_index >= MAX_SPRITES) {
681 UserError("Tried to load too many sprites (#{}; max {})", load_index, MAX_SPRITES);
682 }
683
684 bool is_mapgen = IsMapgenSpriteID(load_index);
685
686 if (is_mapgen) {
687 if (type != SpriteType::Normal) UserError("Uhm, would you be so kind not to load a NewGRF that changes the type of the map generator sprites?");
688 type = SpriteType::MapGen;
689 }
690
691 SpriteCache *sc = AllocateSpriteCache(load_index);
692 sc->file = &file;
693 sc->file_pos = file_pos;
694 sc->length = num;
695 sc->ptr = data;
696 sc->lru = 0;
697 sc->id = file_sprite_id;
698 sc->type = type;
699 sc->warned = false;
700 sc->control_flags = control_flags;
701
702 return true;
703}
704
705
706void DupSprite(SpriteID old_spr, SpriteID new_spr)
707{
708 SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
709 SpriteCache *scold = GetSpriteCache(old_spr);
710
711 scnew->file = scold->file;
712 scnew->file_pos = scold->file_pos;
713 scnew->ptr = nullptr;
714 scnew->id = scold->id;
715 scnew->type = scold->type;
716 scnew->warned = false;
717 scnew->control_flags = scold->control_flags;
718}
719
726static const size_t S_FREE_MASK = sizeof(size_t) - 1;
727
728/* to make sure nobody adds things to MemBlock without checking S_FREE_MASK first */
729static_assert(sizeof(MemBlock) == sizeof(size_t));
730/* make sure it's a power of two */
731static_assert((sizeof(size_t) & (sizeof(size_t) - 1)) == 0);
732
733static inline MemBlock *NextBlock(MemBlock *block)
734{
735 return (MemBlock*)((uint8_t*)block + (block->size & ~S_FREE_MASK));
736}
737
738static size_t GetSpriteCacheUsage()
739{
740 size_t tot_size = 0;
741 MemBlock *s;
742
743 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
744 if (!(s->size & S_FREE_MASK)) tot_size += s->size;
745 }
746
747 return tot_size;
748}
749
750
751void IncreaseSpriteLRU()
752{
753 /* Increase all LRU values */
754 if (_sprite_lru_counter > 16384) {
755 Debug(sprite, 5, "Fixing lru {}, inuse={}", _sprite_lru_counter, GetSpriteCacheUsage());
756
757 for (SpriteCache &sc : _spritecache) {
758 if (sc.ptr != nullptr) {
759 if (sc.lru >= 0) {
760 sc.lru = -1;
761 } else if (sc.lru != -32768) {
762 sc.lru--;
763 }
764 }
765 }
766 _sprite_lru_counter = 0;
767 }
768
769 /* Compact sprite cache every now and then. */
770 if (++_compact_cache_counter >= 740) {
772 _compact_cache_counter = 0;
773 }
774}
775
781{
782 MemBlock *s;
783
784 Debug(sprite, 3, "Compacting sprite cache, inuse={}", GetSpriteCacheUsage());
785
786 for (s = _spritecache_ptr; s->size != 0;) {
787 if (s->size & S_FREE_MASK) {
788 MemBlock *next = NextBlock(s);
789 MemBlock temp;
790 SpriteID i;
791
792 /* Since free blocks are automatically coalesced, this should hold true. */
793 assert(!(next->size & S_FREE_MASK));
794
795 /* If the next block is the sentinel block, we can safely return */
796 if (next->size == 0) break;
797
798 /* Locate the sprite belonging to the next pointer. */
799 for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
800 assert(i != _spritecache.size());
801 }
802
803 GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
804 /* Swap this and the next block */
805 temp = *s;
806 std::byte *p = reinterpret_cast<std::byte *>(next);
807 std::move(p, &p[next->size], reinterpret_cast<std::byte *>(s));
808 s = NextBlock(s);
809 *s = temp;
810
811 /* Coalesce free blocks */
812 while (NextBlock(s)->size & S_FREE_MASK) {
813 s->size += NextBlock(s)->size & ~S_FREE_MASK;
814 }
815 } else {
816 s = NextBlock(s);
817 }
818 }
819}
820
826{
827 /* Mark the block as free (the block must be in use) */
828 MemBlock *s = static_cast<MemBlock *>(item->ptr) - 1;
829 assert(!(s->size & S_FREE_MASK));
830 s->size |= S_FREE_MASK;
831 item->ptr = nullptr;
832
833 /* And coalesce adjacent free blocks */
834 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
835 if (s->size & S_FREE_MASK) {
836 while (NextBlock(s)->size & S_FREE_MASK) {
837 s->size += NextBlock(s)->size & ~S_FREE_MASK;
838 }
839 }
840 }
841}
842
843static void DeleteEntryFromSpriteCache()
844{
845 Debug(sprite, 3, "DeleteEntryFromSpriteCache, inuse={}", GetSpriteCacheUsage());
846
847 SpriteCache *best = nullptr;
848 int cur_lru = 0xffff;
849 for (SpriteCache &sc : _spritecache) {
850 if (sc.ptr != nullptr && sc.lru < cur_lru) {
851 cur_lru = sc.lru;
852 best = &sc;
853 }
854 }
855
856 /* Display an error message and die, in case we found no sprite at all.
857 * This shouldn't really happen, unless all sprites are locked. */
858 if (best == nullptr) FatalError("Out of sprite memory");
859
861}
862
864{
865 mem_req += sizeof(MemBlock);
866
867 /* Align this to correct boundary. This also makes sure at least one
868 * bit is not used, so we can use it for other things. */
869 mem_req = Align(mem_req, S_FREE_MASK + 1);
870
871 for (;;) {
872 MemBlock *s;
873
874 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
875 if (s->size & S_FREE_MASK) {
876 size_t cur_size = s->size & ~S_FREE_MASK;
877
878 /* Is the block exactly the size we need or
879 * big enough for an additional free block? */
880 if (cur_size == mem_req ||
881 cur_size >= mem_req + sizeof(MemBlock)) {
882 /* Set size and in use */
883 s->size = mem_req;
884
885 /* Do we need to inject a free block too? */
886 if (cur_size != mem_req) {
887 NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
888 }
889
890 return s->data;
891 }
892 }
893 }
894
895 /* Reached sentinel, but no block found yet. Delete some old entry. */
897 }
898}
899
901{
902 this->data = std::make_unique<std::byte[]>(size);
903 return this->data.get();
904}
905
915static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, SpriteAllocator *allocator)
916{
917 static const std::string_view sprite_types[] = {
918 "normal", // SpriteType::Normal
919 "map generator", // SpriteType::MapGen
920 "character", // SpriteType::Font
921 "recolour", // SpriteType::Recolour
922 };
923
924 SpriteType available = sc->type;
925 if (requested == SpriteType::Font && available == SpriteType::Normal) {
926 if (sc->ptr == nullptr) sc->type = SpriteType::Font;
927 return GetRawSprite(sprite, sc->type, allocator);
928 }
929
930 uint8_t warning_level = sc->warned ? 6 : 0;
931 sc->warned = true;
932 Debug(sprite, warning_level, "Tried to load {} sprite #{} as a {} sprite. Probable cause: NewGRF interference", sprite_types[static_cast<uint8_t>(available)], sprite, sprite_types[static_cast<uint8_t>(requested)]);
933
934 switch (requested) {
936 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?");
937 [[fallthrough]];
938 case SpriteType::Font:
939 return GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, allocator);
941 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?");
942 return GetRawSprite(PALETTE_TO_DARK_BLUE, SpriteType::Recolour, allocator);
944 /* this shouldn't happen, overriding of SpriteType::MapGen sprites is checked in LoadNextSprite()
945 * (the only case the check fails is when these sprites weren't even loaded...) */
946 default:
947 NOT_REACHED();
948 }
949}
950
960void *GetRawSprite(SpriteID sprite, SpriteType type, SpriteAllocator *allocator, SpriteEncoder *encoder)
961{
962 assert(type != SpriteType::MapGen || IsMapgenSpriteID(sprite));
963 assert(type < SpriteType::Invalid);
964
965 if (!SpriteExists(sprite)) {
966 Debug(sprite, 1, "Tried to load non-existing sprite #{}. Probable cause: Wrong/missing NewGRFs", sprite);
967
968 /* SPR_IMG_QUERY is a BIG FAT RED ? */
969 sprite = SPR_IMG_QUERY;
970 }
971
972 SpriteCache *sc = GetSpriteCache(sprite);
973
974 if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc, allocator);
975
976 if (allocator == nullptr && encoder == nullptr) {
977 /* Load sprite into/from spritecache */
978 CacheSpriteAllocator cache_allocator;
979
980 /* Update LRU */
981 sc->lru = ++_sprite_lru_counter;
982
983 /* Load the sprite, if it is not loaded, yet */
984 if (sc->ptr == nullptr) {
985 if (sc->type == SpriteType::Recolour) {
986 sc->ptr = ReadRecolourSprite(*sc->file, sc->file_pos, sc->length, cache_allocator);
987 } else {
988 sc->ptr = ReadSprite(sc, sprite, type, cache_allocator, nullptr);
989 }
990 }
991
992 return sc->ptr;
993 } else {
994 /* Do not use the spritecache, but a different allocator. */
995 return ReadSprite(sc, sprite, type, *allocator, encoder);
996 }
997}
998
999
1000static void GfxInitSpriteCache()
1001{
1002 /* initialize sprite cache heap */
1004 uint target_size = (bpp > 0 ? _sprite_cache_size * bpp / 8 : 1) * 1024 * 1024;
1005
1006 /* Remember 'target_size' from the previous allocation attempt, so we do not try to reach the target_size multiple times in case of failure. */
1007 static uint last_alloc_attempt = 0;
1008
1009 if (_spritecache_ptr == nullptr || (_allocated_sprite_cache_size != target_size && target_size != last_alloc_attempt)) {
1010 delete[] reinterpret_cast<uint8_t *>(_spritecache_ptr);
1011
1012 last_alloc_attempt = target_size;
1013 _allocated_sprite_cache_size = target_size;
1014
1015 do {
1016 /* Try to allocate 50% more to make sure we do not allocate almost all available. */
1017 _spritecache_ptr = reinterpret_cast<MemBlock *>(new(std::nothrow) uint8_t[_allocated_sprite_cache_size + _allocated_sprite_cache_size / 2]);
1018
1019 if (_spritecache_ptr != nullptr) {
1020 /* Allocation succeeded, but we wanted less. */
1021 delete[] reinterpret_cast<uint8_t *>(_spritecache_ptr);
1022 _spritecache_ptr = reinterpret_cast<MemBlock *>(new uint8_t[_allocated_sprite_cache_size]);
1023 } else if (_allocated_sprite_cache_size < 2 * 1024 * 1024) {
1024 UserError("Cannot allocate spritecache");
1025 } else {
1026 /* Try again to allocate half. */
1027 _allocated_sprite_cache_size >>= 1;
1028 }
1029 } while (_spritecache_ptr == nullptr);
1030
1031 if (_allocated_sprite_cache_size != target_size) {
1032 Debug(misc, 0, "Not enough memory to allocate {} MiB of spritecache. Spritecache was reduced to {} MiB.", target_size / 1024 / 1024, _allocated_sprite_cache_size / 1024 / 1024);
1033
1034 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR_OUT_OF_MEMORY), GetEncodedString(STR_CONFIG_ERROR_SPRITECACHE_TOO_BIG, target_size, _allocated_sprite_cache_size));
1036 }
1037 }
1038
1039 /* A big free block */
1040 _spritecache_ptr->size = (_allocated_sprite_cache_size - sizeof(MemBlock)) | S_FREE_MASK;
1041 /* Sentinel block (identified by size == 0) */
1042 NextBlock(_spritecache_ptr)->size = 0;
1043}
1044
1045void GfxInitSpriteMem()
1046{
1047 GfxInitSpriteCache();
1048
1049 /* Reset the spritecache 'pool' */
1050 _spritecache.clear();
1051 _spritecache.shrink_to_fit();
1052
1053 _compact_cache_counter = 0;
1054 _sprite_files.clear();
1055}
1056
1062{
1063 /* Clear sprite ptr for all cached items */
1064 for (SpriteCache &sc : _spritecache) {
1065 if (sc.ptr != nullptr) DeleteEntryFromSpriteCache(&sc);
1066 }
1067
1069}
1070
1076{
1077 /* Clear sprite ptr for all cached font items */
1078 for (SpriteCache &sc : _spritecache) {
1079 if (sc.type == SpriteType::Font && sc.ptr != nullptr) DeleteEntryFromSpriteCache(&sc);
1080 }
1081}
1082
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:136
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
SpriteAllocator that allocates memory from the sprite cache.
void * AllocatePtr(size_t size) override
Allocate memory for a sprite.
Enum-as-bit-set wrapper.
The data of the error message.
Definition error.h:31
void ReadBlock(void *ptr, size_t size)
Read a block.
size_t GetPos() const
Get position in the file.
void SeekTo(size_t pos, int mode)
Seek in the current file.
uint8_t ReadByte()
Read a byte from the file.
uint32_t ReadDword()
Read a double word (32 bits) from the file (in low endian format).
void SkipBytes(size_t n)
Skip n bytes ahead in the file.
uint16_t ReadWord()
Read a word (16 bits) from the file (in low endian format).
Interface for something that can allocate memory for a sprite.
T * Allocate(size_t size)
Allocate memory for a sprite.
Map zoom level to data.
Interface for something that can encode a sprite.
virtual bool Is32BppSupported()=0
Can the sprite encoder make use of RGBA sprites?
virtual uint GetSpriteAlignment()
Get the value which the height and width on a sprite have to be aligned by.
virtual Sprite * Encode(SpriteType sprite_type, const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator)=0
Convert a sprite from the loader to our own format.
RandomAccessFile with some extra information specific for sprite files.
bool NeedsPaletteRemap() const
Whether a palette remap is needed when loading sprites from this file.
uint8_t GetContainerVersion() const
Get the version number of container type used by the file.
void SeekToBegin()
Seek to the begin of the content, i.e.
Sprite loader for graphics coming from a (New)GRF.
Definition grf.hpp:16
ZoomLevels LoadSprite(SpriteLoader::SpriteCollection &sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, bool load_32bpp, uint8_t control_flags, ZoomLevels &avail_8bpp, ZoomLevels &avail_32bpp) override
Load a sprite from the disk and return a sprite struct which is the same for all loaders.
Definition grf.cpp:362
Sprite loader for converting graphics coming from another source.
Definition makeindexed.h:16
ZoomLevels LoadSprite(SpriteLoader::SpriteCollection &sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, bool load_32bpp, uint8_t control_flags, ZoomLevels &avail_8bpp, ZoomLevels &avail_32bpp) override
Load a sprite from the disk and return a sprite struct which is the same for all loaders.
void * AllocatePtr(size_t size) override
Allocate memory for a sprite.
virtual void ClearSystemSprites()
Clear all cached sprites.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
Functions related to errors.
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
Error reporting related functions.
Factory to 'query' all available blitters.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:87
ZoomLevel _font_zoom
Sprite font Zoom level (not clamped)
Definition gfx.cpp:62
Functions related to the gfx engine.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
SpriteType
Types of sprites that might be loaded.
Definition gfx_type.h:352
@ Recolour
Recolour sprite.
@ Font
A sprite used for fonts.
@ MapGen
Special sprite for the map generator.
@ Invalid
Pseudosprite or other unusable sprite, used only internally.
@ Normal
The most basic (normal) sprite.
Base for reading sprites from (New)GRFs.
Base for converting sprites from another source from 32bpp RGBA to indexed 8bpp.
Integer math functions.
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
Translation tables from one GRF to another GRF.
static const uint8_t _palmap_d2w[]
Converting from the DOS palette to the Windows palette.
Class related to random access to files.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:59
Types related to global configuration settings.
static std::map< uint32_t, GrfSpriteOffset > _grf_sprite_offsets
Map from sprite numbers to position in the GRF file.
SpriteType GetSpriteType(SpriteID sprite)
Get the sprite type of a given sprite.
void GfxClearSpriteCache()
Remove all encoded sprites from the sprite cache without discarding sprite location information.
static SpriteFile * GetCachedSpriteFileByName(const std::string &filename)
Get the cached SpriteFile given the name of the file.
uint GetSpriteCountForFile(const std::string &filename, SpriteID begin, SpriteID end)
Count the sprites which originate from a specific file in a range of SpriteIDs.
static void DeleteEntryFromSpriteCache(SpriteCache *item)
Delete a single entry from the sprite cache.
static void * ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, SpriteAllocator &allocator, SpriteEncoder *encoder)
Read a sprite from disk.
void GfxClearFontSpriteCache()
Remove all encoded font sprites from the sprite cache without discarding sprite location information.
SpriteID GetMaxSpriteID()
Get a reasonable (upper bound) estimate of the maximum SpriteID used in OpenTTD; there will be no spr...
SpriteFile & OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
Open/get the SpriteFile that is cached for use in the sprite cache.
static void * HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, SpriteAllocator *allocator)
Handles the case when a sprite of different type is requested than is present in the SpriteCache.
void * GetRawSprite(SpriteID sprite, SpriteType type, SpriteAllocator *allocator, SpriteEncoder *encoder)
Reads a sprite (from disk or sprite cache).
std::span< const std::unique_ptr< SpriteFile > > GetCachedSpriteFiles()
Get the list of cached SpriteFiles.
bool LoadNextSprite(SpriteID load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
SpriteFile * GetOriginFile(SpriteID sprite)
Get the SpriteFile of a given sprite.
size_t GetGRFSpriteOffset(uint32_t id)
Get the file offset for a specific sprite in the sprite section of a GRF.
static void * ReadRecolourSprite(SpriteFile &file, size_t file_pos, uint num, SpriteAllocator &allocator)
Load a recolour sprite into memory.
bool SkipSpriteData(SpriteFile &file, uint8_t type, uint16_t num)
Skip the given amount of sprite graphics data.
uint32_t GetSpriteLocalID(SpriteID sprite)
Get the GRF-local sprite id of a given sprite.
static void CompactSpriteCache()
Called when holes in the sprite cache should be removed.
static const size_t S_FREE_MASK
S_FREE_MASK is used to mask-out lower bits of MemBlock::size If they are non-zero,...
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Functions to cache sprites in memory.
@ SCCF_ALLOW_ZOOM_MIN_2X_32BPP
Allow use of sprite min zoom setting at 2x in 32bpp mode.
Definition spritecache.h:29
@ SCCF_ALLOW_ZOOM_MIN_1X_32BPP
Allow use of sprite min zoom setting at 1x in 32bpp mode.
Definition spritecache.h:27
@ SCCF_ALLOW_ZOOM_MIN_1X_PAL
Allow use of sprite min zoom setting at 1x in palette mode.
Definition spritecache.h:26
@ SCCF_ALLOW_ZOOM_MIN_2X_PAL
Allow use of sprite min zoom setting at 2x in palette mode.
Definition spritecache.h:28
Internal functions to cache sprites in memory.
@ Palette
Sprite has palette data.
This file contains all sprite-related enums and defines.
static constexpr uint32_t MAX_SPRITES
Masks needed for sprite operations.
Definition sprites.h:1559
Definition of base types and functions in a cross-platform compatible way.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:91
Functions related to OTTD's strings.
GUISettings gui
settings related to the GUI
ZoomLevel sprite_zoom_min
maximum zoom level at which higher-resolution alternative sprites will be used (if available) instead...
uint8_t control_flags
Control flags, see SpriteCacheCtrlFlags.
uint32_t length
Length of sprite data.
bool warned
True iff the user has been warned about incorrect use of this sprite.
SpriteType type
In some cases a single sprite is misused by two NewGRFs. Once as real sprite and once as recolour spr...
SpriteFile * file
The file the sprite in this entry can be found in.
Definition of a common pixel in OpenTTD's realm.
uint8_t m
Remap-channel.
Structure for passing information from the sprite loader to the blitter.
static SpriteCollMap< ReusableBuffer< SpriteLoader::CommonPixel > > buffer
Allocated memory to pass sprite data around.
void AllocateData(ZoomLevel zoom, size_t size)
Allocate the sprite data of this sprite.
uint16_t width
Width of the sprite.
int16_t x_offs
The x-offset of where the sprite will be drawn.
SpriteLoader::CommonPixel * data
The sprite itself.
uint16_t height
Height of the sprite.
int16_t y_offs
The y-offset of where the sprite will be drawn.
Data structure describing a sprite.
Definition spritecache.h:17
uint16_t width
Width of the sprite.
Definition spritecache.h:19
uint16_t height
Height of the sprite.
Definition spritecache.h:18
int16_t y_offs
Number of pixels to shift the sprite downwards.
Definition spritecache.h:21
std::byte data[]
Sprite data.
Definition spritecache.h:22
int16_t x_offs
Number of pixels to shift the sprite to the right.
Definition spritecache.h:20
Base of all video drivers.
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22
int AdjustByZoom(int value, int zoom)
Adjust by zoom level; zoom < 0 shifts right, zoom >= 0 shifts left.
Definition zoom_func.h:45
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:34
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:16
@ Begin
Begin for iteration.
@ Max
Maximum zoom level.
@ Min
Minimum zoom level.
@ End
End for iteration.
@ Normal
The normal zoom level.