]> git.draconx.ca Git - liblbx.git/blobdiff - src/lbximg.c
liblbx: Add support for "chunked" images.
[liblbx.git] / src / lbximg.c
index 0770049c48ff071c8dac3b21aedf442968b6594a..933e1e079abef22c84b709f12539448ecc0a50ae 100644 (file)
@@ -1,12 +1,54 @@
-#define _GNU_SOURCE
+/*
+ *  2ooM: The Master of Orion II Reverse Engineering Project
+ *  Simple command-line tool to convert an LBX image to a set of PNGs.
+ *  Copyright (C) 2006-2008 Nick Bowler
+ *
+ *  This program 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, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program 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.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+#include <config.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
+#include <assert.h>
 #include <getopt.h>
+#include <errno.h>
 
+#include <png.h>
+
+#include "tools.h"
 #include "image.h"
 #include "lbx.h"
 
+/* Global flags */
+static int verbose = 0;
+static char *outname = "out";
+static int usepalette = 1;
+
+static void printusage(void)
+{
+       puts("usage: lbximg [-i|-d] [-v] [-p palette_file] [-O override_file]"
+                         " [-f path]");
+       puts("              [frameno ...]");
+}
+
+static void printhelp(void)
+{
+       printusage();
+       puts("For now, see the man page for detailed help.");
+}
+
 static const char *progname;
 #define errmsg(fmt, ...) (\
        fprintf(stderr, "%s: " fmt, progname, __VA_ARGS__)\
@@ -18,21 +60,337 @@ enum {
        MODE_IDENT,
 };
 
