OpenTTD Source 20250312-master-gcdcc6b491d
grf.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 "../gfx_func.h"
12#include "../debug.h"
13#include "../settings_type.h"
14#include "../strings_func.h"
15#include "table/strings.h"
16#include "../error.h"
17#include "../core/math_func.hpp"
18#include "../core/alloc_type.hpp"
19#include "../core/bitmath_func.hpp"
20#include "../spritecache.h"
21#include "grf.hpp"
22
23#include "../safeguards.h"
24
25extern const uint8_t _palmap_w2d[];
26
35static bool WarnCorruptSprite(const SpriteFile &file, size_t file_pos, int line)
36{
37 static uint8_t warning_level = 0;
38 if (warning_level == 0) {
39 ShowErrorMessage(GetEncodedString(STR_NEWGRF_ERROR_CORRUPT_SPRITE, file.GetSimplifiedFilename()), {}, WL_ERROR);
40 }
41 Debug(sprite, warning_level, "[{}] Loading corrupted sprite from {} at position {}", line, file.GetSimplifiedFilename(), file_pos);
42 warning_level = 6;
43 return false;
44}
45
59bool DecodeSingleSprite(SpriteLoader::Sprite *sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, int64_t num, uint8_t type, ZoomLevel zoom_lvl, SpriteComponents colour_fmt, uint8_t container_format)
60{
61 /*
62 * Original sprite height was max 255 pixels, with 4x extra zoom => 1020 pixels.
63 * Original maximum width for sprites was 640 pixels, with 4x extra zoom => 2560 pixels.
64 * Now up to 5 bytes per pixel => 1020 * 2560 * 5 => ~ 12.5 MiB.
65 *
66 * So, any sprite data more than 64 MiB is way larger that we would even expect; prevent allocating more memory!
67 */
68 if (num < 0 || num > 64 * 1024 * 1024) return WarnCorruptSprite(file, file_pos, __LINE__);
69
70 std::unique_ptr<uint8_t[]> dest_orig = std::make_unique<uint8_t[]>(num);
71 uint8_t *dest = dest_orig.get();
72 const int64_t dest_size = num;
73
74 /* Read the file, which has some kind of compression */
75 while (num > 0) {
76 int8_t code = file.ReadByte();
77
78 if (code >= 0) {
79 /* Plain bytes to read */
80 int size = (code == 0) ? 0x80 : code;
81 num -= size;
82 if (num < 0) return WarnCorruptSprite(file, file_pos, __LINE__);
83 for (; size > 0; size--) {
84 *dest = file.ReadByte();
85 dest++;
86 }
87 } else {
88 /* Copy bytes from earlier in the sprite */
89 const uint data_offset = ((code & 7) << 8) | file.ReadByte();
90 if (dest - data_offset < dest_orig.get()) return WarnCorruptSprite(file, file_pos, __LINE__);
91 int size = -(code >> 3);
92 num -= size;
93 if (num < 0) return WarnCorruptSprite(file, file_pos, __LINE__);
94 for (; size > 0; size--) {
95 *dest = *(dest - data_offset);
96 dest++;
97 }
98 }
99 }
100
101 if (num != 0) return WarnCorruptSprite(file, file_pos, __LINE__);
102
103 sprite->AllocateData(zoom_lvl, static_cast<size_t>(sprite->width) * sprite->height);
104
105 /* Convert colour depth to pixel size. */
106 int bpp = 0;
107 if (colour_fmt.Test(SpriteComponent::RGB)) bpp += 3; // Has RGB data.
108 if (colour_fmt.Test(SpriteComponent::Alpha)) bpp++; // Has alpha data.
109 if (colour_fmt.Test(SpriteComponent::Palette)) bpp++; // Has palette data.
110
111 /* When there are transparency pixels, this format has another trick.. decode it */
112 if (type & 0x08) {
113 for (int y = 0; y < sprite->height; y++) {
114 bool last_item = false;
115 /* Look up in the header-table where the real data is stored for this row */
116 int offset;
117 if (container_format >= 2 && dest_size > UINT16_MAX) {
118 offset = (dest_orig[y * 4 + 3] << 24) | (dest_orig[y * 4 + 2] << 16) | (dest_orig[y * 4 + 1] << 8) | dest_orig[y * 4];
119 } else {
120 offset = (dest_orig[y * 2 + 1] << 8) | dest_orig[y * 2];
121 }
122
123 /* Go to that row */
124 dest = dest_orig.get() + offset;
125
126 do {
127 if (dest + (container_format >= 2 && sprite->width > 256 ? 4 : 2) > dest_orig.get() + dest_size) {
128 return WarnCorruptSprite(file, file_pos, __LINE__);
129 }
130
132 /* Read the header. */
133 int length, skip;
134 if (container_format >= 2 && sprite->width > 256) {
135 /* 0 .. 14 - length
136 * 15 - last_item
137 * 16 .. 31 - transparency bytes */
138 last_item = (dest[1] & 0x80) != 0;
139 length = ((dest[1] & 0x7F) << 8) | dest[0];
140 skip = (dest[3] << 8) | dest[2];
141 dest += 4;
142 } else {
143 /* 0 .. 6 - length
144 * 7 - last_item
145 * 8 .. 15 - transparency bytes */
146 last_item = ((*dest) & 0x80) != 0;
147 length = (*dest++) & 0x7F;
148 skip = *dest++;
149 }
150
151 data = &sprite->data[y * sprite->width + skip];
152
153 if (skip + length > sprite->width || dest + length * bpp > dest_orig.get() + dest_size) {
154 return WarnCorruptSprite(file, file_pos, __LINE__);
155 }
156
157 for (int x = 0; x < length; x++) {
158 if (colour_fmt.Test(SpriteComponent::RGB)) {
159 data->r = *dest++;
160 data->g = *dest++;
161 data->b = *dest++;
162 }
163 data->a = colour_fmt.Test(SpriteComponent::Alpha) ? *dest++ : 0xFF;
164 if (colour_fmt.Test(SpriteComponent::Palette)) {
165 switch (sprite_type) {
166 case SpriteType::Normal: data->m = file.NeedsPaletteRemap() ? _palmap_w2d[*dest] : *dest; break;
167 case SpriteType::Font: data->m = std::min<uint8_t>(*dest, 2u); break;
168 default: data->m = *dest; break;
169 }
170 /* Magic blue. */
171 if (colour_fmt == SpriteComponent::Palette && *dest == 0) data->a = 0x00;
172 dest++;
173 }
174 data++;
175 }
176 } while (!last_item);
177 }
178 } else {
179 int64_t sprite_size = static_cast<int64_t>(sprite->width) * sprite->height * bpp;
180 if (dest_size < sprite_size) {
181 return WarnCorruptSprite(file, file_pos, __LINE__);
182 }
183
184 if (dest_size > sprite_size) {
185 static uint8_t warning_level = 0;
186 Debug(sprite, warning_level, "Ignoring {} unused extra bytes from the sprite from {} at position {}", dest_size - sprite_size, file.GetSimplifiedFilename(), file_pos);
187 warning_level = 6;
188 }
189
190 dest = dest_orig.get();
191
192 for (int i = 0; i < sprite->width * sprite->height; i++) {
193 uint8_t *pixel = &dest[i * bpp];
194
195 if (colour_fmt.Test(SpriteComponent::RGB)) {
196 sprite->data[i].r = *pixel++;
197 sprite->data[i].g = *pixel++;
198 sprite->data[i].b = *pixel++;
199 }
200 sprite->data[i].a = colour_fmt.Test(SpriteComponent::Alpha) ? *pixel++ : 0xFF;
201 if (colour_fmt.Test(SpriteComponent::Palette)) {
202 switch (sprite_type) {
203 case SpriteType::Normal: sprite->data[i].m = file.NeedsPaletteRemap() ? _palmap_w2d[*pixel] : *pixel; break;
204 case SpriteType::Font: sprite->data[i].m = std::min<uint8_t>(*pixel, 2u); break;
205 default: sprite->data[i].m = *pixel; break;
206 }
207 /* Magic blue. */
208 if (colour_fmt == SpriteComponent::Palette && *pixel == 0) sprite->data[i].a = 0x00;
209 pixel++;
210 }
211 }
212 }
213
214 return true;
215}
216
217uint8_t LoadSpriteV1(SpriteLoader::SpriteCollection &sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, bool load_32bpp, uint8_t &avail_8bpp)
218{
219 /* Check the requested colour depth. */
220 if (load_32bpp) return 0;
221
222 /* Open the right file and go to the correct position */
223 file.SeekTo(file_pos, SEEK_SET);
224
225 /* Read the size and type */
226 int num = file.ReadWord();
227 uint8_t type = file.ReadByte();
228
229 /* Type 0xFF indicates either a colourmap or some other non-sprite info; we do not handle them here */
230 if (type == 0xFF) return 0;
231
232 ZoomLevel zoom_lvl = (sprite_type != SpriteType::MapGen) ? ZOOM_LVL_NORMAL : ZOOM_LVL_MIN;
233
234 sprite[zoom_lvl].height = file.ReadByte();
235 sprite[zoom_lvl].width = file.ReadWord();
236 sprite[zoom_lvl].x_offs = file.ReadWord();
237 sprite[zoom_lvl].y_offs = file.ReadWord();
238 sprite[zoom_lvl].colours = SpriteComponent::Palette;
239
240 if (sprite[zoom_lvl].width > INT16_MAX) {
241 WarnCorruptSprite(file, file_pos, __LINE__);
242 return 0;
243 }
244
245 /* 0x02 indicates it is a compressed sprite, so we can't rely on 'num' to be valid.
246 * In case it is uncompressed, the size is 'num' - 8 (header-size). */
247 num = (type & 0x02) ? sprite[zoom_lvl].width * sprite[zoom_lvl].height : num - 8;
248
249 if (DecodeSingleSprite(&sprite[zoom_lvl], file, file_pos, sprite_type, num, type, zoom_lvl, SpriteComponent::Palette, 1)) {
250 SetBit(avail_8bpp, zoom_lvl);
251 return avail_8bpp;
252 }
253
254 return 0;
255}
256
257uint8_t LoadSpriteV2(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)
258{
260
261 /* Is the sprite not present/stripped in the GRF? */
262 if (file_pos == SIZE_MAX) return 0;
263
264 /* Open the right file and go to the correct position */
265 file.SeekTo(file_pos, SEEK_SET);
266
267 uint32_t id = file.ReadDword();
268
269 uint8_t loaded_sprites = 0;
270 do {
271 int64_t num = file.ReadDword();
272 size_t start_pos = file.GetPos();
273 uint8_t type = file.ReadByte();
274
275 /* Type 0xFF indicates either a colourmap or some other non-sprite info; we do not handle them here. */
276 if (type == 0xFF) return 0;
277
278 SpriteComponents colour{type};
279 /* Mask out colour component information from type. */
280 type &= ~SpriteComponents::MASK;
281
282 uint8_t zoom = file.ReadByte();
283
284 bool is_wanted_colour_depth = (colour != SpriteComponents{} && (load_32bpp ? colour != SpriteComponent::Palette : colour == SpriteComponent::Palette));
285 bool is_wanted_zoom_lvl;
286
287 if (sprite_type != SpriteType::MapGen) {
288 if (zoom < lengthof(zoom_lvl_map)) {
289 if (colour == SpriteComponent::Palette) SetBit(avail_8bpp, zoom_lvl_map[zoom]);
290 if (colour != SpriteComponent::Palette) SetBit(avail_32bpp, zoom_lvl_map[zoom]);
291
292 is_wanted_zoom_lvl = true;
294 if (zoom_min >= ZOOM_LVL_IN_2X &&
295 HasBit(control_flags, load_32bpp ? SCCF_ALLOW_ZOOM_MIN_2X_32BPP : SCCF_ALLOW_ZOOM_MIN_2X_PAL) && zoom_lvl_map[zoom] < ZOOM_LVL_IN_2X) {
296 is_wanted_zoom_lvl = false;
297 }
298 if (zoom_min >= ZOOM_LVL_NORMAL &&
299 HasBit(control_flags, load_32bpp ? SCCF_ALLOW_ZOOM_MIN_1X_32BPP : SCCF_ALLOW_ZOOM_MIN_1X_PAL) && zoom_lvl_map[zoom] < ZOOM_LVL_NORMAL) {
300 is_wanted_zoom_lvl = false;
301 }
302 } else {
303 is_wanted_zoom_lvl = false;
304 }
305 } else {
306 is_wanted_zoom_lvl = (zoom == 0);
307 }
308
309 if (is_wanted_colour_depth && is_wanted_zoom_lvl) {
310 ZoomLevel zoom_lvl = (sprite_type != SpriteType::MapGen) ? zoom_lvl_map[zoom] : ZOOM_LVL_MIN;
311
312 if (HasBit(loaded_sprites, zoom_lvl)) {
313 /* We already have this zoom level, skip sprite. */
314 Debug(sprite, 1, "Ignoring duplicate zoom level sprite {} from {}", id, file.GetSimplifiedFilename());
315 file.SkipBytes(num - 2);
316 continue;
317 }
318
319 sprite[zoom_lvl].height = file.ReadWord();
320 sprite[zoom_lvl].width = file.ReadWord();
321 sprite[zoom_lvl].x_offs = file.ReadWord();
322 sprite[zoom_lvl].y_offs = file.ReadWord();
323
324 if (sprite[zoom_lvl].width > INT16_MAX || sprite[zoom_lvl].height > INT16_MAX) {
325 WarnCorruptSprite(file, file_pos, __LINE__);
326 return 0;
327 }
328
329 /* Convert colour components to pixel size. */
330 int bpp = 0;
331 if (colour.Test(SpriteComponent::RGB)) bpp += 3;
332 if (colour.Test(SpriteComponent::Alpha)) bpp++;
333 if (colour.Test(SpriteComponent::Palette)) bpp++;
334
335 sprite[zoom_lvl].colours = colour;
336
337 /* For chunked encoding we store the decompressed size in the file,
338 * otherwise we can calculate it from the image dimensions. */
339 uint decomp_size = (type & 0x08) ? file.ReadDword() : sprite[zoom_lvl].width * sprite[zoom_lvl].height * bpp;
340
341 bool valid = DecodeSingleSprite(&sprite[zoom_lvl], file, file_pos, sprite_type, decomp_size, type, zoom_lvl, colour, 2);
342 if (file.GetPos() != start_pos + num) {
343 WarnCorruptSprite(file, file_pos, __LINE__);
344 return 0;
345 }
346
347 if (valid) SetBit(loaded_sprites, zoom_lvl);
348 } else {
349 /* Not the wanted zoom level or colour depth, continue searching. */
350 file.SkipBytes(num - 2);
351 }
352
353 } while (file.ReadDword() == id);
354
355 return loaded_sprites;
356}
357
358uint8_t SpriteLoaderGrf::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)
359{
360 if (this->container_ver >= 2) {
361 return LoadSpriteV2(sprite, file, file_pos, sprite_type, load_32bpp, control_flags, avail_8bpp, avail_32bpp);
362 } else {
363 return LoadSpriteV1(sprite, file, file_pos, sprite_type, load_32bpp, avail_8bpp);
364 }
365}
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 bool Test(Tvalue_type value) const
Test if the value-th bit is set.
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.
const std::string & GetSimplifiedFilename() const
Get the simplified filename of the opened 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).
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 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
std::array< Sprite, ZOOM_LVL_END > SpriteCollection
Type defining a collection of sprites, one for each zoom level.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition error.h:26
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, const CommandCost &cc)
Display an error message in a window.
SpriteType
Types of sprites that might be loaded.
Definition gfx_type.h:344
@ Font
A sprite used for fonts.
@ MapGen
Special sprite for the map generator.
@ Normal
The most basic (normal) sprite.
static bool WarnCorruptSprite(const SpriteFile &file, size_t file_pos, int line)
We found a corrupted sprite.
Definition grf.cpp:35
bool DecodeSingleSprite(SpriteLoader::Sprite *sprite, SpriteFile &file, size_t file_pos, SpriteType sprite_type, int64_t num, uint8_t type, ZoomLevel zoom_lvl, SpriteComponents colour_fmt, uint8_t container_format)
Decode the image data of a single sprite.
Definition grf.cpp:59
Base for reading sprites from (New)GRFs.
uint8_t valid
Bits indicating what variable is valid (for each bit, 0 is invalid, 1 is valid).
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:57
@ 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
@ Palette
Sprite has palette data.
@ Alpha
Sprite has alpha.
@ RGB
Sprite has RGB.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:277
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
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...
Definition of a common pixel in OpenTTD's realm.
uint8_t m
Remap-channel.
uint8_t b
Blue-channel.
uint8_t r
Red-channel.
uint8_t g
Green-channel.
uint8_t a
Alpha-channel.
Structure for passing information from the sprite loader to the blitter.
void AllocateData(ZoomLevel zoom, size_t size)
Allocate the sprite data of this sprite.
uint16_t width
Width of the sprite.
SpriteLoader::CommonPixel * data
The sprite itself.
uint16_t height
Height of the sprite.
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_OUT_4X
Zoomed 4 times out.
Definition zoom_type.h:23
@ ZOOM_LVL_OUT_2X
Zoomed 2 times out.
Definition zoom_type.h:22
@ ZOOM_LVL_OUT_8X
Zoomed 8 times out.
Definition zoom_type.h:24
@ ZOOM_LVL_IN_2X
Zoomed 2 times in.
Definition zoom_type.h:20
@ ZOOM_LVL_MIN
Minimum zoom level.
Definition zoom_type.h:41
@ ZOOM_LVL_IN_4X
Zoomed 4 times in.
Definition zoom_type.h:19