OpenTTD
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 "../fileio_func.h"
13 #include "../debug.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 "grf.hpp"
21 
22 #include "../safeguards.h"
23 
24 extern const byte _palmap_w2d[];
25 
28  SCC_RGB = 1 << 0,
29  SCC_ALPHA = 1 << 1,
30  SCC_PAL = 1 << 2,
32 };
34 
35 
43 static bool WarnCorruptSprite(uint8 file_slot, size_t file_pos, int line)
44 {
45  static byte warning_level = 0;
46  if (warning_level == 0) {
47  SetDParamStr(0, FioGetFilename(file_slot));
48  ShowErrorMessage(STR_NEWGRF_ERROR_CORRUPT_SPRITE, INVALID_STRING_ID, WL_ERROR);
49  }
50  DEBUG(sprite, warning_level, "[%i] Loading corrupted sprite from %s at position %i", line, FioGetFilename(file_slot), (int)file_pos);
51  warning_level = 6;
52  return false;
53 }
54 
68 bool DecodeSingleSprite(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t file_pos, SpriteType sprite_type, int64 num, byte type, ZoomLevel zoom_lvl, byte colour_fmt, byte container_format)
69 {
70  std::unique_ptr<byte[]> dest_orig(new byte[num]);
71  byte *dest = dest_orig.get();
72  const int64 dest_size = num;
73 
74  /* Read the file, which has some kind of compression */
75  while (num > 0) {
76  int8 code = FioReadByte();
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_slot, file_pos, __LINE__);
83  for (; size > 0; size--) {
84  *dest = FioReadByte();
85  dest++;
86  }
87  } else {
88  /* Copy bytes from earlier in the sprite */
89  const uint data_offset = ((code & 7) << 8) | FioReadByte();
90  if (dest - data_offset < dest_orig.get()) return WarnCorruptSprite(file_slot, file_pos, __LINE__);
91  int size = -(code >> 3);
92  num -= size;
93  if (num < 0) return WarnCorruptSprite(file_slot, 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_slot, file_pos, __LINE__);
102 
103  sprite->AllocateData(zoom_lvl, sprite->width * sprite->height);
104 
105  /* Convert colour depth to pixel size. */
106  int bpp = 0;
107  if (colour_fmt & SCC_RGB) bpp += 3; // Has RGB data.
108  if (colour_fmt & SCC_ALPHA) bpp++; // Has alpha data.
109  if (colour_fmt & SCC_PAL) 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_slot, 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_slot, file_pos, __LINE__);
155  }
156 
157  for (int x = 0; x < length; x++) {
158  if (colour_fmt & SCC_RGB) {
159  data->r = *dest++;
160  data->g = *dest++;
161  data->b = *dest++;
162  }
163  data->a = (colour_fmt & SCC_ALPHA) ? *dest++ : 0xFF;
164  if (colour_fmt & SCC_PAL) {
165  switch (sprite_type) {
166  case ST_NORMAL: data->m = _palette_remap_grf[file_slot] ? _palmap_w2d[*dest] : *dest; break;
167  case ST_FONT: data->m = min(*dest, 2u); break;
168  default: data->m = *dest; break;
169  }
170  /* Magic blue. */
171  if (colour_fmt == SCC_PAL && *dest == 0) data->a = 0x00;
172  dest++;
173  }
174  data++;
175  }
176  } while (!last_item);
177  }
178  } else {
179  if (dest_size < sprite->width * sprite->height * bpp) {
180  return WarnCorruptSprite(file_slot, file_pos, __LINE__);
181  }
182 
183  if (dest_size > sprite->width * sprite->height * bpp) {
184  static byte warning_level = 0;
185  DEBUG(sprite, warning_level, "Ignoring " OTTD_PRINTF64 " unused extra bytes from the sprite from %s at position %i", dest_size - sprite->width * sprite->height * bpp, FioGetFilename(file_slot), (int)file_pos);
186  warning_level = 6;
187  }
188 
189  dest = dest_orig.get();
190 
191  for (int i = 0; i < sprite->width * sprite->height; i++) {
192  byte *pixel = &dest[i * bpp];
193 
194  if (colour_fmt & SCC_RGB) {
195  sprite->data[i].r = *pixel++;
196  sprite->data[i].g = *pixel++;
197  sprite->data[i].b = *pixel++;
198  }
199  sprite->data[i].a = (colour_fmt & SCC_ALPHA) ? *pixel++ : 0xFF;
200  if (colour_fmt & SCC_PAL) {
201  switch (sprite_type) {
202  case ST_NORMAL: sprite->data[i].m = _palette_remap_grf[file_slot] ? _palmap_w2d[*pixel] : *pixel; break;
203  case ST_FONT: sprite->data[i].m = min(*pixel, 2u); break;
204  default: sprite->data[i].m = *pixel; break;
205  }
206  /* Magic blue. */
207  if (colour_fmt == SCC_PAL && *pixel == 0) sprite->data[i].a = 0x00;
208  pixel++;
209  }
210  }
211  }
212 
213  return true;
214 }
215 
216 uint8 LoadSpriteV1(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t file_pos, SpriteType sprite_type, bool load_32bpp)
217 {
218  /* Check the requested colour depth. */
219  if (load_32bpp) return 0;
220 
221  /* Open the right file and go to the correct position */
222  FioSeekToFile(file_slot, file_pos);
223 
224  /* Read the size and type */
225  int num = FioReadWord();
226  byte type = FioReadByte();
227 
228  /* Type 0xFF indicates either a colourmap or some other non-sprite info; we do not handle them here */
229  if (type == 0xFF) return 0;
230 
231  ZoomLevel zoom_lvl = (sprite_type != ST_MAPGEN) ? ZOOM_LVL_OUT_4X : ZOOM_LVL_NORMAL;
232 
233  sprite[zoom_lvl].height = FioReadByte();
234  sprite[zoom_lvl].width = FioReadWord();
235  sprite[zoom_lvl].x_offs = FioReadWord();
236  sprite[zoom_lvl].y_offs = FioReadWord();
237 
238  if (sprite[zoom_lvl].width > INT16_MAX) {
239  WarnCorruptSprite(file_slot, file_pos, __LINE__);
240  return 0;
241  }
242 
243  /* 0x02 indicates it is a compressed sprite, so we can't rely on 'num' to be valid.
244  * In case it is uncompressed, the size is 'num' - 8 (header-size). */
245  num = (type & 0x02) ? sprite[zoom_lvl].width * sprite[zoom_lvl].height : num - 8;
246 
247  if (DecodeSingleSprite(&sprite[zoom_lvl], file_slot, file_pos, sprite_type, num, type, zoom_lvl, SCC_PAL, 1)) return 1 << zoom_lvl;
248 
249  return 0;
250 }
251 
252 uint8 LoadSpriteV2(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t file_pos, SpriteType sprite_type, bool load_32bpp)
253 {
255 
256  /* Is the sprite not present/stripped in the GRF? */
257  if (file_pos == SIZE_MAX) return 0;
258 
259  /* Open the right file and go to the correct position */
260  FioSeekToFile(file_slot, file_pos);
261 
262  uint32 id = FioReadDword();
263 
264  uint8 loaded_sprites = 0;
265  do {
266  int64 num = FioReadDword();
267  size_t start_pos = FioGetPos();
268  byte type = FioReadByte();
269 
270  /* Type 0xFF indicates either a colourmap or some other non-sprite info; we do not handle them here. */
271  if (type == 0xFF) return 0;
272 
273  byte colour = type & SCC_MASK;
274  byte zoom = FioReadByte();
275 
276  if (colour != 0 && (load_32bpp ? colour != SCC_PAL : colour == SCC_PAL) && (sprite_type != ST_MAPGEN ? zoom < lengthof(zoom_lvl_map) : zoom == 0)) {
277  ZoomLevel zoom_lvl = (sprite_type != ST_MAPGEN) ? zoom_lvl_map[zoom] : ZOOM_LVL_NORMAL;
278 
279  if (HasBit(loaded_sprites, zoom_lvl)) {
280  /* We already have this zoom level, skip sprite. */
281  DEBUG(sprite, 1, "Ignoring duplicate zoom level sprite %u from %s", id, FioGetFilename(file_slot));
282  FioSkipBytes(num - 2);
283  continue;
284  }
285 
286  sprite[zoom_lvl].height = FioReadWord();
287  sprite[zoom_lvl].width = FioReadWord();
288  sprite[zoom_lvl].x_offs = FioReadWord();
289  sprite[zoom_lvl].y_offs = FioReadWord();
290 
291  if (sprite[zoom_lvl].width > INT16_MAX || sprite[zoom_lvl].height > INT16_MAX) {
292  WarnCorruptSprite(file_slot, file_pos, __LINE__);
293  return 0;
294  }
295 
296  /* Mask out colour information. */
297  type = type & ~SCC_MASK;
298 
299  /* Convert colour depth to pixel size. */
300  int bpp = 0;
301  if (colour & SCC_RGB) bpp += 3; // Has RGB data.
302  if (colour & SCC_ALPHA) bpp++; // Has alpha data.
303  if (colour & SCC_PAL) bpp++; // Has palette data.
304 
305  /* For chunked encoding we store the decompressed size in the file,
306  * otherwise we can calculate it from the image dimensions. */
307  uint decomp_size = (type & 0x08) ? FioReadDword() : sprite[zoom_lvl].width * sprite[zoom_lvl].height * bpp;
308 
309  bool valid = DecodeSingleSprite(&sprite[zoom_lvl], file_slot, file_pos, sprite_type, decomp_size, type, zoom_lvl, colour, 2);
310  if (FioGetPos() != start_pos + num) {
311  WarnCorruptSprite(file_slot, file_pos, __LINE__);
312  return 0;
313  }
314 
315  if (valid) SetBit(loaded_sprites, zoom_lvl);
316  } else {
317  /* Not the wanted zoom level or colour depth, continue searching. */
318  FioSkipBytes(num - 2);
319  }
320 
321  } while (FioReadDword() == id);
322 
323  return loaded_sprites;
324 }
325 
326 uint8 SpriteLoaderGrf::LoadSprite(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t file_pos, SpriteType sprite_type, bool load_32bpp)
327 {
328  if (this->container_ver >= 2) {
329  return LoadSpriteV2(sprite, file_slot, file_pos, sprite_type, load_32bpp);
330  } else {
331  return LoadSpriteV1(sprite, file_slot, file_pos, sprite_type, load_32bpp);
332  }
333 }
DECLARE_ENUM_AS_BIT_SET(GenderEthnicity) enum CompanyManagerFaceVariable
Bitgroups of the CompanyManagerFace variable.
uint8 a
Alpha-channel.
Zoomed 2 times out.
Definition: zoom_type.h:23
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
uint16 FioReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: fileio.cpp:164
Zoomed 16 times out.
Definition: zoom_type.h:26
uint8 LoadSprite(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t file_pos, SpriteType sprite_type, bool load_32bpp)
Load a sprite from the disk and return a sprite struct which is the same for all loaders.
Definition: grf.cpp:326
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:380
void AllocateData(ZoomLevel zoom, size_t size)
Allocate the sprite data of this sprite.
const char * FioGetFilename(uint8 slot)
Get the filename associated with a slot.
Definition: fileio.cpp:76
const byte _palmap_w2d[]
Converting from the Windows palette to the DOS palette.
Mask of valid colour bits.
Definition: grf.cpp:31
byte FioReadByte()
Read a byte from the file.
Definition: fileio.cpp:131
Definition of a common pixel in OpenTTD&#39;s realm.
Base for reading sprites from (New)GRFs.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:279
uint8 b
Blue-channel.
uint8 valid
Bits indicating what variable is valid (for each bit, 0 is invalid, 1 is valid).
Special sprite for the map generator.
Definition: gfx_type.h:298
A sprite used for fonts.
Definition: gfx_type.h:299
Zoomed 8 times out.
Definition: zoom_type.h:25
int16 x_offs
The x-offset of where the sprite will be drawn.
void FioSeekToFile(uint8 slot, size_t pos)
Switch to a different file and seek to a position.
Definition: fileio.cpp:113
SpriteLoader::CommonPixel * data
The sprite itself.
Structure for passing information from the sprite loader to the blitter.
bool _palette_remap_grf[]
Whether the given NewGRFs must get a palette remap from windows to DOS or not.
Definition: gfxinit.cpp:30
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:40
Sprite has palette data.
Definition: grf.cpp:30
SpriteType
Types of sprites that might be loaded.
Definition: gfx_type.h:296
The most basic (normal) sprite.
Definition: gfx_type.h:297
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
uint8 m
Remap-channel.
uint32 FioReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: fileio.cpp:174
uint16 width
Width of the sprite.
Sprite has RGB.
Definition: grf.cpp:28
Zoomed 32 times out.
Definition: zoom_type.h:27
void FioSkipBytes(int n)
Skip n bytes ahead in the file.
Definition: fileio.cpp:148
static bool WarnCorruptSprite(uint8 file_slot, size_t file_pos, int line)
We found a corrupted sprite.
Definition: grf.cpp:43
SpriteColourComponent
The different colour components a sprite can have.
Definition: grf.cpp:27
uint16 height
Height of the sprite.
The normal zoom level.
Definition: zoom_type.h:22
int16 y_offs
The y-offset of where the sprite will be drawn.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
uint8 r
Red-channel.
ZoomLevel
All zoom levels we know.
Definition: zoom_type.h:19
size_t FioGetPos()
Get position in the current file.
Definition: fileio.cpp:66
Sprite has alpha.
Definition: grf.cpp:29
Errors (eg. saving/loading failed)
Definition: error.h:23
Zoomed 4 times out.
Definition: zoom_type.h:24
uint8 g
Green-channel.
bool DecodeSingleSprite(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t file_pos, SpriteType sprite_type, int64 num, byte type, ZoomLevel zoom_lvl, byte colour_fmt, byte container_format)
Decode the image data of a single sprite.
Definition: grf.cpp:68