+int parserange(struct lbx_imginfo *info, char *str, unsigned char *bits)
+{
+       unsigned long start, end;
+       unsigned int i;
+       char *endptr;
+
+       start = strtoul(str, &endptr, 0);
+       if (start >= info->nframes) {
+               errmsg("frame %lu out of range.\n", start);
+               return -1;
+       }
+
+       if (endptr == str) {
+               errmsg("invalid frame range: %s.\n", str);
+               return -1;
+       }
+
+       switch (*endptr) {
+       case '\0':
+               end = start;
+               break;
+       case '-':
+               end = strtoul(endptr+1, &endptr, 0);
+               if (end >= info->nframes) {
+                       errmsg("frame %lu out of range.\n", end);
+                       return -1;
+               }
+
+               if (endptr == str)
+                       end = info->nframes - 1;
+               break;
+       default:
+               errmsg("invalid frame range: %s.\n", str);
+               return -1;
+       }
+
+       if (end < start) {
+               errmsg("invalid frame range: %s.\n", str);
+               return -1;
+       }
+
+       for (i = start; i <= end; i++) {
+               bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
+       }
+
+       return 0;
+}
+
+static int ismasked(unsigned char **mask, unsigned width, unsigned height)
+{
+       unsigned y, x;
+       for (y = 0; y < height; y++) {
+               for (x = 0; x < width; x++) {
+                       if (mask[y][x] == 0) return 1;
+               }
+       }
+
+       return 0;
+}
+
+int outpng(unsigned int frameno,
+           unsigned char **framedata, unsigned char **mask,
+           unsigned int width, unsigned int height,
+           struct lbx_colour palette[static 256])
+{
+       char name[strlen(outname) + sizeof ".65535.png"];
+       unsigned char *row;
+       unsigned int x, y;
+       FILE *of;
+
+       png_structp png;
+       png_infop   info;
+
+       assert(frameno < 65536);
+       snprintf(name, sizeof name, "%s.%03d.png", outname, frameno);
+
+       row = malloc(4 * width);
+       if (!row) {
+               errmsg("failed to allocate row buffer: %s\n", strerror(errno));
+               return -1;
+       }
+
+       of = fopen(name, "wb");
+       if (!of) {
+               errmsg("failed to open %s: %s.\n", name, strerror(errno));
+               free(row);
+               return -1;
+       }
+
+       png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+       if (!png) {
+               errmsg("failed to init libpng.\n", 0);
+               goto err;
+       }
+
+       info = png_create_info_struct(png);
+       if (!info) {
+               errmsg("failed to init libpng.\n", 0);
+               png_destroy_write_struct(&png, NULL);
+               goto err;
+       }
+
+       if (setjmp(png_jmpbuf(png))) {
+               free(row);
+               png_destroy_write_struct(&png, &info);
+               goto err;
+       }
+
+       png_init_io(png, of);
+
+       if (!ismasked(mask, width, height)) {
+               /*
+                * This case is easy; we can just feed the palette and pixel
+                * data to libpng and let it do its magic.
+                */
+
+               png_color png_palette[256];
+               for (unsigned i = 0; i < 256; i++) {
+                       png_palette[i].red   = palette[i].red;
+                       png_palette[i].green = palette[i].green;
+                       png_palette[i].blue  = palette[i].blue;
+               }
+
+               png_set_IHDR(png, info, width, height, 8,
+                            PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
+                            PNG_COMPRESSION_TYPE_DEFAULT,
+                            PNG_FILTER_TYPE_DEFAULT);
+               
+               png_set_PLTE(png, info, png_palette, 256);
+               png_set_rows(png, info, framedata);
+               png_write_png(png, info, PNG_TRANSFORM_IDENTITY, NULL);
+       } else {
+               /*
+                * Unfortunately, LBX doesn't translate nicely to PNG here.
+                * LBX has a 256 colour palette _plus_ transparency.
+                * We'll form an RGBA PNG to deal with this.
+                */
+
+               png_set_IHDR(png, info, width, height, 8,
+                            PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
+                            PNG_COMPRESSION_TYPE_DEFAULT,
+                            PNG_FILTER_TYPE_DEFAULT);
+       
+               png_write_info(png, info);
+       
+               for (y = 0; y < height; y++) {
+                       for (x = 0; x < width; x++) {
+                               row[4*x+0] = palette[framedata[y][x]].red;
+                               row[4*x+1] = palette[framedata[y][x]].green;
+                               row[4*x+2] = palette[framedata[y][x]].blue;
+                               row[4*x+3] = (mask[y][x]) ? -1 : 0;
+                       }
+       
+                       png_write_row(png, row);
+               }
+       
+               png_write_end(png, NULL);
+       }
+
+       png_destroy_write_struct(&png, &info);
+       fclose(of);
+
+       if (verbose)
+               printf("wrote %s\n", name);
+
+       return 0;
+
+err:
+       fclose(of);
+       remove(name);
+       free(row);
+       return -1;
+}
+
+static int loadoverride(FILE *f, struct lbx_colour palette[static 256])
+{
+       LBX_IMG *overimg = lbximg_fopen(f);
+       struct lbx_imginfo info;
+
+       if (!overimg) {
+               errmsg("failed to open override image: %s\n", lbx_strerror());
+               return -1;
+       }
+       lbximg_getinfo(overimg, &info);
+
+       if (!info.palettesz) {
+               errmsg("override image has no palette.\n", 0);
+               lbximg_close(overimg);
+               return -1;
+       }
+
+       if (lbximg_getpalette(overimg, palette) == -1) {
+               errmsg("error reading override palette: %s\n", lbx_strerror());
+               lbximg_close(overimg);
+               return -1;
+       }
+
+       lbximg_close(overimg);
+       return 0;
+}
+
+static int loadpalette(LBX_IMG *img, struct lbx_imginfo *info,
+                       FILE *palf, FILE *override,
+                       struct lbx_colour palette[static 256])
+{
+       int i;
+
+       /* In no-palette mode, use palette indices for colour. */
+       if (!usepalette) {
+               for (i = 0; i < 256; i++) {
+                       palette[i] = (struct lbx_colour){i,i,i};
+               }
+
+               return 0;
+       }
+
+       /* For sanity. */
+       if (!palf && !info->palettesz && !override) {
+               errmsg("no palette available.\n", 0);
+               return -1;
+       }
+
+       /* Default the palette to a wonderful pink. */
+       for (i = 0; i < 256; i++) {
+               palette[i] = (struct lbx_colour){0xff, 0x00, 0xff};
+       }
+
+       /* Read the external palette, if any. */
+       if (palf && lbximg_loadpalette(palf, &lbx_default_fops, palette) != 0) {
+               errmsg("error reading external palette: %s\n", lbx_strerror());
+               return -1;
+       }
+
+       /* Read the embedded palette, if any. */
+       if (info->palettesz && lbximg_getpalette(img, palette) == -1) {
+               errmsg("error reading embedded palette: %s\n", lbx_strerror());
+               return -1;
+       }
+
+       /* Read the override palette, if any. */
+       if (override && loadoverride(override, palette) == -1) {
+               return -1;
+       }
+
+       return 0;
+}
+
+int decode(LBX_IMG *img, FILE *palf, FILE *override, char **argv)
+{
+       unsigned char *framebits;
+       struct lbx_colour palette[256];
+       struct lbx_imginfo info;
+       int extracted = 0;
+       unsigned int i;
+
+       lbximg_getinfo(img, &info);
+
+       framebits = malloc(info.nframes / CHAR_BIT + 1);
+       if (!framebits) {
+               return EXIT_FAILURE;
+       }
+
+       /* Figure out what images we're extracting. */
+       if (!argv[0]) {
+               /* extract all images by default. */
+               memset(framebits, -1, info.nframes / CHAR_BIT + 1);
+       } else {
+               for (i = 0; argv[i]; i++) {
+                       parserange(&info, argv[i], framebits);
+               }
+       }
+
+       if (loadpalette(img, &info, palf, override, palette) == -1) {
+               goto err;
+       }
+
+       /* Extract the images, in order. */
+       for (i = 0; i < info.nframes; i++) {
+               unsigned char **data;
+               unsigned char **mask;
+
+               if (!(framebits[i / CHAR_BIT] & (1 << (i % CHAR_BIT))))
+                       continue;
+
+               data = lbximg_getframe(img, i);
+               if (!data) {
+                       errmsg("error in frame %u: %s\n", i, lbx_strerror());
+                       continue;
+               }
+
+               mask = lbximg_getmask(img);
+
+               if (!outpng(i, data, mask, info.width, info.height, palette)) {
+                       extracted = 1;
+               }
+       }
+
+       if (!extracted) {
+               errmsg("no frames extracted.\n", 0);
+               goto err;
+       }
+
+       free(framebits);
+       return EXIT_SUCCESS;
+err:
+       free(framebits);
+       return EXIT_FAILURE;
+}
+
 int main(int argc, char **argv)
 {
-       int mode = MODE_NONE, verbose = 0;
-       FILE *inf = stdin, *palf = NULL;
+       int mode = MODE_NONE, opt, rc = EXIT_FAILURE;
+       struct lbx_pipe_state state = { .f = stdin };
+       FILE *palf = NULL, *overf = NULL;
        const char *name = "stdin";
        LBX_IMG *img;
-       int opt;
 
-       static const char *sopts = "idvf:p:";
+       static const char *sopts = "idvf:p:O:V";
        static const struct option lopts[] = {
-               { "info",    0, NULL, 'i' },
-               { "decode",  0, NULL, 'd' },
-               { "verbose", 0, NULL, 'v' },
-               { "file",    1, NULL, 'f' },
-               { "palette", 1, NULL, 'p' },
+               { "ident",    0, NULL, 'i' },
+               { "decode",   0, NULL, 'd' },
+               { "verbose",  0, NULL, 'v' },
+               { "file",     1, NULL, 'f' },
+               { "palette",  1, NULL, 'p' },
+               { "override", 1, NULL, 'p' },
+
+               { "version",  0, NULL, 'V' },
+               { "usage",    0, NULL, 'U' },
+               { "help",     0, NULL, 'H' },
+
+               { "nopalette", 0, &usepalette, 0 },
 
                { 0 }
        };
@@ -50,14 +408,10 @@ int main(int argc, char **argv)
                        verbose = 1;
                        break;
                case 'f':
-                       if (strcmp(optarg, "-") == 0)
-                               break;
-
                        name = strrchr(optarg, '/');
                        name = name ? name+1 : optarg;
 
-                       inf = fopen(optarg, "rb");
-                       if (!inf) {
+                       if (!freopen(optarg, "rb", state.f)) {
                                errmsg("failed to open %s: %m\n", optarg);
                                return EXIT_FAILURE;
                        }
@@ -70,7 +424,24 @@ int main(int argc, char **argv)
                        }
 
                        break;
-               default:
+               case 'O':
+                       overf = fopen(optarg, "rb");
+                       if (!overf) {
+                               errmsg("failed to open %s: %m\n", optarg);
+                               return EXIT_FAILURE;
+                       }
+                       break;
+               case 'V':
+                       puts(VERSION_BOILERPLATE("lbximg"));
+                       return EXIT_SUCCESS;
+               case 'U':
+                       printusage();
+                       return EXIT_SUCCESS;
+               case 'H':
+                       printhelp();
+                       return EXIT_SUCCESS;
+               case '?':
+               case ':':
                        return EXIT_FAILURE;
                }
        }
