OpenTTD Source: src/spritecache.cpp Source File

OpenTTD Source 15.0-beta1

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"
11#include "random_access_file_type.h"
12#include "spriteloader/grf.hpp"
13#include "gfx_func.h"
14#include "error.h"
15#include "error_func.h"
16#include "zoom_func.h"
17#include "settings_type.h"
18#include "blitter/factory.hpp"
19#include "core/math_func.hpp"
20#include "core/mem_func.hpp"
21#include "video/video_driver.hpp"
22#include "spritecache.h"
23#include "spritecache_internal.h"
24
25#include "table/sprites.h"
26#include "table/strings.h"
27#include "table/palette_convert.h"
28
29#include "safeguards.h"
30
31/* Default of 4MB spritecache */
32uint _sprite_cache_size = 4;
33
34
35static uint _spritecache_items = 0;
36static SpriteCache *_spritecache = nullptr;
37static std::vector<std::unique_ptr<SpriteFile>> _sprite_files;
38
39static inline SpriteCache *GetSpriteCache(uint index)
40{
41 return &_spritecache[index];
42}
43
44 SpriteCache *AllocateSpriteCache(uint index)
45{
46 if (index >= _spritecache_items) {
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 = ReallocT(_spritecache, items);
53
54 /* Reset the new items and update the count */
55 memset(_spritecache + _spritecache_items, 0, (items - _spritecache_items) * sizeof(*_spritecache));
56 _spritecache_items = items;
57 }
58
59 return GetSpriteCache(index);
60}
61
67 static SpriteFile *GetCachedSpriteFileByName(const std::string &filename)
68{
69 for (auto &f : _sprite_files) {
70 if (f->GetFilename() == filename) {
71 return f.get();
72 }
73 }
74 return nullptr;
75}
76
81std::span<const std::unique_ptr<SpriteFile>> GetCachedSpriteFiles()
82{
83 return _sprite_files;
84}
85
93 SpriteFile &OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
94{
95 SpriteFile *file = GetCachedSpriteFileByName(filename);
96 if (file == nullptr) {
97 file = _sprite_files.insert(std::end(_sprite_files), std::make_unique<SpriteFile>(filename, subdir, palette_remap))->get();
98 } else {
99 file->SeekToBegin();
100 }
101 return *file;
102}
103
104 struct MemBlock {
105 size_t size;
106 uint8_t data[];
107};
108
109static uint _sprite_lru_counter;
110static MemBlock *_spritecache_ptr;
111static uint _allocated_sprite_cache_size = 0;
112static int _compact_cache_counter;
113
114static void CompactSpriteCache();
115
122 bool SkipSpriteData(SpriteFile &file, uint8_t type, uint16_t num)
123{
124 if (type & 2) {
125 file.SkipBytes(num);
126 } else {
127 while (num > 0) {
128 int8_t i = file.ReadByte();
129 if (i >= 0) {
130 int size = (i == 0) ? 0x80 : i;
131 if (size > num) return false;
132 num -= size;
133 file.SkipBytes(size);
134 } else {
135 i = -(i >> 3);
136 num -= i;
137 file.ReadByte();
138 }
139 }
140 }
141 return true;
142}
143
144/* Check if the given Sprite ID exists */
145bool SpriteExists(SpriteID id)
146{
147 if (id >= _spritecache_items) return false;
148
149 /* Special case for Sprite ID zero -- its position is also 0... */
150 if (id == 0) return true;
151 return !(GetSpriteCache(id)->file_pos == 0 && GetSpriteCache(id)->file == nullptr);
152}
153
159 SpriteType GetSpriteType(SpriteID sprite)
160{
161 if (!SpriteExists(sprite)) return SpriteType::Invalid;
162 return GetSpriteCache(sprite)->type;
163}
164
170 SpriteFile *GetOriginFile(SpriteID sprite)
171{
172 if (!SpriteExists(sprite)) return nullptr;
173 return GetSpriteCache(sprite)->file;
174}
175
181uint32_t GetSpriteLocalID(SpriteID sprite)
182{
183 if (!SpriteExists(sprite)) return 0;
184 return GetSpriteCache(sprite)->id;
185}
186
194uint GetSpriteCountForFile(const std::string &filename, SpriteID begin, SpriteID end)
195{
196 SpriteFile *file = GetCachedSpriteFileByName(filename);
197 if (file == nullptr) return 0;
198
199 uint count = 0;
200 for (SpriteID i = begin; i != end; i++) {
201 if (SpriteExists(i)) {
202 SpriteCache *sc = GetSpriteCache(i);
203 if (sc->file == file) {
204 count++;
205 Debug(sprite, 4, "Sprite: {}", i);
206 }
207 }
208 }
209 return count;
210}
211
220uint GetMaxSpriteID()
221{
222 return _spritecache_items;
223}
224
225static bool ResizeSpriteIn(SpriteLoader::SpriteCollection &sprite, ZoomLevel src, ZoomLevel tgt)
226{
227 uint8_t scaled_1 = ScaleByZoom(1, (ZoomLevel)(src - tgt));
228
229 /* Check for possible memory overflow. */
230 if (sprite[src].width * scaled_1 > UINT16_MAX || sprite[src].height * scaled_1 > UINT16_MAX) return false;
231
232 sprite[tgt].width = sprite[src].width * scaled_1;
233 sprite[tgt].height = sprite[src].height * scaled_1;
234 sprite[tgt].x_offs = sprite[src].x_offs * scaled_1;
235 sprite[tgt].y_offs = sprite[src].y_offs * scaled_1;
236 sprite[tgt].colours = sprite[src].colours;
237
238 sprite[tgt].AllocateData(tgt, static_cast<size_t>(sprite[tgt].width) * sprite[tgt].height);
239
240 SpriteLoader::CommonPixel *dst = sprite[tgt].data;
241 for (int y = 0; y < sprite[tgt].height; y++) {
242 const SpriteLoader::CommonPixel *src_ln = &sprite[src].data[y / scaled_1 * sprite[src].width];
243 for (int x = 0; x < sprite[tgt].width; x++) {
244 *dst = src_ln[x / scaled_1];
245 dst++;
246 }
247 }
248
249 return true;
250}
251
252static void ResizeSpriteOut(SpriteLoader::SpriteCollection &sprite, ZoomLevel zoom)
253{
254 /* Algorithm based on 32bpp_Optimized::ResizeSprite() */
255 sprite[zoom].width = UnScaleByZoom(sprite[ZOOM_LVL_MIN].width, zoom);
256 sprite[zoom].height = UnScaleByZoom(sprite[ZOOM_LVL_MIN].height, zoom);
257 sprite[zoom].x_offs = UnScaleByZoom(sprite[ZOOM_LVL_MIN].x_offs, zoom);
258 sprite[zoom].y_offs = UnScaleByZoom(sprite[ZOOM_LVL_MIN].y_offs, zoom);
259 sprite[zoom].colours = sprite[ZOOM_LVL_MIN].colours;
260
261 sprite[zoom].AllocateData(zoom, static_cast<size_t>(sprite[zoom].height) * sprite[zoom].width);
262
263 SpriteLoader::CommonPixel *dst = sprite[zoom].data;
264 const SpriteLoader::CommonPixel *src = sprite[zoom - 1].data;
265 [[maybe_unused]] const SpriteLoader::CommonPixel *src_end = src + sprite[zoom - 1].height * sprite[zoom - 1].width;
266
267 for (uint y = 0; y < sprite[zoom].height; y++) {
268 const SpriteLoader::CommonPixel *src_ln = src + sprite[zoom - 1].width;
269 assert(src_ln <= src_end);
270 for (uint x = 0; x < sprite[zoom].width; x++) {
271 assert(src < src_ln);
272 if (src + 1 != src_ln && (src + 1)->a != 0) {
273 *dst = *(src + 1);
274 } else {
275 *dst = *src;
276 }
277 dst++;
278 src += 2;
279 }
280 src = src_ln + sprite[zoom - 1].width;
281 }
282}
283
284static bool PadSingleSprite(SpriteLoader::Sprite *sprite, ZoomLevel zoom, uint pad_left, uint pad_top, uint pad_right, uint pad_bottom)
285{
286 uint width = sprite->width + pad_left + pad_right;
287 uint height = sprite->height + pad_top + pad_bottom;
288
289 if (width > UINT16_MAX || height > UINT16_MAX) return false;
290
291 /* Copy source data and reallocate sprite memory. */
292 size_t sprite_size = static_cast<size_t>(sprite->width) * sprite->height;
293 std::vector<SpriteLoader::CommonPixel> src_data(sprite->data, sprite->data + sprite_size);
294 sprite->AllocateData(zoom, static_cast<size_t>(width) * height);
295
296 /* Copy with padding to destination. */
297 SpriteLoader::CommonPixel *src = src_data.data();
298 SpriteLoader::CommonPixel *data = sprite->data;
299 for (uint y = 0; y < height; y++) {
300 if (y < pad_top || pad_bottom + y >= height) {
301 /* Top/bottom padding. */
302 MemSetT(data, 0, width);
303 data += width;
304 } else {
305 if (pad_left > 0) {
306 /* Pad left. */
307 MemSetT(data, 0, pad_left);
308 data += pad_left;
309 }
310
311 /* Copy pixels. */
312 MemCpyT(data, src, sprite->width);
313 src += sprite->width;
314 data += sprite->width;
315
316 if (pad_right > 0) {
317 /* Pad right. */
318 MemSetT(data, 0, pad_right);
319 data += pad_right;
320 }
321 }
322 }
323
324 /* Update sprite size. */
325 sprite->width = width;
326 sprite->height = height;
327 sprite->x_offs -= pad_left;
328 sprite->y_offs -= pad_top;
329
330 return true;
331}
332
333static bool PadSprites(SpriteLoader::SpriteCollection &sprite, uint8_t sprite_avail, SpriteEncoder *encoder)
334{
335 /* Get minimum top left corner coordinates. */
336 int min_xoffs = INT32_MAX;
337 int min_yoffs = INT32_MAX;
338 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
339 if (HasBit(sprite_avail, zoom)) {
340 min_xoffs = std::min(min_xoffs, ScaleByZoom(sprite[zoom].x_offs, zoom));
341 min_yoffs = std::min(min_yoffs, ScaleByZoom(sprite[zoom].y_offs, zoom));
342 }
343 }
344
345 /* Get maximum dimensions taking necessary padding at the top left into account. */
346 int max_width = INT32_MIN;
347 int max_height = INT32_MIN;
348 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
349 if (HasBit(sprite_avail, zoom)) {
350 max_width = std::max(max_width, ScaleByZoom(sprite[zoom].width + sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom), zoom));
351 max_height = std::max(max_height, ScaleByZoom(sprite[zoom].height + sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom), zoom));
352 }
353 }
354
355 /* Align height and width if required to match the needs of the sprite encoder. */
356 uint align = encoder->GetSpriteAlignment();
357 if (align != 0) {
358 max_width = Align(max_width, align);
359 max_height = Align(max_height, align);
360 }
361
362 /* Pad sprites where needed. */
363 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
364 if (HasBit(sprite_avail, zoom)) {
365 /* Scaling the sprite dimensions in the blitter is done with rounding up,
366 * so a negative padding here is not an error. */
367 int pad_left = std::max(0, sprite[zoom].x_offs - UnScaleByZoom(min_xoffs, zoom));
368 int pad_top = std::max(0, sprite[zoom].y_offs - UnScaleByZoom(min_yoffs, zoom));
369 int pad_right = std::max(0, UnScaleByZoom(max_width, zoom) - sprite[zoom].width - pad_left);
370 int pad_bottom = std::max(0, UnScaleByZoom(max_height, zoom) - sprite[zoom].height - pad_top);
371
372 if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) {
373 if (!PadSingleSprite(&sprite[zoom], zoom, pad_left, pad_top, pad_right, pad_bottom)) return false;
374 }
375 }
376 }
377
378 return true;
379}
380
381static bool ResizeSprites(SpriteLoader::SpriteCollection &sprite, uint8_t sprite_avail, SpriteEncoder *encoder)
382{
383 /* Create a fully zoomed image if it does not exist */
384 ZoomLevel first_avail = static_cast<ZoomLevel>(FindFirstBit(sprite_avail));
385 if (first_avail != ZOOM_LVL_MIN) {
386 if (!ResizeSpriteIn(sprite, first_avail, ZOOM_LVL_MIN)) return false;
387 SetBit(sprite_avail, ZOOM_LVL_MIN);
388 }
389
390 /* Pad sprites to make sizes match. */
391 if (!PadSprites(sprite, sprite_avail, encoder)) return false;
392
393 /* Create other missing zoom levels */
394 for (ZoomLevel zoom = ZOOM_LVL_BEGIN; zoom != ZOOM_LVL_END; zoom++) {
395 if (zoom == ZOOM_LVL_MIN) continue;
396
397 if (HasBit(sprite_avail, zoom)) {
398 /* Check that size and offsets match the fully zoomed image. */
399 assert(sprite[zoom].width == UnScaleByZoom(sprite[ZOOM_LVL_MIN].width, zoom));
400 assert(sprite[zoom].height == UnScaleByZoom(sprite[ZOOM_LVL_MIN].height, zoom));
401 assert(sprite[zoom].x_offs == UnScaleByZoom(sprite[ZOOM_LVL_MIN].x_offs, zoom));
402 assert(sprite[zoom].y_offs == UnScaleByZoom(sprite[ZOOM_LVL_MIN].y_offs, zoom));
403 }
404
405 /* Zoom level is not available, or unusable, so create it */
406 if (!HasBit(sprite_avail, zoom)) ResizeSpriteOut(sprite, zoom);
407 }
408
409 /* Upscale to desired sprite_min_zoom if provided sprite only had zoomed in versions. */
410 if (first_avail < _settings_client.gui.sprite_zoom_min) {
411 if (_settings_client.gui.sprite_zoom_min >= ZOOM_LVL_NORMAL) ResizeSpriteIn(sprite, ZOOM_LVL_NORMAL, ZOOM_LVL_IN_2X);
412 if (_settings_client.gui.sprite_zoom_min >= ZOOM_LVL_IN_2X) ResizeSpriteIn(sprite, ZOOM_LVL_IN_2X, ZOOM_LVL_IN_4X);
413 }
414
415 return true;
416}
417
426 static void *ReadRecolourSprite(SpriteFile &file, size_t file_pos, uint num, SpriteAllocator &allocator)
427{
428 /* "Normal" recolour sprites are ALWAYS 257 bytes. Then there is a small
429 * number of recolour sprites that are 17 bytes that only exist in DOS
430 * GRFs which are the same as 257 byte recolour sprites, but with the last
431 * 240 bytes zeroed. */
432 static const uint RECOLOUR_SPRITE_SIZE = 257;
433 uint8_t *dest = allocator.Allocate<uint8_t>(std::max(RECOLOUR_SPRITE_SIZE, num));
434
435 file.SeekTo(file_pos, SEEK_SET);
436 if (file.NeedsPaletteRemap()) {
437 uint8_t *dest_tmp = new uint8_t[std::max(RECOLOUR_SPRITE_SIZE, num)];
438
439 /* Only a few recolour sprites are less than 257 bytes */
440 if (num < RECOLOUR_SPRITE_SIZE) memset(dest_tmp, 0, RECOLOUR_SPRITE_SIZE);
441 file.ReadBlock(dest_tmp, num);
442
443 /* The data of index 0 is never used; "literal 00" according to the (New)GRF specs. */
444 for (uint i = 1; i < RECOLOUR_SPRITE_SIZE; i++) {
445 dest[i] = _palmap_w2d[dest_tmp[_palmap_d2w[i - 1] + 1]];
446 }
447 delete[] dest_tmp;
448 } else {
449 file.ReadBlock(dest, num);
450 }
451
452 return dest;
453}
454
464 static void *ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, SpriteAllocator &allocator, SpriteEncoder *encoder)
465{
466 /* Use current blitter if no other sprite encoder is given. */
467 if (encoder == nullptr) encoder = BlitterFactory::GetCurrentBlitter();
468
469 SpriteFile &file = *sc->file;
470 size_t file_pos = sc->file_pos;
471
472 assert(sprite_type != SpriteType::Recolour);
473 assert(IsMapgenSpriteID(id) == (sprite_type == SpriteType::MapGen));
474 assert(sc->type == sprite_type);
475
476 Debug(sprite, 9, "Load sprite {}", id);
477
478 SpriteLoader::SpriteCollection sprite;
479 uint8_t sprite_avail = 0;
480 sprite[ZOOM_LVL_MIN].type = sprite_type;
481
482 SpriteLoaderGrf sprite_loader(file.GetContainerVersion());
483 if (sprite_type != SpriteType::MapGen && encoder->Is32BppSupported()) {
484 /* Try for 32bpp sprites first. */
485 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, true, sc->control_flags);
486 }
487 if (sprite_avail == 0) {
488 sprite_avail = sprite_loader.LoadSprite(sprite, file, file_pos, sprite_type, false, sc->control_flags);
489 }
490
491 if (sprite_avail == 0) {
492 if (sprite_type == SpriteType::MapGen) return nullptr;
493 if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't load the fallback sprite. What should I do?");
494 return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder);
495 }
496
497 if (sprite_type == SpriteType::MapGen) {
498 /* Ugly hack to work around the problem that the old landscape
499 * generator assumes that those sprites are stored uncompressed in
500 * the memory, and they are only read directly by the code, never
501 * send to the blitter. So do not send it to the blitter (which will
502 * result in a data array in the format the blitter likes most), but
503 * extract the data directly and store that as sprite.
504 * Ugly: yes. Other solution: no. Blame the original author or
505 * something ;) The image should really have been a data-stream
506 * (so type = 0xFF basically). */
507 uint num = sprite[ZOOM_LVL_MIN].width * sprite[ZOOM_LVL_MIN].height;
508
509 Sprite *s = allocator.Allocate<Sprite>(sizeof(*s) + num);
510 s->width = sprite[ZOOM_LVL_MIN].width;
511 s->height = sprite[ZOOM_LVL_MIN].height;
512 s->x_offs = sprite[ZOOM_LVL_MIN].x_offs;
513 s->y_offs = sprite[ZOOM_LVL_MIN].y_offs;
514
515 SpriteLoader::CommonPixel *src = sprite[ZOOM_LVL_MIN].data;
516 uint8_t *dest = s->data;
517 while (num-- > 0) {
518 *dest++ = src->m;
519 src++;
520 }
521
522 return s;
523 }
524
525 if (!ResizeSprites(sprite, sprite_avail, encoder)) {
526 if (id == SPR_IMG_QUERY) UserError("Okay... something went horribly wrong. I couldn't resize the fallback sprite. What should I do?");
527 return (void*)GetRawSprite(SPR_IMG_QUERY, SpriteType::Normal, &allocator, encoder);
528 }
529
530 if (sprite[ZOOM_LVL_MIN].type == SpriteType::Font && _font_zoom != ZOOM_LVL_MIN) {
531 /* Make ZOOM_LVL_MIN be ZOOM_LVL_GUI */
532 sprite[ZOOM_LVL_MIN].width = sprite[_font_zoom].width;
533 sprite[ZOOM_LVL_MIN].height = sprite[_font_zoom].height;
534 sprite[ZOOM_LVL_MIN].x_offs = sprite[_font_zoom].x_offs;
535 sprite[ZOOM_LVL_MIN].y_offs = sprite[_font_zoom].y_offs;
536 sprite[ZOOM_LVL_MIN].data = sprite[_font_zoom].data;
537 sprite[ZOOM_LVL_MIN].colours = sprite[_font_zoom].colours;
538 }
539
540 return encoder->Encode(sprite, allocator);
541}
542
543 struct GrfSpriteOffset {
544 size_t file_pos;
545 uint8_t control_flags;
546};
547
549 static std::map<uint32_t, GrfSpriteOffset> _grf_sprite_offsets;
550
556 size_t GetGRFSpriteOffset(uint32_t id)
557{
558 return _grf_sprite_offsets.find(id) != _grf_sprite_offsets.end() ? _grf_sprite_offsets[id].file_pos : SIZE_MAX;
559}
560
565 void ReadGRFSpriteOffsets(SpriteFile &file)
566{
567 _grf_sprite_offsets.clear();
568
569 if (file.GetContainerVersion() >= 2) {
570 /* Seek to sprite section of the GRF. */
571 size_t data_offset = file.ReadDword();
572 size_t old_pos = file.GetPos();
573 file.SeekTo(data_offset, SEEK_CUR);
574
575 GrfSpriteOffset offset = { 0, 0 };
576
577 /* Loop over all sprite section entries and store the file
578 * offset for each newly encountered ID. */
579 SpriteID id, prev_id = 0;
580 while ((id = file.ReadDword()) != 0) {
581 if (id != prev_id) {
582 _grf_sprite_offsets[prev_id] = offset;
583 offset.file_pos = file.GetPos() - 4;
584 offset.control_flags = 0;
585 }
586 prev_id = id;
587 uint length = file.ReadDword();
588 if (length > 0) {
589 uint8_t colour = file.ReadByte() & SCC_MASK;
590 length--;
591 if (length > 0) {
592 uint8_t zoom = file.ReadByte();
593 length--;
594 if (colour != 0 && zoom == 0) { // ZOOM_LVL_NORMAL (normal zoom)
595 SetBit(offset.control_flags, (colour != SCC_PAL) ? SCCF_ALLOW_ZOOM_MIN_1X_32BPP : SCCF_ALLOW_ZOOM_MIN_1X_PAL);
596 SetBit(offset.control_flags, (colour != SCC_PAL) ? SCCF_ALLOW_ZOOM_MIN_2X_32BPP : SCCF_ALLOW_ZOOM_MIN_2X_PAL);
597 }
598 if (colour != 0 && zoom == 2) { // ZOOM_LVL_IN_2X (2x zoomed in)
599 SetBit(offset.control_flags, (colour != SCC_PAL) ? SCCF_ALLOW_ZOOM_MIN_2X_32BPP : SCCF_ALLOW_ZOOM_MIN_2X_PAL);
600 }
601 }
602 }
603 file.SkipBytes(length);
604 }
605 if (prev_id != 0) _grf_sprite_offsets[prev_id] = offset;
606
607 /* Continue processing the data section. */
608 file.SeekTo(old_pos, SEEK_SET);
609 }
610}
611
612
621 bool LoadNextSprite(SpriteID load_index, SpriteFile &file, uint file_sprite_id)
622{
623 size_t file_pos = file.GetPos();
624
625 /* Read sprite header. */
626 uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
627 if (num == 0) return false;
628 uint8_t grf_type = file.ReadByte();
629
630 SpriteType type;
631 void *data = nullptr;
632 uint8_t control_flags = 0;
633 if (grf_type == 0xFF) {
634 /* Some NewGRF files have "empty" pseudo-sprites which are 1
635 * byte long. Catch these so the sprites won't be displayed. */
636 if (num == 1) {
637 file.ReadByte();
638 return false;
639 }
640 file_pos = file.GetPos();
641 type = SpriteType::Recolour;
642 file.SkipBytes(num);
643 } else if (file.GetContainerVersion() >= 2 && grf_type == 0xFD) {
644 if (num != 4) {
645 /* Invalid sprite section include, ignore. */
646 file.SkipBytes(num);
647 return false;
648 }
649 /* It is not an error if no sprite with the provided ID is found in the sprite section. */
650 auto iter = _grf_sprite_offsets.find(file.ReadDword());
651 if (iter != _grf_sprite_offsets.end()) {
652 file_pos = iter->second.file_pos;
653 control_flags = iter->second.control_flags;
654 } else {
655 file_pos = SIZE_MAX;
656 }
657 type = SpriteType::Normal;
658 } else {
659 file.SkipBytes(7);
660 type = SkipSpriteData(file, grf_type, num - 8) ? SpriteType::Normal : SpriteType::Invalid;
661 /* Inline sprites are not supported for container version >= 2. */
662 if (file.GetContainerVersion() >= 2) return false;
663 }
664
665 if (type == SpriteType::Invalid) return false;
666
667 if (load_index >= MAX_SPRITES) {
668 UserError("Tried to load too many sprites (#{}; max {})", load_index, MAX_SPRITES);
669 }
670
671 bool is_mapgen = IsMapgenSpriteID(load_index);
672
673 if (is_mapgen) {
674 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?");
675 type = SpriteType::MapGen;
676 }
677
678 SpriteCache *sc = AllocateSpriteCache(load_index);
679 sc->file = &file;
680 sc->file_pos = file_pos;
681 sc->length = num;
682 sc->ptr = data;
683 sc->lru = 0;
684 sc->id = file_sprite_id;
685 sc->type = type;
686 sc->warned = false;
687 sc->control_flags = control_flags;
688
689 return true;
690}
691
692
693void DupSprite(SpriteID old_spr, SpriteID new_spr)
694{
695 SpriteCache *scnew = AllocateSpriteCache(new_spr); // may reallocate: so put it first
696 SpriteCache *scold = GetSpriteCache(old_spr);
697
698 scnew->file = scold->file;
699 scnew->file_pos = scold->file_pos;
700 scnew->ptr = nullptr;
701 scnew->id = scold->id;
702 scnew->type = scold->type;
703 scnew->warned = false;
704 scnew->control_flags = scold->control_flags;
705}
706
713 static const size_t S_FREE_MASK = sizeof(size_t) - 1;
714
715/* to make sure nobody adds things to MemBlock without checking S_FREE_MASK first */
716static_assert(sizeof(MemBlock) == sizeof(size_t));
717/* make sure it's a power of two */
718static_assert((sizeof(size_t) & (sizeof(size_t) - 1)) == 0);
719
720static inline MemBlock *NextBlock(MemBlock *block)
721{
722 return (MemBlock*)((uint8_t*)block + (block->size & ~S_FREE_MASK));
723}
724
725static size_t GetSpriteCacheUsage()
726{
727 size_t tot_size = 0;
728 MemBlock *s;
729
730 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
731 if (!(s->size & S_FREE_MASK)) tot_size += s->size;
732 }
733
734 return tot_size;
735}
736
737
738void IncreaseSpriteLRU()
739{
740 /* Increase all LRU values */
741 if (_sprite_lru_counter > 16384) {
742 SpriteID i;
743
744 Debug(sprite, 5, "Fixing lru {}, inuse={}", _sprite_lru_counter, GetSpriteCacheUsage());
745
746 for (i = 0; i != _spritecache_items; i++) {
747 SpriteCache *sc = GetSpriteCache(i);
748 if (sc->ptr != nullptr) {
749 if (sc->lru >= 0) {
750 sc->lru = -1;
751 } else if (sc->lru != -32768) {
752 sc->lru--;
753 }
754 }
755 }
756 _sprite_lru_counter = 0;
757 }
758
759 /* Compact sprite cache every now and then. */
760 if (++_compact_cache_counter >= 740) {
761 CompactSpriteCache();
762 _compact_cache_counter = 0;
763 }
764}
765
770 static void CompactSpriteCache()
771{
772 MemBlock *s;
773
774 Debug(sprite, 3, "Compacting sprite cache, inuse={}", GetSpriteCacheUsage());
775
776 for (s = _spritecache_ptr; s->size != 0;) {
777 if (s->size & S_FREE_MASK) {
778 MemBlock *next = NextBlock(s);
779 MemBlock temp;
780 SpriteID i;
781
782 /* Since free blocks are automatically coalesced, this should hold true. */
783 assert(!(next->size & S_FREE_MASK));
784
785 /* If the next block is the sentinel block, we can safely return */
786 if (next->size == 0) break;
787
788 /* Locate the sprite belonging to the next pointer. */
789 for (i = 0; GetSpriteCache(i)->ptr != next->data; i++) {
790 assert(i != _spritecache_items);
791 }
792
793 GetSpriteCache(i)->ptr = s->data; // Adjust sprite array entry
794 /* Swap this and the next block */
795 temp = *s;
796 memmove(s, next, next->size);
797 s = NextBlock(s);
798 *s = temp;
799
800 /* Coalesce free blocks */
801 while (NextBlock(s)->size & S_FREE_MASK) {
802 s->size += NextBlock(s)->size & ~S_FREE_MASK;
803 }
804 } else {
805 s = NextBlock(s);
806 }
807 }
808}
809
814 static void DeleteEntryFromSpriteCache(uint item)
815{
816 /* Mark the block as free (the block must be in use) */
817 MemBlock *s = (MemBlock*)GetSpriteCache(item)->ptr - 1;
818 assert(!(s->size & S_FREE_MASK));
819 s->size |= S_FREE_MASK;
820 GetSpriteCache(item)->ptr = nullptr;
821
822 /* And coalesce adjacent free blocks */
823 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
824 if (s->size & S_FREE_MASK) {
825 while (NextBlock(s)->size & S_FREE_MASK) {
826 s->size += NextBlock(s)->size & ~S_FREE_MASK;
827 }
828 }
829 }
830}
831
832static void DeleteEntryFromSpriteCache()
833{
834 uint best = UINT_MAX;
835 int cur_lru;
836
837 Debug(sprite, 3, "DeleteEntryFromSpriteCache, inuse={}", GetSpriteCacheUsage());
838
839 cur_lru = 0xffff;
840 for (SpriteID i = 0; i != _spritecache_items; i++) {
841 SpriteCache *sc = GetSpriteCache(i);
842 if (sc->ptr != nullptr && sc->lru < cur_lru) {
843 cur_lru = sc->lru;
844 best = i;
845 }
846 }
847
848 /* Display an error message and die, in case we found no sprite at all.
849 * This shouldn't really happen, unless all sprites are locked. */
850 if (best == UINT_MAX) FatalError("Out of sprite memory");
851
852 DeleteEntryFromSpriteCache(best);
853}
854
855 void *CacheSpriteAllocator::AllocatePtr(size_t mem_req)
856{
857 mem_req += sizeof(MemBlock);
858
859 /* Align this to correct boundary. This also makes sure at least one
860 * bit is not used, so we can use it for other things. */
861 mem_req = Align(mem_req, S_FREE_MASK + 1);
862
863 for (;;) {
864 MemBlock *s;
865
866 for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
867 if (s->size & S_FREE_MASK) {
868 size_t cur_size = s->size & ~S_FREE_MASK;
869
870 /* Is the block exactly the size we need or
871 * big enough for an additional free block? */
872 if (cur_size == mem_req ||
873 cur_size >= mem_req + sizeof(MemBlock)) {
874 /* Set size and in use */
875 s->size = mem_req;
876
877 /* Do we need to inject a free block too? */
878 if (cur_size != mem_req) {
879 NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
880 }
881
882 return s->data;
883 }
884 }
885 }
886
887 /* Reached sentinel, but no block found yet. Delete some old entry. */
888 DeleteEntryFromSpriteCache();
889 }
890}
891
895 void *SimpleSpriteAllocator::AllocatePtr(size_t size)
896{
897 return MallocT<uint8_t>(size);
898}
899
900 void *UniquePtrSpriteAllocator::AllocatePtr(size_t size)
901{
902 this->data = std::make_unique<uint8_t[]>(size);
903 return this->data.get();
904}
905
915 static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, SpriteAllocator *allocator)
916{
917 static const char * const 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) {
935 case SpriteType::Normal:
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);
940 case SpriteType::Recolour:
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);
943 case SpriteType::MapGen:
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
960 void *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 */
1003 int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
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(STR_CONFIG_ERROR_OUT_OF_MEMORY, STR_CONFIG_ERROR_SPRITECACHE_TOO_BIG);
1035 msg.SetDParam(0, target_size);
1036 msg.SetDParam(1, _allocated_sprite_cache_size);
1037 ScheduleErrorMessage(msg);
1038 }
1039 }
1040
1041 /* A big free block */
1042 _spritecache_ptr->size = (_allocated_sprite_cache_size - sizeof(MemBlock)) | S_FREE_MASK;
1043 /* Sentinel block (identified by size == 0) */
1044 NextBlock(_spritecache_ptr)->size = 0;
1045}
1046
1047void GfxInitSpriteMem()
1048{
1049 GfxInitSpriteCache();
1050
1051 /* Reset the spritecache 'pool' */
1052 free(_spritecache);
1053 _spritecache_items = 0;
1054 _spritecache = nullptr;
1055
1056 _compact_cache_counter = 0;
1057 _sprite_files.clear();
1058}
1059
1064 void GfxClearSpriteCache()
1065{
1066 /* Clear sprite ptr for all cached items */
1067 for (uint i = 0; i != _spritecache_items; i++) {
1068 SpriteCache *sc = GetSpriteCache(i);
1069 if (sc->ptr != nullptr) DeleteEntryFromSpriteCache(i);
1070 }
1071
1072 VideoDriver::GetInstance()->ClearSystemSprites();
1073}
1074
1079 void GfxClearFontSpriteCache()
1080{
1081 /* Clear sprite ptr for all cached font items */
1082 for (uint i = 0; i != _spritecache_items; i++) {
1083 SpriteCache *sc = GetSpriteCache(i);
1084 if (sc->type == SpriteType::Font && sc->ptr != nullptr) DeleteEntryFromSpriteCache(i);
1085 }
1086}
1087
1088/* static */ ReusableBuffer<SpriteLoader::CommonPixel> SpriteLoader::Sprite::buffer[ZOOM_LVL_END];
ReallocT
T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type.
Definition alloc_func.hpp:111
HasBit
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition bitmath_func.hpp:103
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition bitmath_func.hpp:121
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition bitmath_func.hpp:213
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:138
Blitter::GetScreenDepth
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
CacheSpriteAllocator
SpriteAllocator that allocates memory from the sprite cache.
Definition spritecache_internal.h:36
CacheSpriteAllocator::AllocatePtr
void * AllocatePtr(size_t size) override
Allocate memory for a sprite.
Definition spritecache.cpp:855
ErrorMessageData
The data of the error message.
Definition error.h:31
RandomAccessFile::ReadBlock
void ReadBlock(void *ptr, size_t size)
Read a block.
Definition random_access_file.cpp:145
RandomAccessFile::GetPos
size_t GetPos() const
Get position in the file.
Definition random_access_file.cpp:71
RandomAccessFile::SeekTo
void SeekTo(size_t pos, int mode)
Seek in the current file.
Definition random_access_file.cpp:90
RandomAccessFile::ReadByte
uint8_t ReadByte()
Read a byte from the file.
Definition random_access_file.cpp:107
RandomAccessFile::ReadDword
uint32_t ReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition random_access_file.cpp:134
RandomAccessFile::SkipBytes
void SkipBytes(size_t n)
Skip n bytes ahead in the file.
Definition random_access_file.cpp:163
RandomAccessFile::ReadWord
uint16_t ReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition random_access_file.cpp:124
ReusableBuffer
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition alloc_type.hpp:24
SimpleSpriteAllocator::AllocatePtr
void * AllocatePtr(size_t size) override
Sprite allocator simply using malloc.
Definition spritecache.cpp:895
SpriteAllocator
Interface for something that can allocate memory for a sprite.
Definition spriteloader.hpp:88
SpriteAllocator::Allocate
T * Allocate(size_t size)
Allocate memory for a sprite.
Definition spriteloader.hpp:99
SpriteEncoder
Interface for something that can encode a sprite.
Definition spriteloader.hpp:114
SpriteEncoder::Encode
virtual Sprite * Encode(const SpriteLoader::SpriteCollection &sprite, SpriteAllocator &allocator)=0
Convert a sprite from the loader to our own format.
SpriteEncoder::Is32BppSupported
virtual bool Is32BppSupported()=0
Can the sprite encoder make use of RGBA sprites?
SpriteEncoder::GetSpriteAlignment
virtual uint GetSpriteAlignment()
Get the value which the height and width on a sprite have to be aligned by.
Definition spriteloader.hpp:133
SpriteFile
RandomAccessFile with some extra information specific for sprite files.
Definition sprite_file_type.hpp:19
SpriteFile::NeedsPaletteRemap
bool NeedsPaletteRemap() const
Whether a palette remap is needed when loading sprites from this file.
Definition sprite_file_type.hpp:32
SpriteFile::GetContainerVersion
uint8_t GetContainerVersion() const
Get the version number of container type used by the file.
Definition sprite_file_type.hpp:38
SpriteFile::SeekToBegin
void SeekToBegin()
Seek to the begin of the content, i.e.
Definition sprite_file_type.hpp:43
SpriteLoaderGrf
Sprite loader for graphics coming from a (New)GRF.
Definition grf.hpp:16
SpriteLoaderGrf::LoadSprite
uint8_t LoadSprite(SpriteLoader::SpriteCollection &sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, bool load_32bpp, uint8_t control_flags) override
Load a sprite from the disk and return a sprite struct which is the same for all loaders.
Definition grf.cpp:353
SpriteLoader::SpriteCollection
std::array< Sprite, ZOOM_LVL_END > SpriteCollection
Type defining a collection of sprites, one for each zoom level.
Definition spriteloader.hpp:70
UniquePtrSpriteAllocator::AllocatePtr
void * AllocatePtr(size_t size) override
Allocate memory for a sprite.
Definition spritecache.cpp:900
VideoDriver::ClearSystemSprites
virtual void ClearSystemSprites()
Clear all cached sprites.
Definition video_driver.hpp:107
VideoDriver::GetInstance
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Definition video_driver.hpp:201
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition debug.h:37
error.h
Functions related to errors.
ScheduleErrorMessage
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
Definition error_gui.cpp:452
error_func.h
Error reporting related functions.
factory.hpp
Factory to 'query' all available blitters.
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:115
_font_zoom
ZoomLevel _font_zoom
Sprite font Zoom level (not clamped)
Definition gfx.cpp:62
gfx_func.h
Functions related to the gfx engine.
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:18
SpriteType
SpriteType
Types of sprites that might be loaded.
Definition gfx_type.h:312
SpriteType::Recolour
@ Recolour
Recolour sprite.
SpriteType::Font
@ Font
A sprite used for fonts.
SpriteType::MapGen
@ MapGen
Special sprite for the map generator.
SpriteType::Invalid
@ Invalid
Pseudosprite or other unusable sprite, used only internally.
SpriteType::Normal
@ Normal
The most basic (normal) sprite.
grf.hpp
Base for reading sprites from (New)GRFs.
math_func.hpp
Integer math functions.
Align
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
mem_func.hpp
Functions related to memory operations.
MemCpyT
void MemCpyT(T *destination, const T *source, size_t num=1)
Type-safe version of memcpy().
Definition mem_func.hpp:23
MemSetT
void MemSetT(T *ptr, uint8_t value, size_t num=1)
Type-safe version of memset().
Definition mem_func.hpp:49
palette_convert.h
Translation tables from one GRF to another GRF.
_palmap_d2w
static const uint8_t _palmap_d2w[]
Converting from the DOS palette to the Windows palette.
Definition palette_convert.h:47
random_access_file_type.h
Class related to random access to files.
safeguards.h
A number of safeguards to prevent using unsafe methods.
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:56
settings_type.h
Types related to global configuration settings.
DeleteEntryFromSpriteCache
static void DeleteEntryFromSpriteCache(uint item)
Delete a single entry from the sprite cache.
Definition spritecache.cpp:814
_grf_sprite_offsets
static std::map< uint32_t, GrfSpriteOffset > _grf_sprite_offsets
Map from sprite numbers to position in the GRF file.
Definition spritecache.cpp:549
GetSpriteType
SpriteType GetSpriteType(SpriteID sprite)
Get the sprite type of a given sprite.
Definition spritecache.cpp:159
GfxClearSpriteCache
void GfxClearSpriteCache()
Remove all encoded sprites from the sprite cache without discarding sprite location information.
Definition spritecache.cpp:1064
GetCachedSpriteFileByName
static SpriteFile * GetCachedSpriteFileByName(const std::string &filename)
Get the cached SpriteFile given the name of the file.
Definition spritecache.cpp:67
GetSpriteCountForFile
uint GetSpriteCountForFile(const std::string &filename, SpriteID begin, SpriteID end)
Count the sprites which originate from a specific file in a range of SpriteIDs.
Definition spritecache.cpp:194
ReadSprite
static void * ReadSprite(const SpriteCache *sc, SpriteID id, SpriteType sprite_type, SpriteAllocator &allocator, SpriteEncoder *encoder)
Read a sprite from disk.
Definition spritecache.cpp:464
GfxClearFontSpriteCache
void GfxClearFontSpriteCache()
Remove all encoded font sprites from the sprite cache without discarding sprite location information.
Definition spritecache.cpp:1079
OpenCachedSpriteFile
SpriteFile & OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
Open/get the SpriteFile that is cached for use in the sprite cache.
Definition spritecache.cpp:93
HandleInvalidSpriteRequest
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.
Definition spritecache.cpp:915
GetRawSprite
void * GetRawSprite(SpriteID sprite, SpriteType type, SpriteAllocator *allocator, SpriteEncoder *encoder)
Reads a sprite (from disk or sprite cache).
Definition spritecache.cpp:960
GetCachedSpriteFiles
std::span< const std::unique_ptr< SpriteFile > > GetCachedSpriteFiles()
Get the list of cached SpriteFiles.
Definition spritecache.cpp:81
LoadNextSprite
bool LoadNextSprite(SpriteID load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
Definition spritecache.cpp:621
GetMaxSpriteID
uint GetMaxSpriteID()
Get a reasonable (upper bound) estimate of the maximum SpriteID used in OpenTTD; there will be no spr...
Definition spritecache.cpp:220
GetOriginFile
SpriteFile * GetOriginFile(SpriteID sprite)
Get the SpriteFile of a given sprite.
Definition spritecache.cpp:170
GetGRFSpriteOffset
size_t GetGRFSpriteOffset(uint32_t id)
Get the file offset for a specific sprite in the sprite section of a GRF.
Definition spritecache.cpp:556
ReadRecolourSprite
static void * ReadRecolourSprite(SpriteFile &file, size_t file_pos, uint num, SpriteAllocator &allocator)
Load a recolour sprite into memory.
Definition spritecache.cpp:426
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, uint8_t type, uint16_t num)
Skip the given amount of sprite graphics data.
Definition spritecache.cpp:122
GetSpriteLocalID
uint32_t GetSpriteLocalID(SpriteID sprite)
Get the GRF-local sprite id of a given sprite.
Definition spritecache.cpp:181
CompactSpriteCache
static void CompactSpriteCache()
Called when holes in the sprite cache should be removed.
Definition spritecache.cpp:770
S_FREE_MASK
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,...
Definition spritecache.cpp:713
ReadGRFSpriteOffsets
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Definition spritecache.cpp:565
spritecache.h
Functions to cache sprites in memory.
SCCF_ALLOW_ZOOM_MIN_2X_32BPP
@ 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
@ 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
@ 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
@ SCCF_ALLOW_ZOOM_MIN_2X_PAL
Allow use of sprite min zoom setting at 2x in palette mode.
Definition spritecache.h:28
spritecache_internal.h
Internal functions to cache sprites in memory.
SCC_MASK
@ SCC_MASK
Mask of valid colour bits.
Definition spriteloader.hpp:25
SCC_PAL
@ SCC_PAL
Sprite has palette data.
Definition spriteloader.hpp:24
sprites.h
This file contains all sprite-related enums and defines.
MAX_SPRITES
static constexpr uint32_t MAX_SPRITES
Masks needed for sprite operations.
Definition sprites.h:1555
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
free
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition stdafx.h:334
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition settings_type.h:610
GUISettings::sprite_zoom_min
ZoomLevel sprite_zoom_min
maximum zoom level at which higher-resolution alternative sprites will be used (if available) instead...
Definition settings_type.h:167
GrfSpriteOffset
Definition spritecache.cpp:543
MemBlock
Definition spritecache.cpp:104
SpriteCache
Definition spritecache_internal.h:23
SpriteCache::control_flags
uint8_t control_flags
Control flags, see SpriteCacheCtrlFlags.
Definition spritecache_internal.h:32
SpriteCache::length
uint32_t length
Length of sprite data.
Definition spritecache_internal.h:27
SpriteCache::warned
bool warned
True iff the user has been warned about incorrect use of this sprite.
Definition spritecache_internal.h:31
SpriteCache::type
SpriteType type
In some cases a single sprite is misused by two NewGRFs. Once as real sprite and once as recolour spr...
Definition spritecache_internal.h:30
SpriteCache::file
SpriteFile * file
The file the sprite in this entry can be found in.
Definition spritecache_internal.h:26
SpriteLoader::CommonPixel
Definition of a common pixel in OpenTTD's realm.
Definition spriteloader.hpp:33
SpriteLoader::CommonPixel::m
uint8_t m
Remap-channel.
Definition spriteloader.hpp:38
SpriteLoader::Sprite
Structure for passing information from the sprite loader to the blitter.
Definition spriteloader.hpp:47
SpriteLoader::Sprite::buffer
static ReusableBuffer< SpriteLoader::CommonPixel > buffer[ZOOM_LVL_END]
Allocated memory to pass sprite data around.
Definition spriteloader.hpp:64
SpriteLoader::Sprite::AllocateData
void AllocateData(ZoomLevel zoom, size_t size)
Allocate the sprite data of this sprite.
Definition spriteloader.hpp:61
SpriteLoader::Sprite::width
uint16_t width
Width of the sprite.
Definition spriteloader.hpp:49
SpriteLoader::Sprite::x_offs
int16_t x_offs
The x-offset of where the sprite will be drawn.
Definition spriteloader.hpp:50
SpriteLoader::Sprite::data
SpriteLoader::CommonPixel * data
The sprite itself.
Definition spriteloader.hpp:54
SpriteLoader::Sprite::height
uint16_t height
Height of the sprite.
Definition spriteloader.hpp:48
SpriteLoader::Sprite::y_offs
int16_t y_offs
The y-offset of where the sprite will be drawn.
Definition spriteloader.hpp:51
Sprite
Data structure describing a sprite.
Definition spritecache.h:17
Sprite::width
uint16_t width
Width of the sprite.
Definition spritecache.h:19
Sprite::height
uint16_t height
Height of the sprite.
Definition spritecache.h:18
Sprite::y_offs
int16_t y_offs
Number of pixels to shift the sprite downwards.
Definition spritecache.h:21
Sprite::data
uint8_t data[]
Sprite data.
Definition spritecache.h:22
Sprite::x_offs
int16_t x_offs
Number of pixels to shift the sprite to the right.
Definition spritecache.h:20
video_driver.hpp
Base of all video drivers.
zoom_func.h
Functions related to zooming.
ScaleByZoom
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
UnScaleByZoom
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
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:16
ZOOM_LVL_NORMAL
@ ZOOM_LVL_NORMAL
The normal zoom level.
Definition zoom_type.h:21
ZOOM_LVL_BEGIN
@ ZOOM_LVL_BEGIN
Begin for iteration.
Definition zoom_type.h:18
ZOOM_LVL_IN_2X
@ ZOOM_LVL_IN_2X
Zoomed 2 times in.
Definition zoom_type.h:20
ZOOM_LVL_END
@ ZOOM_LVL_END
End for iteration.
Definition zoom_type.h:25
ZOOM_LVL_MIN
@ ZOOM_LVL_MIN
Minimum zoom level.
Definition zoom_type.h:41
ZOOM_LVL_IN_4X
@ ZOOM_LVL_IN_4X
Zoomed 4 times in.
Definition zoom_type.h:19