Back to index

tetex-bin  3.0
gd_gd2.c
Go to the documentation of this file.
00001 /*
00002    * gd_gd2.c
00003    *
00004    * Implements the I/O and support for the GD2 format.
00005    *
00006    * Changing the definition of GD2_DBG (below) will cause copious messages
00007    * to be displayed while it processes requests.
00008    *
00009    * Designed, Written & Copyright 1999, Philip Warner.
00010    *
00011  */
00012 
00013 #ifdef HAVE_CONFIG_H
00014 #include "config.h"
00015 #endif
00016 
00017 #include <stdio.h>
00018 /* 2.0.29: no more errno.h, makes windows happy */
00019 #include <math.h>
00020 #include <string.h>
00021 #include <stdlib.h>
00022 #include "gd.h"
00023 #include "gdhelpers.h"
00024 
00025 /* 2.03: gd2 is no longer mandatory */
00026 /* JCE - test after including gd.h so that HAVE_LIBZ can be set in
00027  * a config.h file included by gd.h */
00028 #ifdef HAVE_LIBZ
00029 #include <zlib.h>
00030 
00031 #define TRUE 1
00032 #define FALSE 0
00033 
00034 /* 2.11: not part of the API, as the save routine can figure it out
00035        from im->trueColor, and the load routine doesn't need to tell
00036        the end user the saved format. NOTE: adding 2 is assumed
00037        to result in the correct format value for truecolor! */
00038 #define GD2_FMT_TRUECOLOR_RAW 3
00039 #define GD2_FMT_TRUECOLOR_COMPRESSED 4
00040 
00041 #define gd2_compressed(fmt) (((fmt) == GD2_FMT_COMPRESSED) || \
00042        ((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
00043 
00044 #define gd2_truecolor(fmt) (((fmt) == GD2_FMT_TRUECOLOR_RAW) || \
00045        ((fmt) == GD2_FMT_TRUECOLOR_COMPRESSED))
00046 
00047 /* Use this for commenting out debug-print statements. */
00048 /* Just use the first '#define' to allow all the prints... */
00049 /*#define GD2_DBG(s) (s) */
00050 #define GD2_DBG(s)
00051 
00052 typedef struct
00053 {
00054   int offset;
00055   int size;
00056 }
00057 t_chunk_info;
00058 
00059 extern int _gdGetColors (gdIOCtx * in, gdImagePtr im, int gd2xFlag);
00060 extern void _gdPutColors (gdImagePtr im, gdIOCtx * out);
00061 
00062 /* */
00063 /* Read the extra info in the gd2 header. */
00064 /* */
00065 static int
00066 _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
00067               int *cs, int *vers, int *fmt, int *ncx, int *ncy,
00068               t_chunk_info ** chunkIdx)
00069 {
00070   int i;
00071   int ch;
00072   char id[5];
00073   t_chunk_info *cidx;
00074   int sidx;
00075   int nc;
00076 
00077   GD2_DBG (printf ("Reading gd2 header info\n"));
00078 
00079   for (i = 0; i < 4; i++)
00080     {
00081       ch = gdGetC (in);
00082       if (ch == EOF)
00083        {
00084          goto fail1;
00085        };
00086       id[i] = ch;
00087     };
00088   id[4] = 0;
00089 
00090   GD2_DBG (printf ("Got file code: %s\n", id));
00091 
00092   /* Equiv. of 'magick'.  */
00093   if (strcmp (id, GD2_ID) != 0)
00094     {
00095       GD2_DBG (printf ("Not a valid gd2 file\n"));
00096       goto fail1;
00097     };
00098 
00099   /* Version */
00100   if (gdGetWord (vers, in) != 1)
00101     {
00102       goto fail1;
00103     };
00104   GD2_DBG (printf ("Version: %d\n", *vers));
00105 
00106   if ((*vers != 1) && (*vers != 2))
00107     {
00108       GD2_DBG (printf ("Bad version: %d\n", *vers));
00109       goto fail1;
00110     };
00111 
00112   /* Image Size */
00113   if (!gdGetWord (sx, in))
00114     {
00115       GD2_DBG (printf ("Could not get x-size\n"));
00116       goto fail1;
00117     }
00118   if (!gdGetWord (sy, in))
00119     {
00120       GD2_DBG (printf ("Could not get y-size\n"));
00121       goto fail1;
00122     }
00123   GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
00124 
00125   /* Chunk Size (pixels, not bytes!) */
00126   if (gdGetWord (cs, in) != 1)
00127     {
00128       goto fail1;
00129     };
00130   GD2_DBG (printf ("ChunkSize: %d\n", *cs));
00131 
00132   if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX))
00133     {
00134       GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
00135       goto fail1;
00136     };
00137 
00138   /* Data Format */
00139   if (gdGetWord (fmt, in) != 1)
00140     {
00141       goto fail1;
00142     };
00143   GD2_DBG (printf ("Format: %d\n", *fmt));
00144 
00145   if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
00146       (*fmt != GD2_FMT_TRUECOLOR_RAW) &&
00147       (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED))
00148     {
00149       GD2_DBG (printf ("Bad data format: %d\n", *fmt));
00150       goto fail1;
00151     };
00152 
00153 
00154   /* # of chunks wide */
00155   if (gdGetWord (ncx, in) != 1)
00156     {
00157       goto fail1;
00158     };
00159   GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
00160 
00161   /* # of chunks high */
00162   if (gdGetWord (ncy, in) != 1)
00163     {
00164       goto fail1;
00165     };
00166   GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
00167 
00168   if (gd2_compressed (*fmt))
00169     {
00170       nc = (*ncx) * (*ncy);
00171       GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
00172       sidx = sizeof (t_chunk_info) * nc;
00173       cidx = gdCalloc (sidx, 1);
00174       for (i = 0; i < nc; i++)
00175        {
00176          if (gdGetInt (&cidx[i].offset, in) != 1)
00177            {
00178              goto fail1;
00179            };
00180          if (gdGetInt (&cidx[i].size, in) != 1)
00181            {
00182              goto fail1;
00183            };
00184        };
00185       *chunkIdx = cidx;
00186     };
00187 
00188   GD2_DBG (printf ("gd2 header complete\n"));
00189 
00190   return 1;
00191 
00192 fail1:
00193   return 0;
00194 }
00195 
00196 static gdImagePtr
00197 _gd2CreateFromFile (gdIOCtxPtr in, int *sx, int *sy,
00198                   int *cs, int *vers, int *fmt,
00199                   int *ncx, int *ncy, t_chunk_info ** cidx)
00200 {
00201   gdImagePtr im;
00202 
00203   if (_gd2GetHeader (in, sx, sy, cs, vers, fmt, ncx, ncy, cidx) != 1)
00204     {
00205       GD2_DBG (printf ("Bad GD2 header\n"));
00206       goto fail1;
00207     }
00208   if (gd2_truecolor (*fmt))
00209     {
00210       im = gdImageCreateTrueColor (*sx, *sy);
00211     }
00212   else
00213     {
00214       im = gdImageCreate (*sx, *sy);
00215     }
00216   if (im == NULL)
00217     {
00218       GD2_DBG (printf ("Could not create gdImage\n"));
00219       goto fail1;
00220     };
00221 
00222   if (!_gdGetColors (in, im, (*vers) == 2))
00223     {
00224       GD2_DBG (printf ("Could not read color palette\n"));
00225       goto fail2;
00226     }
00227   GD2_DBG (printf ("Image palette completed: %d colours\n", im->colorsTotal));
00228 
00229   return im;
00230 
00231 fail2:
00232   gdImageDestroy (im);
00233   return 0;
00234 
00235 fail1:
00236   return 0;
00237 
00238 }
00239 
00240 static int
00241 _gd2ReadChunk (int offset, char *compBuf, int compSize, char *chunkBuf,
00242               uLongf * chunkLen, gdIOCtx * in)
00243 {
00244   int zerr;
00245 
00246   if (gdTell (in) != offset)
00247     {
00248       GD2_DBG (printf ("Positioning in file to %d\n", offset));
00249       gdSeek (in, offset);
00250     }
00251   else
00252     {
00253       GD2_DBG (printf ("Already Positioned in file to %d\n", offset));
00254     };
00255 
00256   /* Read and uncompress an entire chunk. */
00257   GD2_DBG (printf ("Reading file\n"));
00258   if (gdGetBuf (compBuf, compSize, in) != compSize)
00259     {
00260       return FALSE;
00261     };
00262   GD2_DBG (printf
00263           ("Got %d bytes. Uncompressing into buffer of %d bytes\n", compSize,
00264            *chunkLen));
00265   zerr =
00266     uncompress ((unsigned char *) chunkBuf, chunkLen,
00267               (unsigned char *) compBuf, compSize);
00268   if (zerr != Z_OK)
00269     {
00270       GD2_DBG (printf ("Error %d from uncompress\n", zerr));
00271       return FALSE;
00272     };
00273   GD2_DBG (printf ("Got chunk\n"));
00274   return TRUE;
00275 }
00276 
00277 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2 (FILE * inFile)
00278 {
00279   gdIOCtx *in = gdNewFileCtx (inFile);
00280   gdImagePtr im;
00281 
00282   im = gdImageCreateFromGd2Ctx (in);
00283 
00284   in->gd_free (in);
00285 
00286   return im;
00287 }
00288 
00289 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ptr (int size, void *data)
00290 {
00291   gdImagePtr im;
00292   gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0);
00293   im = gdImageCreateFromGd2Ctx (in);
00294   in->gd_free (in);
00295   return im;
00296 }
00297 
00298 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
00299 {
00300   int sx, sy;
00301   int i;
00302   int ncx, ncy, nc, cs, cx, cy;
00303   int x, y, ylo, yhi, xlo, xhi;
00304   int vers, fmt;
00305   t_chunk_info *chunkIdx = NULL;   /* So we can gdFree it with impunity. */
00306   unsigned char *chunkBuf = NULL;  /* So we can gdFree it with impunity. */
00307   int chunkNum = 0;
00308   int chunkMax = 0;
00309   uLongf chunkLen;
00310   int chunkPos = 0;
00311   int compMax = 0;
00312   int bytesPerPixel;
00313   char *compBuf = NULL;            /* So we can gdFree it with impunity. */
00314 
00315   gdImagePtr im;
00316 
00317   /* Get the header */
00318   im =
00319     _gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
00320                      &chunkIdx);
00321 
00322   if (im == NULL)
00323     {
00324       return 0;
00325     };
00326   bytesPerPixel = im->trueColor ? 4 : 1;
00327   nc = ncx * ncy;
00328 
00329   if (gd2_compressed (fmt))
00330     {
00331       /* Find the maximum compressed chunk size. */
00332       compMax = 0;
00333       for (i = 0; (i < nc); i++)
00334        {
00335          if (chunkIdx[i].size > compMax)
00336            {
00337              compMax = chunkIdx[i].size;
00338            };
00339        };
00340       compMax++;
00341 
00342       /* Allocate buffers */
00343       chunkMax = cs * bytesPerPixel * cs;
00344       chunkBuf = gdCalloc (chunkMax, 1);
00345       compBuf = gdCalloc (compMax, 1);
00346       GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
00347     };
00348 
00349 /*      if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
00350 /*              goto fail2; */
00351 /*      }; */
00352 
00353   /* Read the data... */
00354   for (cy = 0; (cy < ncy); cy++)
00355     {
00356       for (cx = 0; (cx < ncx); cx++)
00357        {
00358 
00359          ylo = cy * cs;
00360          yhi = ylo + cs;
00361          if (yhi > im->sy)
00362            {
00363              yhi = im->sy;
00364            };
00365 
00366          GD2_DBG (printf
00367                  ("Processing Chunk %d (%d, %d), y from %d to %d\n",
00368                   chunkNum, cx, cy, ylo, yhi));
00369 
00370          if (gd2_compressed (fmt))
00371            {
00372 
00373              chunkLen = chunkMax;
00374 
00375              if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
00376                               compBuf,
00377                               chunkIdx[chunkNum].size,
00378                               (char *) chunkBuf, &chunkLen, in))
00379               {
00380                 GD2_DBG (printf ("Error reading comproessed chunk\n"));
00381                 goto fail2;
00382               };
00383 
00384              chunkPos = 0;
00385            };
00386 
00387          for (y = ylo; (y < yhi); y++)
00388            {
00389 
00390              xlo = cx * cs;
00391              xhi = xlo + cs;
00392              if (xhi > im->sx)
00393               {
00394                 xhi = im->sx;
00395               };
00396              /*GD2_DBG(printf("y=%d: ",y)); */
00397              if (!gd2_compressed (fmt))
00398               {
00399                 for (x = xlo; x < xhi; x++)
00400                   {
00401 
00402                     if (im->trueColor)
00403                      {
00404                        if (!gdGetInt (&im->tpixels[y][x], in))
00405                          {
00406                            /*printf("EOF while reading\n"); */
00407                            /*gdImageDestroy(im); */
00408                            /*return 0; */
00409                            im->tpixels[y][x] = 0;
00410                          }
00411                      }
00412                     else
00413                      {
00414                        int ch;
00415                        if (!gdGetByte (&ch, in))
00416                          {
00417                            /*printf("EOF while reading\n"); */
00418                            /*gdImageDestroy(im); */
00419                            /*return 0; */
00420                            ch = 0;
00421                          }
00422                        im->pixels[y][x] = ch;
00423                      }
00424                   }
00425               }
00426              else
00427               {
00428                 for (x = xlo; x < xhi; x++)
00429                   {
00430                     if (im->trueColor)
00431                      {
00432                        /* 2.0.1: work around a gcc bug by being verbose.
00433                           TBB */
00434                        int a = chunkBuf[chunkPos++] << 24;
00435                        int r = chunkBuf[chunkPos++] << 16;
00436                        int g = chunkBuf[chunkPos++] << 8;
00437                        int b = chunkBuf[chunkPos++];
00438                        /* 2.0.11: tpixels */
00439                        im->tpixels[y][x] = a + r + g + b;
00440                      }
00441                     else
00442                      {
00443                        im->pixels[y][x] = chunkBuf[chunkPos++];
00444                      }
00445                   };
00446               };
00447              /*GD2_DBG(printf("\n")); */
00448            };
00449          chunkNum++;
00450        };
00451     };
00452 
00453   GD2_DBG (printf ("Freeing memory\n"));
00454 
00455   gdFree (chunkBuf);
00456   gdFree (compBuf);
00457   gdFree (chunkIdx);
00458 
00459   GD2_DBG (printf ("Done\n"));
00460 
00461   return im;
00462 
00463 fail2:
00464   gdImageDestroy (im);
00465   gdFree (chunkBuf);
00466   gdFree (compBuf);
00467   gdFree (chunkIdx);
00468   return 0;
00469 
00470 }
00471 
00472 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Part (FILE * inFile, int srcx, int srcy, int w, int h)
00473 {
00474   gdImagePtr im;
00475   gdIOCtx *in = gdNewFileCtx (inFile);
00476 
00477   im = gdImageCreateFromGd2PartCtx (in, srcx, srcy, w, h);
00478 
00479   in->gd_free (in);
00480 
00481   return im;
00482 }
00483 
00484 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartPtr (int size, void *data, int srcx, int srcy, int w,
00485                           int h)
00486 {
00487   gdImagePtr im;
00488   gdIOCtx *in = gdNewDynamicCtxEx (size, data, 0);
00489   im = gdImageCreateFromGd2PartCtx (in, srcx, srcy, w, h);
00490   in->gd_free (in);
00491   return im;
00492 }
00493 
00494 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h)
00495 {
00496   int scx, scy, ecx, ecy, fsx, fsy;
00497   int nc, ncx, ncy, cs, cx, cy;
00498   int x, y, ylo, yhi, xlo, xhi;
00499   int dstart, dpos;
00500   int i;
00501   /* 2.0.12: unsigned is correct; fixes problems with color munging.
00502      Thanks to Steven Brown. */
00503   unsigned int ch;
00504   int vers, fmt;
00505   t_chunk_info *chunkIdx = NULL;
00506   unsigned char *chunkBuf = NULL;
00507   int chunkNum;
00508   int chunkMax = 0;
00509   uLongf chunkLen;
00510   int chunkPos = 0;
00511   int compMax;
00512   char *compBuf = NULL;
00513 
00514   gdImagePtr im;
00515 
00516   /* */
00517   /* The next few lines are basically copied from gd2CreateFromFile */
00518   /* - we change the file size, so don't want to use the code directly. */
00519   /*   but we do need to know the file size. */
00520   /* */
00521   if (_gd2GetHeader (in, &fsx, &fsy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx)
00522       != 1)
00523     {
00524       goto fail1;
00525     }
00526 
00527   GD2_DBG (printf ("File size is %dx%d\n", fsx, fsy));
00528 
00529   /* This is the difference - make a file based on size of chunks. */
00530   if (gd2_truecolor (fmt))
00531     {
00532       im = gdImageCreateTrueColor (w, h);
00533     }
00534   else
00535     {
00536       im = gdImageCreate (w, h);
00537     }
00538   if (im == NULL)
00539     {
00540       goto fail1;
00541     };
00542 
00543   if (!_gdGetColors (in, im, vers == 2))
00544     {
00545       goto fail2;
00546     }
00547   GD2_DBG (printf ("Image palette completed: %d colours\n", im->colorsTotal));
00548 
00549   /* Process the header info */
00550   nc = ncx * ncy;
00551 
00552   if (gd2_compressed (fmt))
00553     {
00554       /* Find the maximum compressed chunk size. */
00555       compMax = 0;
00556       for (i = 0; (i < nc); i++)
00557        {
00558          if (chunkIdx[i].size > compMax)
00559            {
00560              compMax = chunkIdx[i].size;
00561            };
00562        };
00563       compMax++;
00564 
00565       if (im->trueColor)
00566        {
00567          chunkMax = cs * cs * 4;
00568        }
00569       else
00570        {
00571          chunkMax = cs * cs;
00572        }
00573       chunkBuf = gdCalloc (chunkMax, 1);
00574       compBuf = gdCalloc (compMax, 1);
00575     };
00576 
00577 /*      Don't bother with this... */
00578 /*      if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
00579 /*              goto fail2; */
00580 /*      }; */
00581 
00582 
00583   /* Work out start/end chunks */
00584   scx = srcx / cs;
00585   scy = srcy / cs;
00586   if (scx < 0)
00587     {
00588       scx = 0;
00589     };
00590   if (scy < 0)
00591     {
00592       scy = 0;
00593     };
00594 
00595   ecx = (srcx + w) / cs;
00596   ecy = (srcy + h) / cs;
00597   if (ecx >= ncx)
00598     {
00599       ecx = ncx - 1;
00600     };
00601   if (ecy >= ncy)
00602     {
00603       ecy = ncy - 1;
00604     };
00605 
00606   /* Remember file position of image data. */
00607   dstart = gdTell (in);
00608   GD2_DBG (printf ("Data starts at %d\n", dstart));
00609 
00610   /* Loop through the chunks. */
00611   for (cy = scy; (cy <= ecy); cy++)
00612     {
00613 
00614       ylo = cy * cs;
00615       yhi = ylo + cs;
00616       if (yhi > fsy)
00617        {
00618          yhi = fsy;
00619        };
00620 
00621       for (cx = scx; (cx <= ecx); cx++)
00622        {
00623 
00624          xlo = cx * cs;
00625          xhi = xlo + cs;
00626          if (xhi > fsx)
00627            {
00628              xhi = fsx;
00629            };
00630 
00631          GD2_DBG (printf
00632                  ("Processing Chunk (%d, %d), from %d to %d\n", cx, cy, ylo,
00633                   yhi));
00634 
00635          if (!gd2_compressed (fmt))
00636            {
00637              GD2_DBG (printf ("Using raw format data\n"));
00638              if (im->trueColor)
00639               {
00640                 dpos =
00641                   (cy * (cs * fsx) * 4 + cx * cs * (yhi - ylo) * 4) +
00642                   dstart;
00643               }
00644              else
00645               {
00646                 dpos = cy * (cs * fsx) + cx * cs * (yhi - ylo) + dstart;
00647               }
00648              /* gd 2.0.11: gdSeek returns TRUE on success, not 0.
00649                 Longstanding bug. 01/16/03 */
00650              if (!gdSeek (in, dpos))
00651               {
00652                 fprintf (stderr, "Seek error\n");
00653                 goto fail2;
00654               };
00655              GD2_DBG (printf
00656                      ("Reading (%d, %d) from position %d\n", cx, cy,
00657                      dpos - dstart));
00658            }
00659          else
00660            {
00661              chunkNum = cx + cy * ncx;
00662 
00663              chunkLen = chunkMax;
00664              if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
00665                               compBuf,
00666                               chunkIdx[chunkNum].size,
00667                               (char *) chunkBuf, &chunkLen, in))
00668               {
00669                 printf ("Error reading comproessed chunk\n");
00670                 goto fail2;
00671               };
00672              chunkPos = 0;
00673              GD2_DBG (printf
00674                      ("Reading (%d, %d) from chunk %d\n", cx, cy,
00675                      chunkNum));
00676            };
00677 
00678          GD2_DBG (printf
00679                  ("   into (%d, %d) - (%d, %d)\n", xlo, ylo, xhi, yhi));
00680          for (y = ylo; (y < yhi); y++)
00681            {
00682 
00683              for (x = xlo; x < xhi; x++)
00684               {
00685                 if (!gd2_compressed (fmt))
00686                   {
00687                     if (im->trueColor)
00688                      {
00689                        if (!gdGetInt ((int *) &ch, in))
00690                          {
00691                            ch = 0;
00692                            /*printf("EOF while reading file\n"); */
00693                            /*goto fail2; */
00694                          }
00695                      }
00696                     else
00697                      {
00698                        ch = gdGetC (in);
00699                        if ((int) ch == EOF)
00700                          {
00701                            ch = 0;
00702                            /*printf("EOF while reading file\n"); */
00703                            /*goto fail2; */
00704                          }
00705                      }
00706                   }
00707                 else
00708                   {
00709                     if (im->trueColor)
00710                      {
00711                        ch = chunkBuf[chunkPos++];
00712                        ch = (ch << 8) + chunkBuf[chunkPos++];
00713                        ch = (ch << 8) + chunkBuf[chunkPos++];
00714                        ch = (ch << 8) + chunkBuf[chunkPos++];
00715                      }
00716                     else
00717                      {
00718                        ch = chunkBuf[chunkPos++];
00719                      }
00720                   };
00721 
00722                 /* Only use a point that is in the image. */
00723                 if ((x >= srcx) && (x < (srcx + w)) && (x < fsx) && (x >= 0)
00724                     && (y >= srcy) && (y < (srcy + h)) && (y < fsy)
00725                     && (y >= 0))
00726                   {
00727                     /* 2.0.11: tpixels */
00728                     if (im->trueColor)
00729                      {
00730                        im->tpixels[y - srcy][x - srcx] = ch;
00731                      }
00732                     else
00733                      {
00734                        im->pixels[y - srcy][x - srcx] = ch;
00735                      }
00736                   }
00737               };
00738            };
00739        };
00740     };
00741 
00742   gdFree (chunkBuf);
00743   gdFree (compBuf);
00744   gdFree (chunkIdx);
00745 
00746   return im;
00747 
00748 fail2:
00749   gdImageDestroy (im);
00750 fail1:
00751   gdFree (chunkBuf);
00752   gdFree (compBuf);
00753   gdFree (chunkIdx);
00754 
00755   return 0;
00756 
00757 }
00758 
00759 static void
00760 _gd2PutHeader (gdImagePtr im, gdIOCtx * out, int cs, int fmt, int cx, int cy)
00761 {
00762   int i;
00763 
00764   /* Send the gd2 id, to verify file format. */
00765   for (i = 0; i < 4; i++)
00766     {
00767       gdPutC ((unsigned char) (GD2_ID[i]), out);
00768     };
00769 
00770   /* */
00771   /* We put the version info first, so future versions can easily change header info. */
00772   /* */
00773   gdPutWord (GD2_VERS, out);
00774   gdPutWord (im->sx, out);
00775   gdPutWord (im->sy, out);
00776   gdPutWord (cs, out);
00777   gdPutWord (fmt, out);
00778   gdPutWord (cx, out);
00779   gdPutWord (cy, out);
00780 
00781 }
00782 
00783 static void
00784 _gdImageGd2 (gdImagePtr im, gdIOCtx * out, int cs, int fmt)
00785 {
00786   int ncx, ncy, cx, cy;
00787   int x, y, ylo, yhi, xlo, xhi;
00788   int chunkLen;
00789   int chunkNum = 0;
00790   char *chunkData = NULL;   /* So we can gdFree it with impunity. */
00791   char *compData = NULL;    /* So we can gdFree it with impunity. */
00792   uLongf compLen;
00793   int idxPos = 0;
00794   int idxSize;
00795   t_chunk_info *chunkIdx = NULL;
00796   int posSave;
00797   int bytesPerPixel = im->trueColor ? 4 : 1;
00798   int compMax = 0;
00799 
00800   /*printf("Trying to write GD2 file\n"); */
00801 
00802   /* */
00803   /* Force fmt to a valid value since we don't return anything. */
00804   /* */
00805   if ((fmt != GD2_FMT_RAW) && (fmt != GD2_FMT_COMPRESSED))
00806     {
00807       fmt = im->trueColor ? GD2_FMT_TRUECOLOR_COMPRESSED : GD2_FMT_COMPRESSED;
00808     };
00809   if (im->trueColor)
00810     {
00811       fmt += 2;
00812     }
00813   /* */
00814   /* Make sure chunk size is valid. These are arbitrary values; 64 because it seems */
00815   /* a little silly to expect performance improvements on a 64x64 bit scale, and  */
00816   /* 4096 because we buffer one chunk, and a 16MB buffer seems a little large - it may be */
00817   /* OK for one user, but for another to read it, they require the buffer. */
00818   /* */
00819   if (cs == 0)
00820     {
00821       cs = GD2_CHUNKSIZE;
00822     }
00823   else if (cs < GD2_CHUNKSIZE_MIN)
00824     {
00825       cs = GD2_CHUNKSIZE_MIN;
00826     }
00827   else if (cs > GD2_CHUNKSIZE_MAX)
00828     {
00829       cs = GD2_CHUNKSIZE_MAX;
00830     };
00831 
00832   /* Work out number of chunks. */
00833   ncx = im->sx / cs + 1;
00834   ncy = im->sy / cs + 1;
00835 
00836   /* Write the standard header. */
00837   _gd2PutHeader (im, out, cs, fmt, ncx, ncy);
00838 
00839   if (gd2_compressed (fmt))
00840     {
00841       /* */
00842       /* Work out size of buffer for compressed data, If CHUNKSIZE is large, */
00843       /* then these will be large! */
00844       /* */
00845       /* The zlib notes say output buffer size should be (input size) * 1.01 * 12 */
00846       /* - we'll use 1.02 to be paranoid. */
00847       /* */
00848       compMax = cs * bytesPerPixel * cs * 1.02 + 12;
00849 
00850       /* */
00851       /* Allocate the buffers.  */
00852       /* */
00853       chunkData = gdCalloc (cs * bytesPerPixel * cs, 1);
00854       compData = gdCalloc (compMax, 1);
00855 
00856       /* */
00857       /* Save the file position of chunk index, and allocate enough space for */
00858       /* each chunk_info block . */
00859       /* */
00860       idxPos = gdTell (out);
00861       idxSize = ncx * ncy * sizeof (t_chunk_info);
00862       GD2_DBG (printf ("Index size is %d\n", idxSize));
00863       gdSeek (out, idxPos + idxSize);
00864 
00865       chunkIdx = gdCalloc (idxSize * sizeof (t_chunk_info), 1);
00866     };
00867 
00868   _gdPutColors (im, out);
00869 
00870   GD2_DBG (printf ("Size: %dx%d\n", im->sx, im->sy));
00871   GD2_DBG (printf ("Chunks: %dx%d\n", ncx, ncy));
00872 
00873   for (cy = 0; (cy < ncy); cy++)
00874     {
00875       for (cx = 0; (cx < ncx); cx++)
00876        {
00877 
00878          ylo = cy * cs;
00879          yhi = ylo + cs;
00880          if (yhi > im->sy)
00881            {
00882              yhi = im->sy;
00883            };
00884 
00885          GD2_DBG (printf
00886                  ("Processing Chunk (%dx%d), y from %d to %d\n", cx, cy,
00887                   ylo, yhi));
00888          chunkLen = 0;
00889          for (y = ylo; (y < yhi); y++)
00890            {
00891 
00892              /*GD2_DBG(printf("y=%d: ",y)); */
00893 
00894              xlo = cx * cs;
00895              xhi = xlo + cs;
00896              if (xhi > im->sx)
00897               {
00898                 xhi = im->sx;
00899               };
00900 
00901              if (gd2_compressed (fmt))
00902               {
00903                 for (x = xlo; x < xhi; x++)
00904                   {
00905                     /* 2.0.11: use truecolor pixel array. TBB */
00906                     /*GD2_DBG(printf("%d...",x)); */
00907                     if (im->trueColor)
00908                      {
00909                        int p = im->tpixels[y][x];
00910                        chunkData[chunkLen++] = gdTrueColorGetAlpha (p);
00911                        chunkData[chunkLen++] = gdTrueColorGetRed (p);
00912                        chunkData[chunkLen++] = gdTrueColorGetGreen (p);
00913                        chunkData[chunkLen++] = gdTrueColorGetBlue (p);
00914                      }
00915                     else
00916                      {
00917                        int p = im->pixels[y][x];
00918                        chunkData[chunkLen++] = p;
00919                      }
00920                   };
00921               }
00922              else
00923               {
00924                 for (x = xlo; x < xhi; x++)
00925                   {
00926                     /*GD2_DBG(printf("%d, ",x)); */
00927 
00928                     if (im->trueColor)
00929                      {
00930                        gdPutInt (im->tpixels[y][x], out);
00931                      }
00932                     else
00933                      {
00934                        gdPutC ((unsigned char) im->pixels[y][x], out);
00935                      }
00936                   };
00937               };
00938              /*GD2_DBG(printf("y=%d done.\n",y)); */
00939            };
00940          if (gd2_compressed (fmt))
00941            {
00942              compLen = compMax;
00943              if (compress ((unsigned char *)
00944                          &compData[0], &compLen,
00945                          (unsigned char *) &chunkData[0],
00946                          chunkLen) != Z_OK)
00947               {
00948                 printf ("Error from compressing\n");
00949               }
00950              else
00951               {
00952                 chunkIdx[chunkNum].offset = gdTell (out);
00953                 chunkIdx[chunkNum++].size = compLen;
00954                 GD2_DBG (printf
00955                         ("Chunk %d size %d offset %d\n", chunkNum,
00956                          chunkIdx[chunkNum - 1].size,
00957                          chunkIdx[chunkNum - 1].offset));
00958 
00959                 if (gdPutBuf (compData, compLen, out) <= 0)
00960                   {
00961                      fprintf(stderr, "gd write error\n");
00962                   };
00963               };
00964            };
00965        };
00966     };
00967   if (gd2_compressed (fmt))
00968     {
00969       /* Save the position, write the index, restore position (paranoia). */
00970       GD2_DBG (printf ("Seeking %d to write index\n", idxPos));
00971       posSave = gdTell (out);
00972       gdSeek (out, idxPos);
00973       GD2_DBG (printf ("Writing index\n"));
00974       for (x = 0; x < chunkNum; x++)
00975        {
00976          GD2_DBG (printf
00977                  ("Chunk %d size %d offset %d\n", x, chunkIdx[x].size,
00978                   chunkIdx[x].offset));
00979          gdPutInt (chunkIdx[x].offset, out);
00980          gdPutInt (chunkIdx[x].size, out);
00981        };
00982       /* We don't use fwrite for *endian reasons. */
00983       /*fwrite(chunkIdx, sizeof(int)*2, chunkNum, out); */
00984       gdSeek (out, posSave);
00985     };
00986 
00987   GD2_DBG (printf ("Freeing memory\n"));
00988   gdFree (chunkData);
00989   gdFree (compData);
00990   gdFree (chunkIdx);
00991   GD2_DBG (printf ("Done\n"));
00992 
00993   /*printf("Memory block size is %d\n",gdTell(out)); */
00994 
00995 }
00996 
00997 BGD_DECLARE(void) gdImageGd2 (gdImagePtr im, FILE * outFile, int cs, int fmt)
00998 {
00999   gdIOCtx *out = gdNewFileCtx (outFile);
01000   _gdImageGd2 (im, out, cs, fmt);
01001   out->gd_free (out);
01002 }
01003 
01004 BGD_DECLARE(void *) gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size)
01005 {
01006   void *rv;
01007   gdIOCtx *out = gdNewDynamicCtx (2048, NULL);
01008   _gdImageGd2 (im, out, cs, fmt);
01009   rv = gdDPExtractData (out, size);
01010   out->gd_free (out);
01011   return rv;
01012 }
01013 
01014 #else /* no HAVE_LIBZ */
01015 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2 (FILE * inFile)
01016 {
01017   fprintf (stderr, "GD2 support is not available - no libz\n");
01018   return NULL;
01019 }
01020 
01021 BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
01022 {
01023   fprintf (stderr, "GD2 support is not available - no libz\n");
01024   return NULL;
01025 }
01026 #endif /* HAVE_LIBZ */