Crazy pointer arithmetic issues
More specifically, this:
- Code:
typedef struct //_TargaHeader
{
byte
id_length
, colormap_type
, image_type
;
unsigned short
colormap_index
, colormap_length
;
byte
colormap_size
;
unsigned short
x_origin
, y_origin
, width
, height
;
byte
pixel_size
, attributes
;
} TargaHeader;
void LoadTGA_as8bit (char *filename, byte **pic, int *width, int *height)
{
TargaHeader *filedata; //pcx_t *pcx;
byte *input, *output; //*out,
int row, column; //int x, y;
int columns, rows, numPixels; //int dataByte, runLength;
byte *pixbuf; //byte *pix;
loadedfile_t *fileinfo;
*pic = NULL;
fileinfo = COM_LoadTempFile (filename);
if (!fileinfo)
return;
// parse the file
filedata = (TargaHeader *) fileinfo->data;
if (filedata->image_type != 2 && filedata->image_type != 10)
Sys_Error ("LoadTGA: Only type 2 and 10 targa RGB images supported\n");
if (filedata->colormap_type != 0)
Sys_Error ("LoadTGA: No colormaps supported\non \"%s\"\n", filename);
if (filedata->pixel_size != 32)
if (filedata->pixel_size != 24)
Sys_Error ("LoadTGA: Only 32 or 24 bit images supported\non \"%s\",\n%i not supported", filename, (int) (filedata->pixel_size));
columns = LittleShort (filedata->width );
rows = LittleShort (filedata->height );
numPixels = columns * rows;
*pic = output = malloc (numPixels);
input = (byte *) filedata + sizeof (TargaHeader) + filedata->id_length; // skip TARGA image comment
if (filedata->image_type == 2) // Uncompressed, RGB images
{
for(row = rows - 1 ; row >= 0 ; row--)
{
pixbuf = output + row * columns;
for (column = 0 ; column < columns ; column++)
{
byte
red
, green
, blue
, alphabyte
;
switch (filedata->pixel_size)
{
case 24:
blue = input[ (rows - row) * columns + 0];
green = input[ (rows - row) * columns + 1];
red = input[ (rows - row) * columns + 2];
*pixbuf++ = BestColor (red, green, blue, 0, 254);
break;
case 32:
blue = input[ (rows - row) * columns + 0];
green = input[ (rows - row) * columns + 1];
red = input[ (rows - row) * columns + 2];
alphabyte = input[ (rows - row) * columns + 3];
*pixbuf++ = (alphabyte == 255) ? 255 : BestColor (red, green, blue, 0, 254);
break;
}
input += (filedata->pixel_size / 8);
}
}
}
}
I've just checked the TargaHeader struct and it's fine, it passes the image_type test with no problems, but when checking for the pixel_size it goes nuts, apparently reading two, five or eight bytes ahead, and returning 49 instead of 24.
These are the first 32 bytes of the TGA file:
This makes no sense for me, specially since the algorithm for loading PCX images is quite similar, and works just fine.
