OpenTTD Source 20250312-master-gcdcc6b491d
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"
22#include "core/mem_func.hpp"
24#include "spritecache.h"
26
27#include "table/sprites.h"
28#include "table/strings.h"
30
31#include "safeguards.h"
32
33/* Default of 4MB spritecache */
34uint _sprite_cache_size = 4;
35
36
37static std::vector<SpriteCache> _spritecache;
38static std::vector<std::unique_ptr<SpriteFile>> _sprite_files;
39
40static inline SpriteCache *GetSpriteCache(uint index)
41{
42 return &_spritecache[index];
43}
44
45SpriteCache *AllocateSpriteCache(uint index)
46{
47 if (index >= _spritecache.size()) {
48 /* Add another 1024 items to the 'pool' */
49 uint items = Align(index + 1, 1024);
50
51 Debug(sprite, 4, "Increasing sprite cache to {} items ({} bytes)", items, items * sizeof(SpriteCache));
52
53 _spritecache.resize(items);
54 }
55
56 return GetSpriteCache(index);
57}
58
64static SpriteFile *GetCachedSpriteFileByName(const std::string &filename)
65{
66 for (auto &f : _sprite_files) {
67 if (f->GetFilename() == filename) {
68 return f.get();
69 }
70 }
71 return nullptr;
72}
73
78std::span<const std::unique_ptr<SpriteFile>> GetCachedSpriteFiles()
79{
80 return _sprite_files;
81}
82
90SpriteFile &OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
91{
92 SpriteFile *file = GetCachedSpriteFileByName(filename);
93 if (file == nullptr) {
94 file = _sprite_files.insert(std::end(_sprite_files), std::make_unique<SpriteFile>(filename, subdir, palette_remap))->get();
95 } else {
96 file->SeekToBegin();
97 }
98 return *file;
99}
100
101struct MemBlock {
102 size_t size;
103 uint8_t data[];
104};
105
106static uint _sprite_lru_counter;
107static MemBlock *_spritecache_ptr;
108static uint _allocated_sprite_cache_size = 0;
109static int _compact_cache_counter;
110
111static void CompactSpriteCache();
112
119bool SkipSpriteData(SpriteFile &file, uint8_t type, uint16_t num)
120{
121 if (type & 2) {
122 file.SkipBytes(num);
123 } else {
124 while (num > 0) {
125 int8_t i = file.ReadByte();
126 if (i >= 0) {
127 int size = (i == 0) ? 0x80 : i;
128 if (size > num) return false;
129 num -= size;
130 file.SkipBytes(size);
131 } else {
132 i = -(i >> 3);
133 num -= i;
134 file.ReadByte();
135 }
136 }
137 }
138 return true;
139}
140
141/* Check if the given Sprite ID exists */
142bool SpriteExists(SpriteID id)
143{
144 if (id >= _spritecache.size()) return false;
145
146 /* Special case for Sprite ID zero -- its position is also 0... */
147 if (id == 0) return true;
148 return !(GetSpriteCache(id)->file_pos == 0 && GetSpriteCache(id)->file == nullptr);
149}
150
157{
158 if (!SpriteExists(sprite)) return SpriteType::Invalid;
159 return GetSpriteCache(sprite)->type;
160}
161
168{
169 if (!SpriteExists(sprite)) return nullptr;
170 return GetSpriteCache(sprite)->file;
171}
172
179{
180 if (!SpriteExists(sprite)) return 0;
181 return GetSpriteCache(sprite)->id;
182}
183
191uint GetSpriteCountForFile(const std::string &filename, SpriteID begin, SpriteID end)
192{
193 SpriteFile *file = GetCachedSpriteFileByName(filename);
194 if (file == nullptr) return 0;
195
196 uint count = 0;
197 for (SpriteID i = begin; i != end; i++) {
198 if (SpriteExists(i)) {
199 SpriteCache *sc = GetSpriteCache(i);
200 if (sc->file == file) {
201 count++;
202 Debug(sprite, 4, "Sprite: {}", i);
203 }
204 }
205 }
206 return count;
207}
208
218{
219 return static_cast<SpriteID>(_spritecache.size());
220}
221
222static bool ResizeSpriteIn(SpriteLoader::SpriteCollection &sprite, ZoomLevel src, ZoomLevel tgt)
223{
224 uint8_t scaled_1 = ScaleByZoom(1, (ZoomLevel)(src - tgt));
225
226 /* Check for possible memory overflow. */
227 if (sprite[src].width * scaled_1 > UINT16_MAX || sprite[src].height * scaled_1 > UINT16_MAX) return false;
228
229 sprite[tgt].width = sprite[src].width * scaled_1;
230 sprite[tgt].height = sprite[src].height * scaled_1;
231 sprite[tgt].x_offs = sprite[src].x_offs * scaled_1;
232 sprite[tgt].y_offs = sprite[src].y_offs * scaled_1;
233 sprite[tgt].colours = sprite[src].colours;
234
235 sprite[tgt].AllocateData(tgt, static_cast<size_t>(sprite[tgt].width) * sprite[tgt].height);
236
237 SpriteLoader::CommonPixel *dst = sprite[tgt].data;
238 for (int y = 0; y < sprite[tgt].height; y++) {
239 const SpriteLoader::CommonPixel *src_ln = &sprite[src].data[y / scaled_1 * sprite[src].width];
240 for (int x = 0; x < sprite[tgt].width; x++) {
241 *dst = src_ln[x / scaled_1];
242 dst++;
243 }
244 }
245
246 return true;
247}
248
249static void ResizeSpriteOut(SpriteLoader::SpriteCollection &sprite, ZoomLevel zoom)
250{
251 /* Algorithm based on 32bpp_Optimized::ResizeSprite() */
252 sprite[zoom].width = UnScaleByZoom(sprite[ZOOM_LVL_MIN].width, zoom);
253 sprite[zoom].height = UnScaleByZoom(sprite[ZOOM_LVL_MIN].height, zoom);
254 sprite[zoom].x_offs = UnScaleByZoom(sprite[ZOOM_LVL_MIN].x_offs, zoom);
255 sprite[zoom].y_offs = UnScaleByZoom(sprite[ZOOM_LVL_MIN].y_offs, zoom);
256 sprite[zoom].colours = sprite[ZOOM_LVL_MIN].colours;
257
258 sprite[zoom].AllocateData(zoom, static_cast<size_t>(sprite[zoom].height) * sprite[zoom].width);
259
260 SpriteLoader::CommonPixel *dst = sprite[zoom].data;
261 const SpriteLoader::CommonPixel *src = sprite[zoom - 1].data;
262 [[maybe_unused]] const SpriteLoader::CommonPixel *src_end = src + sprite[zoom - 1].height * sprite[zoom - 1].width;
263
264 for (uint y = 0; y < sprite[zoom].height; y++) {
265 const SpriteLoader::CommonPixel *src_ln = src + sprite[zoom - 1].width;
266 assert(src_ln <= src_end);
267 for (uint x = 0; x < sprite[zoom].width; x++) {
268 assert(src < src_ln);
269 if (src + 1 != src_ln && (src + 1)->a != 0) {
270 *dst = *(src + 1);
271 } else {
272 *dst = *src;
273 }
274 dst++;
275 src += 2;
276 }
277 src = src_ln + sprite[zoom - 1].width;
278 }
279}
280
281static bool PadSingleSprite(SpriteLoader::Sprite *sprite, ZoomLevel zoom, uint pad_left, uint pad_top, uint pad_right, uint pad_bottom)
282{
283 uint width = sprite->width + pad_left + pad_right;
284 uint height = sprite->height + pad_top + pad_bottom;
285
286 if (width > UINT16_MAX || height > UINT16_MAX) return false;
287
288 /* Copy source data and reallocate sprite memory. */
289 size_t sprite_size = static_cast<size_t>(sprite->width) * sprite->height;
290 std::vector<SpriteLoader::CommonPixel> src_data(sprite->data, sprite->data + sprite_size);
291 sprite->AllocateData(zoom, static_cast<size_t>(width) * height);
292
293 /* Copy with padding to destination. */
294 SpriteLoader::CommonPixel *src = src_data.data();
295 SpriteLoader::CommonPixel *data = sprite->data;
296 for (uint y = 0; y < height; y++) {
297 if (y < pad_top || pad_bottom + y >= height) {
298 /* Top/bottom padding. */
299 std::fill_n(data, width, SpriteLoader::CommonPixel{});
300 data += width;
301 } else {
302 if (pad_left > 0) {
303 /* Pad left. */
304 std::fill_n(data, pad_left, SpriteLoader::CommonPixel{});
305 data += pad_left;
306 }
307
308 /* Copy pixels. */
309 std::copy_n(src, sprite->width, data);
310 src += sprite->width;
311 data += sprite->width;
312
313 if (pad_right > 0) {
314 /* Pad right. */
315 std::fill_n(data, pad_right, SpriteLoader::CommonPixel{});
316 data += pad_right;
317 }
318 }
319 }
320
321 /* Update sprite size. */
322 sprite->width = width;
323 sprite->height = height;
324 sprite->x_offs -= pad_left;
325 sprite->y_offs -= pad_top;
326
327 return true;
328}
329
330static bool PadSprites(SpriteLoader::SpriteCollection &sprite, uint8_t sprite_avail, SpriteEncoder *encoder)
331{
332 /* Get minimum top left corner coordinates. */
333 int min_xoffs = INT32_MAX;
334 int min_yoffs = INT32_MAX;
335 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
336 if (HasBit(sprite_avail, zoom)) {
337 min_xoffs = std::min(min_xoffs, ScaleByZoom(sprite[zoom].x_offs, zoom));
338 min_yoffs = std::min(min_yoffs, ScaleByZoom(sprite[zoom].y_offs, zoom));
339 }
340 }
341
342 /* Get maximum dimensions taking necessary padding at the top left into account. */
343 int max_width = INT32_MIN;
344 int max_height = INT32_MIN;
345 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
346 if (HasBit(sprite_avail, zoom)) {
347 max_width = std::max(max_width, ScaleByZoom(sprite[zoom].width + sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom), zoom));
348 max_height = std::max(max_height, ScaleByZoom(sprite[zoom].height + sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom), zoom));
349 }
350 }
351
352 /* Align height and width if required to match the needs of the sprite encoder. */
353 uint align = encoder->GetSpriteAlignment();
354 if (align != 0) {
355 max_width = Align(max_width, align);
356 max_height = Align(max_height, align);
357 }
358
359 /* Pad sprites where needed. */
360 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
361 if (HasBit(sprite_avail, zoom)) {
362 /* Scaling the sprite dimensions in the blitter is done with rounding up,
363 * so a negative padding here is not an error. */
364 int pad_left = std::max(0, sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom));
365 int pad_top = std::max(0, sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom));
366 int pad_right = std::max(0, UnScaleByZoom(max_width, zoom) - sprite[zoom].width - pad_left);
367 int pad_bottom = std::max(0, UnScaleByZoom(max_height, zoom) - sprite[zoom].height - pad_top);
368
369 if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) {
370 if (!PadSingleSprite(&sprite[zoom], zoom, pad_left, pad_top, pad_right, pad_bottom)) return false;
371 }
372 }
373 }
374
375 return true;
376}
377
378static bool ResizeSprites(SpriteLoader::SpriteCollection &sprite, uint8_t sprite_avail, SpriteEncoder *encoder)
379{
380 /* Create a fully zoomed image if it does not exist */
381 ZoomLevel first_avail = static_cast<ZoomLevel>(FindFirstBit(sprite_avail));
382 if (first_avail != ZOOM_LVL_MIN) {
383 if (!ResizeSpriteIn(sprite, first_avail, ZOOM_LVL_MIN)) return false;
384 SetBit(sprite_avail, ZOOM_LVL_MIN);
385 }
386
387 /* Pad sprites to make sizes match. */
388 if (!PadSprites(sprite, sprite_avail, encoder)) return false;
389
390 /* Create other missing zoom levels */
391 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
392 if (zoom == ZOOM_LVL_MIN) continue;
393
394 if (HasBit(sprite_avail, zoom)) {
395 /* Check that size and offsets match the fully zoomed image. */
396 assert(sprite[zoom].width == UnScaleByZoom(sprite[ZOOM_LVL_MIN].width, zoom));
397 assert(sprite[zoom].height == UnScaleByZoom(sprite[ZOOM_LVL_MIN].height, zoom));
398 assert(sprite[zoom].x_offs == UnScaleByZoom(sprite[ZOOM_LVL_MIN].x_offs, zoom));
399 assert(sprite[zoom].y_offs == UnScaleByZoom(sprite[ZOOM_LVL_MIN].y_offs, zoom));
400 }
401
402 /* Zoom level is not available, or unusable, so create it */
403 if (!HasBit(sprite_avail, zoom)) ResizeSpriteOut(sprite, zoom);
404 }
405
406 /* Upscale to desired sprite_min_zoom if provided sprite only had zoomed in versions. */
407 if (first_avail < _settings_client.gui.sprite_zoom_min) {
410 }
411
412 return true;
413}
414
423static void *ReadRecolourSprite(SpriteFile &file, size_t file_pos, uint num, SpriteAllocator &allocator)
424{
425 /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
426 * number of recolour sprites that are 17 bytes that only exist in DOS
427 * GRFs which are the same as 257 byte recolour sprites, but with the last
428 * 240 bytes zeroed. */
429 static const uint RECOLOUR_SPRITE_SIZE = 257;
430 uint8_t *dest = allocator.Allocate<uint8_t>(std::max(RECOLOUR_SPRITE_SIZE, num));
431
432 file.SeekTo(file_pos, SEEK_SET);
433 if (file.NeedsPaletteRemap()) {
434 uint8_t *dest_tmp = new uint8_t[std::max(RECOLOUR_SPRITE_SIZE, num)];
435
436 /* Only a few recolour sprites are less than 257 bytes */
437 if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
438 file.ReadBlock(dest_tmp, num);
439
440 /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
441 for (uint i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
442 dest[i] = _palmap_w2d[dest_tmp[_palmap_d2w[i - 1] + 1]];
443 }
444 delete[] dest_tmp;
445 } else {
446 file.ReadBlock(dest, num);
447 }
448
449 return dest;
450}
451
461static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, SpriteAllocator &allocator, SpriteEncoder *encoder)
462{
463 /* Use current blitter if no other sprite encoder is given. */
464 if (encoder == nullptr) encoder = BlitterFactory::GetCurrentBlitter();
465
466 SpriteFile &file = *sc->file;
467 size_t file_pos = sc->file_pos;
468
469 assert(sprite_type != SpriteType::Recolour);
470 assert(IsMapgenSpriteID(id) == (sprite_type == SpriteType::MapGen));
471 assert(sc->type == sprite_type);
472
473 Debug(sprite, 9, "Load sprite {}", id);
474
476 uint8_t sprite_avail = 0;
477 uint8_t avail_8bpp = 0;
478 uint8_t avail_32bpp = 0;
479 sprite[ZOOM_LVL_MIN].type = sprite_type;
480
481 SpriteLoaderGrf sprite_loader(file.GetContainerVersion());
482 if (sprite_type != SpriteType::MapGen && encoder->Is32BppSupported()) {
483 /* Try for 32bpp sprites first. */
484 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, true, sc->control_flags, avail_8bpp, avail_32bpp);
485 }
486 if (sprite_avail == 0) {
487 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, false, sc->control_flags, avail_8bpp, avail_32bpp);
488 if (sprite_type == SpriteType::Normal && avail_32bpp != 0 && !encoder->Is32BppSupported() && sprite_avail == 0) {
489 /* No 8bpp available, try converting from 32bpp. */
490 SpriteLoaderMakeIndexed make_indexed(sprite_loader);
491 sprite_avail = make_indexed.LoadSprite(sprite, file, file_pos, sprite_type, true, sc->control_flags, sprite_avail, avail_32bpp);
492 }
493 }
494
495 if (sprite_avail == 0) {
496 if (sprite_type == SpriteType::MapGen) return nullptr;
497 if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
498 return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder);
499 }
500
501 if (sprite_type == SpriteType::MapGen) {
502 /* Ugly hack to work around the problem that the old landscape
503 * generator assumes that those sprites are stored uncompressed in
504 * the memory, and they are only read directly by the code, never
505 * send to the blitter. So do not send it to the blitter (which will
506 * result in a data array in the format the blitter likes most), but
507 * extract the data directly and store that as sprite.
508 * Ugly: yes. Other solution: no. Blame the original author or
509 * something ;) The image should really have been a data-stream
510 * (so type = 0xFF basically). */
511 uint num = sprite[ZOOM_LVL_MIN].width * sprite[ZOOM_LVL_MIN].height;
512
513 Sprite *s = allocator.Allocate<Sprite>(sizeof(*s) + num);
514 s->width = sprite[ZOOM_LVL_MIN].width;
515 s->height = sprite[ZOOM_LVL_MIN].height;
516 s->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
517 s->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
518
519 SpriteLoader::CommonPixel *src = sprite[ZOOM_LVL_MIN].data;
520 uint8_t *dest = s->data;
521 while (num-- > 0) {
522 *dest++ = src->m;
523 src++;
524 }
525
526 return s;
527 }
528
529 if (!ResizeSprites(sprite, sprite_avail, encoder)) {
530 if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't resize the fallback sprite. What should I do?");
531 return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder);
532 }
533
534 if (sprite[ZOOM_LVL_MIN].type == SpriteType::Font && _font_zoom != ZOOM_LVL_MIN) {
535 /* Make ZOOM_LVL_MIN be ZOOM_LVL_GUI */
536 sprite[ZOOM_LVL_MIN].width = sprite[_font_zoom].width;
537 sprite[ZOOM_LVL_MIN].height = sprite[_font_zoom].height;
538 sprite[ZOOM_LVL_MIN].x_offs = sprite[_font_zoom].x_offs;
539 sprite[ZOOM_LVL_MIN].y_offs = sprite[_font_zoom].y_offs;
540 sprite[ZOOM_LVL_MIN].data = sprite[_font_zoom].data;
541 sprite[ZOOM_LVL_MIN].colours = sprite[_font_zoom].colours;
542 }
543
544 return encoder->Encode(sprite, allocator);
545}
546
548 size_t file_pos;
549 uint8_t control_flags;
550};
551
553static std::map<uint32_t, GrfSpriteOffset> _grf_sprite_offsets;
554
560size_t GetGRFSpriteOffset(uint32_t id)
561{
562 return _grf_sprite_offsets.find(id) != _grf_sprite_offsets.end() ? _grf_sprite_offsets[id].file_pos : SIZE_MAX;
563}
564
570{
571 _grf_sprite_offsets.clear();
572
573 if (file.GetContainerVersion() >= 2) {
574 /* Seek to sprite section of the GRF. */
575 size_t data_offset = file.ReadDword();
576 size_t old_pos = file.GetPos();
577 file.SeekTo(data_offset, SEEK_CUR);
578
579 GrfSpriteOffset offset = { 0, 0 };
580
581 /* Loop over all sprite section entries and store the file
582 * offset for each newly encountered ID. */
583 SpriteID id, prev_id = 0;
584 while ((id = file.ReadDword()) != 0) {
585 if (id != prev_id) {
586 _grf_sprite_offsets[prev_id] = offset;
587 offset.file_pos = file.GetPos() - 4;
588 offset.control_flags = 0;
589 }
590 prev_id = id;
591 uint length = file.ReadDword();
592 if (length > 0) {
593 SpriteComponents colour{file.ReadByte()};
594 length--;
595 if (length > 0) {
596 uint8_t zoom = file.ReadByte();
597 length--;
598 if (colour != SpriteComponents{} && zoom == 0) { // ZOOM_LVL_NORMAL (normal zoom)
601 }
602 if (colour != SpriteComponents{} && zoom == 2) { // ZOOM_LVL_IN_2X (2x zoomed in)
604 }
605 }
606 }
607 file.SkipBytes(length);
608 }
609 if (prev_id != 0) _grf_sprite_offsets[prev_id] = offset;
610
611 /* Continue processing the data section. */
612 file.SeekTo(old_pos, SEEK_SET);
613 }
614}
615
616
625bool LoadNextSprite(SpriteID load_index, SpriteFile &file, uint file_sprite_id)
626{
627 size_t file_pos = file.GetPos();
628
629 /* Read sprite header. */
630 uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
631 if (num == 0) return false;
632 uint8_t grf_type = file.ReadByte();
633
634 SpriteType type;
635 void *data = nullptr;
636 uint8_t control_flags = 0;
637 if (grf_type == 0xFF) {
638 /* Some NewGRF files have "empty" pseudo-sprites which are 1
639 * byte long. Catch these so the sprites won't be displayed. */
640 if (num == 1) {
641 file.ReadByte();
642 return false;
643 }
644 file_pos = file.GetPos();
646 file.SkipBytes(num);
647 } else if (file.GetContainerVersion() >= 2 && grf_type == 0xFD) {
648 if (num != 4) {
649 /* Invalid sprite section include, ignore. */
650 file.SkipBytes(num);
651 return false;
652 }
653 /* It is not an error if no sprite with the provided ID is found in the sprite section. */
654 auto iter = _grf_sprite_offsets.find(file.ReadDword());
655 if (iter != _grf_sprite_offsets.end()) {
656 file_pos = iter->second.file_pos;
657 control_flags = iter->second.control_flags;
658 } else {
659 file_pos = SIZE_MAX;
660 }
661 type = SpriteType::Normal;
662 } else {
663 file.SkipBytes(7);
664 type = SkipSpriteData(file, grf_type, num - 8) ? SpriteType::Normal : SpriteType::Invalid;
665 /* Inline sprites are not supported for container version >= 2. */
666 if (file.GetContainerVersion() >= 2) return false;
667 }
668
669 if (type == SpriteType::Invalid) return false;
670
671 if (load_index >= MAX_SPRITES) {
672 UserError("Tried to load too many sprites (#{}; max {})", load_index, MAX_SPRITES);
673 }
674
675 bool is_mapgen = IsMapgenSpriteID(load_index);
676
677 if (is_mapgen) {
678 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?");
679 type = SpriteType::MapGen;
680 }
681
682 SpriteCache *sc = AllocateSpriteCache(load_index);
683 sc->file = &file;
684 sc->file_pos = file_pos;
685 sc->length = num;
686 sc->ptr = data;
687 sc->lru = 0;
688 sc->id = file_sprite_id;
689 sc->type = type;
690 sc->warned = false;
691 sc->control_flags = control_flags;
692
693 return true;
694}
695
696
697void DupSprite(SpriteID old_spr, SpriteID new_spr)
698{
699 SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
700 SpriteCache *scold = GetSpriteCache(old_spr);
701
702 scnew->file = scold->file;
703 scnew->file_pos = scold->file_pos;
704 scnew->ptr = nullptr;
705 scnew->id = scold->id;
706 scnew->type = scold->type;
707 scnew->warned = false;
708 scnew->control_flags = scold->control_flags;
709}
710
717static const size_t S_FREE_MASK = sizeof(size_t) - 1;
718
719/* to make sure nobody adds things to MemBlock without checking S_FREE_MASK first */
720static_assert(sizeof(MemBlock) == sizeof(size_t));
721/* make sure it's a power of two */
722static_assert((sizeof(size_t) & (sizeof(size_t) - 1)) == 0);
723
724static inline MemBlock *NextBlock(MemBlock *block)
725{
726 return (MemBlock*)((uint8_t*)block + (block->size & ~S_FREE_MASK));
727}
728
729static size_t GetSpriteCacheUsage()
730{
731 size_t tot_size = 0;
732 MemBlock *s;
733
734 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
735 if (!(s->size & S_FREE_MASK)) tot_size += s->size;
736 }
737
738 return tot_size;
739}
740
741
742void IncreaseSpriteLRU()
743{
744 /* Increase all LRU values */
745 if (_sprite_lru_counter > 16384) {
746 Debug(sprite, 5, "Fixing lru {}, inuse={}", _sprite_lru_counter, GetSpriteCacheUsage());
747
748 for (SpriteCache &sc : _spritecache) {
749 if (sc.ptr != nullptr) {
750 if (sc.lru >= 0) {
751 sc.lru = -1;
752 } else if (sc.lru != -32768) {
753 sc.lru--;
754 }
755 }
756 }
757 _sprite_lru_counter = 0;
758 }
759
760 /* Compact sprite cache every now and then. */
761 if (++_compact_cache_counter >= 740) {
763 _compact_cache_counter = 0;
764 }
765}
766
772{
773 MemBlock *s;
774
775 Debug(sprite, 3, "Compacting sprite cache, inuse={}", GetSpriteCacheUsage());
776
777 for (s = _spritecache_ptr; s->size != 0;) {
778 if (s->size & S_FREE_MASK) {
779 MemBlock *next = NextBlock(s);
780 MemBlock temp;
781 SpriteID i;
782
783 /* Since free blocks are automatically coalesced, this should hold true. */
784 assert(!(next->size & S_FREE_MASK));
785
786 /* If the next block is the sentinel block, we can safely return */
787 if (next->size == 0) break;
788
789 /* Locate the sprite belonging to the next pointer. */
790 for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
791 assert(i != _spritecache.size());
792 }
793
794 GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
795 /* Swap this and the next block */
796 temp = *s;
797 memmove(s, next, next->size);
798 s = NextBlock(s);
799 *s = temp;
800
801 /* Coalesce free blocks */
802 while (NextBlock(s)->size & S_FREE_MASK) {
803 s->size += NextBlock(s)->size & ~S_FREE_MASK;
804 }
805 } else {
806 s = NextBlock(s);
807 }
808 }
809}
810
816{
817 /* Mark the block as free (the block must be in use) */
818 MemBlock *s = static_cast<MemBlock *>(item->ptr) - 1;
819 assert(!(s->size & S_FREE_MASK));
820 s->size |= S_FREE_MASK;
821 item->ptr = nullptr;
822
823 /* And coalesce adjacent free blocks */
824 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
825 if (s->size & S_FREE_MASK) {
826 while (NextBlock(s)->size & S_FREE_MASK) {
827 s->size += NextBlock(s)->size & ~S_FREE_MASK;
828 }
829 }
830 }
831}
832
833static void DeleteEntryFromSpriteCache()
834{
835 Debug(sprite, 3, "DeleteEntryFromSpriteCache, inuse={}", GetSpriteCacheUsage());
836
837 SpriteCache *best = nullptr;
838 int cur_lru = 0xffff;
839 for (SpriteCache &sc : _spritecache) {
840 if (sc.ptr != nullptr && sc.lru < cur_lru) {
841 cur_lru = sc.lru;
842 best = &sc;
843 }
844 }
845
846 /* Display an error message and die, in case we found no sprite at all.
847 * This shouldn't really happen, unless all sprites are locked. */
848 if (best == nullptr) FatalError("Out of sprite memory");
849
851}
852
854{
855 mem_req += sizeof(MemBlock);
856
857 /* Align this to correct boundary. This also makes sure at least one
858 * bit is not used, so we can use it for other things. */
859 mem_req = Align(mem_req, S_FREE_MASK + 1);
860
861 for (;;) {
862 MemBlock *s;
863
864 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
865 if (s->size & S_FREE_MASK) {
866 size_t cur_size = s->size & ~S_FREE_MASK;
867
868 /* Is the block exactly the size we need or
869 * big enough for an additional free block? */
870 if (cur_size == mem_req ||
871 cur_size >= mem_req + sizeof(MemBlock)) {
872 /* Set size and in use */
873 s->size = mem_req;
874
875 /* Do we need to inject a free block too? */
876 if (cur_size != mem_req) {
877 NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
878 }
879
880 return s->data;
881 }
882 }
883 }
884
885 /* Reached sentinel, but no block found yet. Delete some old entry. */
887 }
888}
889
891{
892 this->data = std::make_unique<uint8_t[]>(size);
893 return this->data.get();
894}
895
905static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, SpriteAllocator *allocator)
906{
907 static const char * const sprite_types[] = {
908 "normal", // SpriteType::Normal
909 "map generator", // SpriteType::MapGen
910 "character", // SpriteType::Font
911 "recolour", // SpriteType::Recolour
912 };
913
914 SpriteType available = sc->type;
915 if (requested == SpriteType::Font && available == SpriteType::Normal) {
916 if (sc->ptr == nullptr) sc->type = SpriteType::Font;
917 return GetRawSprite(sprite, sc->type, allocator);
918 }
919
920 uint8_t warning_level = sc->warned ? 6 : 0;
921 sc->warned = true;
922 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)]);
923
924 switch (requested) {
926 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?");
927 [[fallthrough]];
928 case SpriteType::Font:
929 return GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, allocator);
931 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?");
932 return GetRawSprite(PALETTE_TO_DARK_BLUE, SpriteType::Recolour, allocator);
934 /* this shouldn't happen, overriding of SpriteType::MapGen sprites is checked in LoadNextSprite()
935 * (the only case the check fails is when these sprites weren't even loaded...) */
936 default:
937 NOT_REACHED();
938 }
939}
940
950void *GetRawSprite(SpriteID sprite, SpriteType type, SpriteAllocator *allocator, SpriteEncoder *encoder)
951{
952 assert(type != SpriteType::MapGen || IsMapgenSpriteID(sprite));
953 assert(type < SpriteType::Invalid);
954
955 if (!SpriteExists(sprite)) {
956 Debug(sprite, 1, "Tried to load non-existing sprite #{}. Probable cause: Wrong/missing NewGRFs", sprite);
957
958 /* SPR_IMG_QUERY is a BIG FAT RED ? */
959 sprite = SPR_IMG_QUERY;
960 }
961
962 SpriteCache *sc = GetSpriteCache(sprite);
963
964 if (sc->type != type) return HandleInvalidSpriteRequest(sprite, type, sc, allocator);
965
966 if (allocator == nullptr && encoder == nullptr) {
967 /* Load sprite into/from spritecache */
968 CacheSpriteAllocator cache_allocator;
969
970 /* Update LRU */
971 sc->lru = ++_sprite_lru_counter;
972
973 /* Load the sprite, if it is not loaded, yet */
974 if (sc->ptr == nullptr) {
975 if (sc->type == SpriteType::Recolour) {
976 sc->ptr = ReadRecolourSprite(*sc->file, sc->file_pos, sc->length, cache_allocator);
977 } else {
978 sc->ptr = ReadSprite(sc, sprite, type, cache_allocator, nullptr);
979 }
980 }
981
982 return sc->ptr;
983 } else {
984 /* Do not use the spritecache, but a different allocator. */
985 return ReadSprite(sc, sprite, type, *allocator, encoder);
986 }
987}
988
989
990static void GfxInitSpriteCache()
991{
992 /* initialize sprite cache heap */
994 uint target_size = (bpp > 0 ? _sprite_cache_size * bpp / 8 : 1) * 1024 * 1024;
995
996 /* Remember 'target_size' from the previous allocation attempt, so we do not try to reach the target_size multiple times in case of failure. */
997 static uint last_alloc_attempt = 0;
998
999 if (_spritecache_ptr == nullptr || (_allocated_sprite_cache_size != target_size && target_size != last_alloc_attempt)) {
1000 delete[] reinterpret_cast<uint8_t *>(_spritecache_ptr);
1001
1002 last_alloc_attempt = target_size;
1003 _allocated_sprite_cache_size = target_size;
1004
1005 do {
1006 /* Try to allocate 50% more to make sure we do not allocate almost all available. */
1007 _spritecache_ptr = reinterpret_cast<MemBlock *>(new(std::nothrow) uint8_t[_allocated_sprite_cache_size + _allocated_sprite_cache_size / 2]);
1008
1009 if (_spritecache_ptr != nullptr) {
1010 /* Allocation succeeded, but we wanted less. */
1011 delete[] reinterpret_cast<uint8_t *>(_spritecache_ptr);
1012 _spritecache_ptr = reinterpret_cast<MemBlock *>(new uint8_t[_allocated_sprite_cache_size]);
1013 } else if (_allocated_sprite_cache_size < 2 * 1024 * 1024) {
1014 UserError("Cannot allocate spritecache");
1015 } else {
1016 /* Try again to allocate half. */
1017 _allocated_sprite_cache_size >>= 1;
1018 }
1019 } while (_spritecache_ptr == nullptr);
1020
1021 if (_allocated_sprite_cache_size != target_size) {
1022 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);
1023
1024 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR_OUT_OF_MEMORY), GetEncodedString(STR_CONFIG_ERROR_SPRITECACHE_TOO_BIG, target_size, _allocated_sprite_cache_size));
1026 }
1027 }
1028
1029 /* A big free block */
1030 _spritecache_ptr->size = (_allocated_sprite_cache_size - sizeof(MemBlock)) | S_FREE_MASK;
1031 /* Sentinel block (identified by size == 0) */
1032 NextBlock(_spritecache_ptr)->size = 0;
1033}
1034
1035void GfxInitSpriteMem()
1036{
1037 GfxInitSpriteCache();
1038
1039 /* Reset the spritecache 'pool' */
1040 _spritecache.clear();
1041 _spritecache.shrink_to_fit();
1042
1043 _compact_cache_counter = 0;
1044 _sprite_files.clear();
1045}
1046
1052{
1053 /* Clear sprite ptr for all cached items */
1054 for (SpriteCache &sc : _spritecache) {
1055 if (sc.ptr != nullptr) DeleteEntryFromSpriteCache(&sc);
1056 }
1057
1059}
1060
1066{
1067 /* Clear sprite ptr for all cached font items */
1068 for (SpriteCache &sc : _spritecache) {
1069 if (sc.type == SpriteType::Font && sc.ptr != nullptr) DeleteEntryFromSpriteCache(&sc);
1070 }
1071}
1072
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:138
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.
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).
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Interface for something that can allocate memory for a sprite.
T * Allocate(size_t size)
Allocate memory for a sprite.
Interface for something that can encode a sprite.
virtual Sprite * Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator)=0
Convert a sprite from the loader to our own format.
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.
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
uint8_t LoadSprite(SpriteLoader::SpriteCollection &sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, bool load_32bpp, uint8_t control_flags, uint8_t &avail_8bpp, uint8_t &avail_32bpp) override
Load a sprite from the disk and return a sprite struct which is the same for all loaders.
Definition grf.cpp:358
Sprite loader for converting graphics coming from another source.
Definition makeindexed.h:16
uint8_t LoadSprite(SpriteLoader::SpriteCollection &sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, bool load_32bpp, uint8_t control_flags, uint8_t &avail_8bpp, uint8_t &avail_32bpp) override
Load a sprite from the disk and return a sprite struct which is the same for all loaders.
std::array< Sprite, ZOOM_LVL_END > SpriteCollection
Type defining a collection of sprites, one for each zoom level.
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.
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:344
@ 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
Functions related to memory operations.
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:57
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:90
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 ReusableBuffer< SpriteLoader::CommonPixel > buffer[ZOOM_LVL_END]
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
uint8_t 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 > ZOOM_LVL_MIN) When shifting right,...
Definition zoom_func.h:22
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZOOM_LVL_MIN) When shifting right,...
Definition zoom_func.h:34
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:16
@ ZOOM_LVL_NORMAL
The normal zoom level.
Definition zoom_type.h:21
@ ZOOM_LVL_BEGIN
Begin for iteration.
Definition zoom_type.h:18
@ ZOOM_LVL_IN_2X
Zoomed 2 times in.
Definition zoom_type.h:20
@ ZOOM_LVL_END
End for iteration.
Definition zoom_type.h:25
@ ZOOM_LVL_MIN
Minimum zoom level.
Definition zoom_type.h:41
@ ZOOM_LVL_IN_4X
Zoomed 4 times in.
Definition zoom_type.h:19