@@ -80,7 +451,11 @@ int main(int argc, char **argv)
                return EXIT_FAILURE;
        }
 
-       img = lbximg_fopen(inf);
+       if (fseek(state.f, 0, SEEK_CUR) == 0)
+               img = lbximg_open(state.f, &lbx_default_fops, NULL);
+       else
+               img = lbximg_open(&state, &lbx_pipe_fops, NULL);
+
        if (!img) {
                errmsg("failed to open image: %s.\n", lbx_strerror());
                return EXIT_FAILURE;
@@ -90,16 +465,19 @@ int main(int argc, char **argv)
                struct lbx_imginfo info;
                lbximg_getinfo(img, &info);
 
-               printf("%s is %ux%u LBX image, %u frames\n",
-                      name, info.width, info.height, info.nframes);
+               printf("%s is %ux%u LBX image, %u frame(s)%s%s\n",
+                      name, info.width, info.height, info.nframes,
+                      info.palettesz ? ", embedded palette" : "",
+                      info.chunk     ? ", chunked" : "",
+                      info.looping   ? ", loops" : "");
        }
 
        switch (mode) {
        case MODE_DECODE:
-               errmsg("decode function not yet implemented.\n", 0);
+               rc = decode(img, palf, overf, &argv[optind]);
                break;
        }
 
        lbximg_close(img);
-       return EXIT_SUCCESS;
+       return rc;
 }