tga.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. #pragma once
  2. // interface for TrueVision (TGA) image file loader
  3. //
  4. ////////////////////////////////////////////////////////////////////////////////
  5. //
  6. // WARNING
  7. //
  8. // THIS DOES NOT DEAL WITH VERTICALLY FLIPPED DATA CORRECTLY
  9. //
  10. ////////////////////////////////////////////////////////////////////////////////
  11. /* This file is derived from (actually an earlier version of)... */
  12. /* The GIMP -- an image manipulation program
  13. * Copyright (C) 1995 Spencer Kimball and Peter Mattis
  14. *
  15. * $Id: tga.cpp,v 1.1.2.5 2007-05-10 02:10:07 elif Exp $
  16. * TrueVision Targa loading and saving file filter for the Gimp.
  17. * Targa code Copyright (C) 1997 Raphael FRANCOIS and Gordon Matzigkeit
  18. *
  19. * The Targa reading and writing code was written from scratch by
  20. * Raphael FRANCOIS <fraph@ibm.net> and Gordon Matzigkeit
  21. * <gord@gnu.ai.mit.edu> based on the TrueVision TGA File Format
  22. * Specification, Version 2.0:
  23. *
  24. * <URL:ftp://ftp.truevision.com/pub/TGA.File.Format.Spec/>
  25. *
  26. * It does not contain any code written for other TGA file loaders.
  27. * Not even the RLE handling. ;)
  28. *
  29. * This program is free software; you can redistribute it and/or modify
  30. * it under the terms of the GNU General Public License as published by
  31. * the Free Software Foundation; either version 2 of the License, or
  32. * (at your option) any later version.
  33. *
  34. * This program is distributed in the hope that it will be useful,
  35. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  36. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  37. * GNU General Public License for more details.
  38. *
  39. * You should have received a copy of the GNU General Public License
  40. * along with this program; if not, write to the Free Software
  41. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  42. */
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include <assert.h>
  47. #include <iostream>
  48. #if defined(_WIN32) || defined(_WIN64)
  49. #include <windows.h>
  50. #endif
  51. #if defined(__APPLE__) || defined(__MACH__)
  52. #include <OpenGL/gl.h>
  53. #include <GLUT/glut.h>
  54. #else
  55. #include <GL/gl.h>
  56. #include <GL/glut.h>
  57. #endif
  58. // wrap everything in a namespace and expose read_tga function and Image type only
  59. namespace igl{
  60. ////////////////////////////////////////////////////////////////////
  61. // declaration
  62. typedef struct {
  63. GLsizei width;
  64. GLsizei height;
  65. GLint components;
  66. GLenum format;
  67. GLsizei cmapEntries;
  68. GLenum cmapFormat;
  69. GLubyte *cmap;
  70. GLubyte *pixels;
  71. } gliGenericImage;
  72. typedef struct {
  73. unsigned char idLength;
  74. unsigned char colorMapType;
  75. /* The image type. */
  76. #define TGA_TYPE_MAPPED 1
  77. #define TGA_TYPE_COLOR 2
  78. #define TGA_TYPE_GRAY 3
  79. #define TGA_TYPE_MAPPED_RLE 9
  80. #define TGA_TYPE_COLOR_RLE 10
  81. #define TGA_TYPE_GRAY_RLE 11
  82. unsigned char imageType;
  83. /* Color Map Specification. */
  84. /* We need to separately specify high and low bytes to avoid endianness
  85. and alignment problems. */
  86. unsigned char colorMapIndexLo, colorMapIndexHi;
  87. unsigned char colorMapLengthLo, colorMapLengthHi;
  88. unsigned char colorMapSize;
  89. /* Image Specification. */
  90. unsigned char xOriginLo, xOriginHi;
  91. unsigned char yOriginLo, yOriginHi;
  92. unsigned char widthLo, widthHi;
  93. unsigned char heightLo, heightHi;
  94. unsigned char bpp;
  95. /* Image descriptor.
  96. 3-0: attribute bpp
  97. 4: left-to-right ordering
  98. 5: top-to-bottom ordering
  99. 7-6: zero
  100. */
  101. #define TGA_DESC_ABITS 0x0f
  102. #define TGA_DESC_HORIZONTAL 0x10
  103. #define TGA_DESC_VERTICAL 0x20
  104. unsigned char descriptor;
  105. } TgaHeader;
  106. typedef struct {
  107. unsigned int extensionAreaOffset;
  108. unsigned int developerDirectoryOffset;
  109. #define TGA_SIGNATURE "TRUEVISION-XFILE"
  110. char signature[16];
  111. char dot;
  112. char null;
  113. } TgaFooter;
  114. //////////////////////////////////////////////////////////////////////////////////////////
  115. // implementation
  116. static char error[256];
  117. static unsigned int _verbose = 0;
  118. static int totbytes = 0;
  119. typedef struct {
  120. unsigned char *statebuf;
  121. int statelen;
  122. int laststate;
  123. } RLEstate;
  124. static int
  125. std_fread(RLEstate *rleInfo, unsigned char *buf, size_t datasize, size_t nelems, FILE *fp)
  126. {
  127. if (_verbose > 1) {
  128. totbytes += nelems * datasize;
  129. printf("TGA: std_fread %d (total %d)\n",
  130. (int)(nelems * datasize), totbytes);
  131. }
  132. return fread(buf, datasize, nelems, fp);
  133. }
  134. #define MIN(a,b) (((a) < (b)) ? (a) : (b))
  135. #define RLE_PACKETSIZE 0x80
  136. /* Decode a bufferful of file. */
  137. static int
  138. rle_fread(RLEstate *rleInfo, unsigned char *vbuf, size_t datasize, size_t nelems, FILE *fp)
  139. {
  140. unsigned char *buf = vbuf;
  141. int j, k;
  142. int buflen, count, bytes, curbytes;
  143. unsigned char *p;
  144. /* Scale the buffer length. */
  145. buflen = nelems * datasize;
  146. j = 0;
  147. curbytes = totbytes;
  148. while (j < buflen) {
  149. if (rleInfo->laststate < rleInfo->statelen) {
  150. /* Copy bytes from our previously decoded buffer. */
  151. bytes = MIN(buflen - j, rleInfo->statelen - rleInfo->laststate);
  152. memcpy(buf + j, rleInfo->statebuf + rleInfo->laststate, bytes);
  153. j += bytes;
  154. rleInfo->laststate += bytes;
  155. /* If we used up all of our state bytes, then reset them. */
  156. if (rleInfo->laststate >= rleInfo->statelen) {
  157. rleInfo->laststate = 0;
  158. rleInfo->statelen = 0;
  159. }
  160. /* If we filled the buffer, then exit the loop. */
  161. if (j >= buflen) break;
  162. }
  163. /* Decode the next packet. */
  164. count = fgetc(fp);
  165. if (count == EOF) {
  166. if (_verbose) printf("TGA: hit EOF while looking for count\n");
  167. return j / datasize;
  168. }
  169. /* Scale the byte length to the size of the data. */
  170. bytes = ((count & ~RLE_PACKETSIZE) + 1) * datasize;
  171. if (j + bytes <= buflen) {
  172. /* We can copy directly into the image buffer. */
  173. p = buf + j;
  174. } else {
  175. #ifdef PROFILE
  176. printf("TGA: needed to use statebuf for %d bytes\n", buflen - j);
  177. #endif
  178. /* Allocate the state buffer if we haven't already. */
  179. if (!rleInfo->statebuf) {
  180. rleInfo->statebuf = (unsigned char *) malloc(RLE_PACKETSIZE * datasize);
  181. }
  182. p = rleInfo->statebuf;
  183. }
  184. if (count & RLE_PACKETSIZE) {
  185. /* Fill the buffer with the next value. */
  186. if (fread(p, datasize, 1, fp) != 1) {
  187. if (_verbose) {
  188. printf("TGA: EOF while reading %d/%d element RLE packet\n",
  189. bytes, (int)datasize);
  190. }
  191. return j / datasize;
  192. }
  193. /* Optimized case for single-byte encoded data. */
  194. if (datasize == 1) {
  195. memset(p + 1, *p, bytes - 1);
  196. } else {
  197. for (k = datasize; k < bytes; k += datasize) {
  198. memcpy(p + k, p, datasize);
  199. }
  200. }
  201. } else {
  202. /* Read in the buffer. */
  203. if (fread(p, bytes, 1, fp) != 1) {
  204. if (_verbose) {
  205. printf("TGA: EOF while reading %d/%d element raw packet\n",
  206. bytes, (int)datasize);
  207. }
  208. return j / datasize;
  209. }
  210. }
  211. if (_verbose > 1) {
  212. totbytes += bytes;
  213. if (_verbose > 2) {
  214. printf("TGA: %s packet %d/%d\n",
  215. (count & RLE_PACKETSIZE) ? "RLE" : "raw",
  216. bytes, totbytes);
  217. }
  218. }
  219. /* We may need to copy bytes from the state buffer. */
  220. if (p == rleInfo->statebuf) {
  221. rleInfo->statelen = bytes;
  222. } else {
  223. j += bytes;
  224. }
  225. }
  226. if (_verbose > 1) {
  227. printf("TGA: rle_fread %d/%d (total %d)\n",
  228. (int) ( nelems * datasize), totbytes - curbytes, totbytes);
  229. }
  230. return nelems;
  231. }
  232. static gliGenericImage *
  233. gliReadTGA(FILE *fp, const char *name, int hflip, int vflip)
  234. {
  235. TgaHeader tgaHeader;
  236. TgaFooter tgaFooter;
  237. char horzrev, vertrev;
  238. int width, height, bpp;
  239. int start, end, dir;
  240. int i, j, k;
  241. int pelbytes, wbytes;
  242. GLenum format;
  243. int components;
  244. RLEstate rleRec;
  245. RLEstate *rleInfo;
  246. int rle;
  247. int index, colors, length;
  248. GLubyte *cmap, *pixels, *data;
  249. int (*myfread)(RLEstate *rleInfo, unsigned char*, size_t, size_t, FILE*);
  250. gliGenericImage *genericImage;
  251. /* Check the footer. */
  252. if (fseek(fp, 0L - sizeof(tgaFooter), SEEK_END)
  253. || fread(&tgaFooter, sizeof(tgaFooter), 1, fp) != 1) {
  254. sprintf(error, "TGA: Cannot read footer from \"%s\"", name);
  255. if (_verbose) printf("%s\n", error);
  256. return NULL;
  257. }
  258. /* Check the signature. */
  259. if (memcmp(tgaFooter.signature, TGA_SIGNATURE,
  260. sizeof(tgaFooter.signature)) == 0) {
  261. if (_verbose) printf("TGA: found New TGA\n");
  262. } else {
  263. if (_verbose) printf("TGA: found Original TGA\n");
  264. }
  265. if (fseek(fp, 0, SEEK_SET) ||
  266. fread(&tgaHeader, sizeof(tgaHeader), 1, fp) != 1) {
  267. sprintf(error, "TGA: Cannot read header from \"%s\"", name);
  268. if (_verbose) printf("%s\n", error);
  269. return NULL;
  270. }
  271. if (_verbose && tgaHeader.idLength) {
  272. char *idString = (char*) malloc(tgaHeader.idLength);
  273. if (fread(idString, tgaHeader.idLength, 1, fp) != 1) {
  274. sprintf(error, "TGA: Cannot read ID field in \"%s\"", name);
  275. printf("%s\n", error);
  276. } else {
  277. printf("TGA: ID field: \"%*s\"\n", tgaHeader.idLength, idString);
  278. }
  279. free(idString);
  280. } else {
  281. /* Skip the image ID field. */
  282. if (tgaHeader.idLength && fseek(fp, tgaHeader.idLength, SEEK_CUR)) {
  283. sprintf(error, "TGA: Cannot skip ID field in \"%s\"", name);
  284. if (_verbose) printf("%s\n", error);
  285. return NULL;
  286. }
  287. }
  288. /* Reassemble the multi-byte values correctly, regardless of
  289. host endianness. */
  290. width = (tgaHeader.widthHi << 8) | tgaHeader.widthLo;
  291. height = (tgaHeader.heightHi << 8) | tgaHeader.heightLo;
  292. bpp = tgaHeader.bpp;
  293. if (_verbose) {
  294. printf("TGA: width=%d, height=%d, bpp=%d\n", width, height, bpp);
  295. }
  296. horzrev = tgaHeader.descriptor & TGA_DESC_HORIZONTAL;
  297. vertrev = tgaHeader.descriptor & TGA_DESC_VERTICAL;
  298. //vertrev=0;
  299. // // JASON - we can force this stuff if we want
  300. // if( hflip )
  301. // horzrev = 1;
  302. if( vflip )
  303. vertrev = 1;
  304. if (_verbose && horzrev) printf("TGA: horizontal reversed\n");
  305. if (_verbose && vertrev) printf("TGA: vertical reversed\n");
  306. rle = 0;
  307. switch (tgaHeader.imageType) {
  308. case TGA_TYPE_MAPPED_RLE:
  309. rle = 1;
  310. if (_verbose) printf("TGA: run-length encoded\n");
  311. case TGA_TYPE_MAPPED:
  312. /* Test for alpha channel. */
  313. format = GL_COLOR_INDEX;
  314. components = 1;
  315. if (_verbose) {
  316. printf("TGA: %d bit indexed image (%d bit palette)\n",
  317. tgaHeader.colorMapSize, bpp);
  318. }
  319. break;
  320. case TGA_TYPE_GRAY_RLE:
  321. rle = 1;
  322. if (_verbose) printf("TGA: run-length encoded\n");
  323. case TGA_TYPE_GRAY:
  324. format = GL_LUMINANCE;
  325. components = 1;
  326. if (_verbose) printf("TGA: %d bit grayscale image\n", bpp);
  327. break;
  328. case TGA_TYPE_COLOR_RLE:
  329. rle = 1;
  330. if (_verbose) printf("TGA: run-length encoded\n");
  331. case TGA_TYPE_COLOR:
  332. /* Test for alpha channel. */
  333. if (bpp == 32) {
  334. format = GL_BGRA_EXT;
  335. components = 4;
  336. if (_verbose) {
  337. printf("TGA: %d bit color image with alpha channel\n", bpp);
  338. }
  339. } else {
  340. format = GL_BGR_EXT;
  341. components = 3;
  342. if (_verbose) printf("TGA: %d bit color image\n", bpp);
  343. }
  344. break;
  345. default:
  346. sprintf(error,
  347. "TGA: unrecognized image type %d\n", tgaHeader.imageType);
  348. if (_verbose) printf("%s\n", error);
  349. return NULL;
  350. }
  351. if ((format == GL_BGRA_EXT && bpp != 32) ||
  352. (format == GL_BGR_EXT && bpp != 24) ||
  353. ((format == GL_LUMINANCE || format == GL_COLOR_INDEX) && bpp != 8)) {
  354. /* FIXME: We haven't implemented bit-packed fields yet. */
  355. fprintf(stderr, "bpp %d, format %x\n", bpp, (unsigned int)format);
  356. sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
  357. if (_verbose) printf("%s\n", error);
  358. return NULL;
  359. }
  360. /* Check that we have a color map only when we need it. */
  361. if (format == GL_COLOR_INDEX) {
  362. if (tgaHeader.colorMapType != 1) {
  363. sprintf(error, "TGA: indexed image has invalid color map type %d\n",
  364. tgaHeader.colorMapType);
  365. if (_verbose) printf("%s\n", error);
  366. return NULL;
  367. }
  368. } else if (tgaHeader.colorMapType != 0) {
  369. sprintf(error, "TGA: non-indexed image has invalid color map type %d\n",
  370. tgaHeader.colorMapType);
  371. if (_verbose) printf("%s\n", error);
  372. return NULL;
  373. }
  374. if (tgaHeader.colorMapType == 1) {
  375. /* We need to read in the colormap. */
  376. index = (tgaHeader.colorMapIndexHi << 8) | tgaHeader.colorMapIndexLo;
  377. length = (tgaHeader.colorMapLengthHi << 8) | tgaHeader.colorMapLengthLo;
  378. if (_verbose) {
  379. printf("TGA: reading color map (%d + %d) * (%d / 8)\n",
  380. index, length, tgaHeader.colorMapSize);
  381. }
  382. if (length == 0) {
  383. sprintf(error, "TGA: invalid color map length %d", length);
  384. if (_verbose) printf("%s\n", error);
  385. return NULL;
  386. }
  387. if (tgaHeader.colorMapSize != 24) {
  388. /* We haven't implemented bit-packed fields yet. */
  389. sprintf(error, "TGA: channel sizes other than 8 bits are unimplemented");
  390. if (_verbose) printf("%s\n", error);
  391. return NULL;
  392. }
  393. pelbytes = tgaHeader.colorMapSize / 8;
  394. colors = length + index;
  395. cmap = (GLubyte*)malloc (colors * pelbytes);
  396. /* Zero the entries up to the beginning of the map. */
  397. memset(cmap, 0, index * pelbytes);
  398. /* Read in the rest of the colormap. */
  399. if (fread(cmap, pelbytes, length, fp) != (size_t) length) {
  400. sprintf(error, "TGA: error reading colormap (ftell == %ld)\n",
  401. ftell (fp));
  402. if (_verbose) printf("%s\n", error);
  403. return NULL;
  404. }
  405. if (pelbytes >= 3) {
  406. /* Rearrange the colors from BGR to RGB. */
  407. int tmp;
  408. for (j = index; j < length * pelbytes; j += pelbytes) {
  409. tmp = cmap[j];
  410. cmap[j] = cmap[j + 2];
  411. cmap[j + 2] = tmp;
  412. }
  413. }
  414. } else {
  415. colors = 0;
  416. cmap = NULL;
  417. }
  418. /* Allocate the data. */
  419. pelbytes = bpp / 8;
  420. pixels = (unsigned char *) malloc (width * height * pelbytes);
  421. if (rle) {
  422. rleRec.statebuf = 0;
  423. rleRec.statelen = 0;
  424. rleRec.laststate = 0;
  425. rleInfo = &rleRec;
  426. myfread = rle_fread;
  427. } else {
  428. rleInfo = NULL;
  429. myfread = std_fread;
  430. }
  431. wbytes = width * pelbytes;
  432. if (vertrev) {
  433. start = 0;
  434. end = height;
  435. dir = 1;
  436. } else {
  437. /* We need to reverse loading order of rows. */
  438. start = height-1;
  439. end = -1;
  440. dir = -1;
  441. }
  442. for (i = start; i != end; i += dir) {
  443. data = pixels + i*wbytes;
  444. /* Suck in the data one row at a time. */
  445. if (myfread(rleInfo, data, pelbytes, width, fp) != width) {
  446. /* Probably premature end of file. */
  447. if (_verbose) {
  448. printf ("TGA: error reading (ftell == %ld, width=%d)\n",
  449. ftell(fp), width);
  450. }
  451. return NULL;
  452. }
  453. if (horzrev) {
  454. /* We need to mirror row horizontally. */
  455. for (j = 0; j < width/2; j++) {
  456. GLubyte tmp;
  457. for (k = 0; k < pelbytes; k++) {
  458. tmp = data[j*pelbytes+k];
  459. data[j*pelbytes+k] = data[(width-j-1)*pelbytes+k];
  460. data[(width-j-1)*pelbytes+k] = tmp;
  461. }
  462. }
  463. }
  464. }
  465. if (rle) {
  466. free(rleInfo->statebuf);
  467. }
  468. if (fgetc (fp) != EOF) {
  469. if (_verbose) printf ("TGA: too much input data, ignoring extra...\n");
  470. }
  471. genericImage = (gliGenericImage*) malloc(sizeof(gliGenericImage));
  472. genericImage->width = width;
  473. genericImage->height = height;
  474. genericImage->format = format;
  475. genericImage->components = components;
  476. genericImage->cmapEntries = colors;
  477. genericImage->cmapFormat = GL_BGR_EXT; // XXX fix me
  478. genericImage->cmap = cmap;
  479. genericImage->pixels = pixels;
  480. return genericImage;
  481. }
  482. static int
  483. gli_verbose(int new_verbose)
  484. {
  485. _verbose = new_verbose;
  486. return _verbose;
  487. }
  488. // added 10/2005, Denis Zorin
  489. // a very simple TGA output, supporting
  490. // uncompressed luminance RGB and RGBA
  491. // G22.2270 students: this is C (no C++)
  492. // so this is not the style I would encourage
  493. // you to use; I used it for consistency
  494. // with the rest of the code in this file
  495. // fixed header values for the subset of TGA we use for writing
  496. static unsigned char TGAHeaderColor[12] =
  497. { 0,// 0 ID length = no id
  498. 0,// 1 color map type = no color map
  499. 2,// 2 image type = uncompressed true color
  500. 0, 0, 0, 0, 0,// color map spec = empty
  501. 0, 0, // x origin of image
  502. 0, 0 // y origin of image
  503. };
  504. static unsigned char TGAHeaderBW[12] =
  505. { 0,// 0 ID length = no id
  506. 0,// 1 color map type = no color map
  507. 3,// 3 image type = uncompressed black and white
  508. 0, 0, 0, 0, 0,// color map spec = empty
  509. 0, 0, // x origin of image
  510. 0, 0 // y origin of image
  511. };
  512. // this makes sure that
  513. // image size is written in correct format
  514. // and byte order (least first)
  515. static void write16bit(int n, FILE* fp) {
  516. unsigned char bytes[] = { n % 256, n / 256 };
  517. fwrite(bytes, 2, sizeof(unsigned char),fp);
  518. }
  519. static void writeTGA( gliGenericImage* image, FILE *fp) {
  520. assert(!image->cmap); // we do not deal with color map images
  521. if(image->components == 3 || image->components == 4)
  522. fwrite(TGAHeaderColor, 12, sizeof(unsigned char),fp);
  523. else {
  524. if(image->components == 1 )
  525. fwrite(TGAHeaderBW, 12, sizeof(unsigned char),fp);
  526. else { fprintf(stderr,"Supported component number: 1,3 or 4\n"); exit(1); }
  527. }
  528. write16bit(image->width,fp);
  529. write16bit(image->height,fp);
  530. switch (image->components ) {
  531. case 1:
  532. putc(8,fp);
  533. break;
  534. case 3:
  535. putc(24,fp);
  536. break;
  537. case 4:
  538. putc(32,fp);
  539. break;
  540. default: fprintf(stderr,"Supported component number: 1,3 or 4\n"); exit(1);
  541. };
  542. if(image-> components == 4)
  543. putc(0x04,fp); // bottom left image (0x00) + 8 bit alpha (0x4)
  544. else
  545. putc(0x00,fp);
  546. fwrite(image->pixels, image->height*image->width*image->components, sizeof(char),fp);
  547. }
  548. } // end of namespace