]> git.draconx.ca Git - liblbx.git/blob - src/lbximg.c
Add version, help, and usage messages to the tools.
[liblbx.git] / src / lbximg.c
1 /* 2ooM: The Master of Orion II Reverse Engineering Project
2  * Simple command-line tool to convert an LBX image to a set of PNGs.
3  * Copyright (C) 2006-2008 Nick Bowler
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 #define _GNU_SOURCE
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <assert.h>
25 #include <getopt.h>
26 #include <errno.h>
27
28 #include <png.h>
29
30 #include "tools.h"
31 #include "image.h"
32 #include "lbx.h"
33
34 /* Global flags */
35 static int verbose = 0;
36 static char *outname = "out";
37 static int usepalette = 1;
38
39 static void printusage(void)
40 {
41         puts("usage: lbximg [-i|-d] [-v] [-p palette_file] [-O override_file]"
42                           " [-f path]");
43         puts("              [frameno ...]");
44 }
45
46 static void printhelp(void)
47 {
48         printusage();
49         puts("For now, see the man page for detailed help.");
50 }
51
52 static const char *progname;
53 #define errmsg(fmt, ...) (\
54         fprintf(stderr, "%s: " fmt, progname, __VA_ARGS__)\
55 )
56
57 enum {
58         MODE_NONE,
59         MODE_DECODE,
60         MODE_IDENT,
61 };
62
63 int parserange(struct lbx_imginfo *info, char *str, unsigned char *bits)
64 {
65         unsigned long start, end;
66         unsigned int i;
67         char *endptr;
68
69         start = strtoul(str, &endptr, 0);
70         if (start >= info->nframes) {
71                 errmsg("frame %lu out of range.\n", start);
72                 return -1;
73         }
74
75         if (endptr == str) {
76                 errmsg("invalid frame range: %s.\n", str);
77                 return -1;
78         }
79
80         switch (*endptr) {
81         case '\0':
82                 end = start;
83                 break;
84         case '-':
85                 end = strtoul(endptr+1, &endptr, 0);
86                 if (end >= info->nframes) {
87                         errmsg("frame %lu out of range.\n", end);
88                         return -1;
89                 }
90
91                 if (endptr == str)
92                         end = info->nframes - 1;
93                 break;
94         default:
95                 errmsg("invalid frame range: %s.\n", str);
96                 return -1;
97         }
98
99         if (end < start) {
100                 errmsg("invalid frame range: %s.\n", str);
101                 return -1;
102         }
103
104         for (i = start; i <= end; i++) {
105                 bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
106         }
107
108         return 0;
109 }
110
111 static int ismasked(unsigned char **mask, unsigned width, unsigned height)
112 {
113         unsigned y, x;
114         for (y = 0; y < height; y++) {
115                 for (x = 0; x < width; x++) {
116                         if (mask[y][x] == 0) return 1;
117                 }
118         }
119
120         return 0;
121 }
122
123 int outpng(unsigned int frameno,
124            unsigned char **framedata, unsigned char **mask,
125            unsigned int width, unsigned int height,
126            struct lbx_colour palette[static 256])
127 {
128         char name[strlen(outname) + sizeof ".65535.png"];
129         unsigned char *row;
130         unsigned int x, y;
131         FILE *of;
132
133         png_structp png;
134         png_infop   info;
135
136         assert(frameno < 65536);
137         snprintf(name, sizeof name, "%s.%03d.png", outname, frameno);
138
139         row = malloc(4 * width);
140         if (!row) {
141                 errmsg("failed to allocate row buffer: %s\n", strerror(errno));
142                 return -1;
143         }
144
145         of = fopen(name, "wb");
146         if (!of) {
147                 errmsg("failed to open %s: %s.\n", name, strerror(errno));
148                 free(row);
149                 return -1;
150         }
151
152         png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
153         if (!png) {
154                 errmsg("failed to init libpng.\n", 0);
155                 goto err;
156         }
157
158         info = png_create_info_struct(png);
159         if (!info) {
160                 errmsg("failed to init libpng.\n", 0);
161                 png_destroy_write_struct(&png, NULL);
162                 goto err;
163         }
164
165         if (setjmp(png_jmpbuf(png))) {
166                 free(row);
167                 png_destroy_write_struct(&png, &info);
168                 goto err;
169         }
170
171         png_init_io(png, of);
172
173         if (!ismasked(mask, width, height)) {
174                 /*
175                  * This case is easy; we can just feed the palette and pixel
176                  * data to libpng and let it do its magic.
177                  */
178
179                 png_set_IHDR(png, info, width, height, 8,
180                              PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
181                              PNG_COMPRESSION_TYPE_DEFAULT,
182                              PNG_FILTER_TYPE_DEFAULT);
183                 
184                 png_set_PLTE(png, info, (png_colorp)palette, 256);
185                 png_set_rows(png, info, framedata);
186                 png_write_png(png, info, PNG_TRANSFORM_IDENTITY, NULL);
187         } else {
188                 /*
189                  * Unfortunately, LBX doesn't translate nicely to PNG here.
190                  * LBX has a 256 colour palette _plus_ transparency.
191                  * We'll form an RGBA PNG to deal with this.
192                  */
193
194                 png_set_IHDR(png, info, width, height, 8,
195                              PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
196                              PNG_COMPRESSION_TYPE_DEFAULT,
197                              PNG_FILTER_TYPE_DEFAULT);
198         
199                 png_write_info(png, info);
200         
201                 for (y = 0; y < height; y++) {
202                         for (x = 0; x < width; x++) {
203                                 row[4*x+0] = palette[framedata[y][x]].red;
204                                 row[4*x+1] = palette[framedata[y][x]].green;
205                                 row[4*x+2] = palette[framedata[y][x]].blue;
206                                 row[4*x+3] = (mask[y][x]) ? -1 : 0;
207                         }
208         
209                         png_write_row(png, row);
210                 }
211         
212                 png_write_end(png, NULL);
213         }
214
215         png_destroy_write_struct(&png, &info);
216         fclose(of);
217
218         if (verbose)
219                 printf("wrote %s\n", name);
220
221         return 0;
222
223 err:
224         fclose(of);
225         remove(name);
226         free(row);
227         return -1;
228 }
229
230 static int loadoverride(FILE *f, struct lbx_colour palette[static 256])
231 {
232         LBX_IMG *overimg = lbximg_fopen(f);
233         struct lbx_imginfo info;
234
235         if (!overimg) {
236                 errmsg("failed to open override image: %s\n", lbx_strerror());
237                 return -1;
238         }
239         lbximg_getinfo(overimg, &info);
240
241         if (!info.palettesz) {
242                 errmsg("override image has no palette.\n", 0);
243                 lbximg_close(overimg);
244                 return -1;
245         }
246
247         if (lbximg_getpalette(overimg, palette) == -1) {
248                 errmsg("error reading override palette: %s\n", lbx_strerror());
249                 lbximg_close(overimg);
250                 return -1;
251         }
252
253         lbximg_close(overimg);
254         return 0;
255 }
256
257 static int loadpalette(LBX_IMG *img, struct lbx_imginfo *info,
258                        FILE *palf, FILE *override,
259                        struct lbx_colour palette[static 256])
260 {
261         int i;
262
263         /* In no-palette mode, use palette indices for colour. */
264         if (!usepalette) {
265                 for (i = 0; i < 256; i++) {
266                         palette[i] = (struct lbx_colour){i,i,i};
267                 }
268
269                 return 0;
270         }
271
272         /* For sanity. */
273         if (!palf && !info->palettesz && !override) {
274                 errmsg("no palette available.\n", 0);
275                 return -1;
276         }
277
278         /* Default the palette to a wonderful pink. */
279         for (i = 0; i < 256; i++) {
280                 palette[i] = (struct lbx_colour){0xff, 0x00, 0xff};
281         }
282
283         /* Read the external palette, if any. */
284         if (palf && lbximg_loadpalette(palf, palette) == -1) {
285                 errmsg("error reading external palette: %s\n", lbx_strerror());
286                 return -1;
287         }
288
289         /* Read the embedded palette, if any. */
290         if (info->palettesz && lbximg_getpalette(img, palette) == -1) {
291                 errmsg("error reading embedded palette: %s\n", lbx_strerror());
292                 return -1;
293         }
294
295         /* Read the override palette, if any. */
296         if (override && loadoverride(override, palette) == -1) {
297                 return -1;
298         }
299
300         return 0;
301 }
302
303 int decode(LBX_IMG *img, FILE *palf, FILE *override, char **argv)
304 {
305         unsigned char *framebits;
306         struct lbx_colour palette[256];
307         struct lbx_imginfo info;
308         int extracted = 0;
309         unsigned int i;
310
311         lbximg_getinfo(img, &info);
312
313         framebits = malloc(info.nframes / CHAR_BIT + 1);
314         if (!framebits) {
315                 return EXIT_FAILURE;
316         }
317
318         /* Figure out what images we're extracting. */
319         if (!argv[0]) {
320                 /* extract all images by default. */
321                 memset(framebits, -1, info.nframes / CHAR_BIT + 1);
322         } else {
323                 for (i = 0; argv[i]; i++) {
324                         parserange(&info, argv[i], framebits);
325                 }
326         }
327
328         if (loadpalette(img, &info, palf, override, palette) == -1) {
329                 goto err;
330         }
331
332         /* Extract the images, in order. */
333         for (i = 0; i < info.nframes; i++) {
334                 unsigned char **data;
335                 unsigned char **mask;
336
337                 if (!(framebits[i / CHAR_BIT] & (1 << (i % CHAR_BIT))))
338                         continue;
339
340                 data = lbximg_getframe(img, i);
341                 if (!data) {
342                         errmsg("error in frame %u: %s\n", i, lbx_strerror());
343                         continue;
344                 }
345
346                 mask = lbximg_getmask(img);
347
348                 if (!outpng(i, data, mask, info.width, info.height, palette)) {
349                         extracted = 1;
350                 }
351         }
352
353         if (!extracted) {
354                 errmsg("no frames extracted.\n", 0);
355                 goto err;
356         }
357
358         free(framebits);
359         return EXIT_SUCCESS;
360 err:
361         free(framebits);
362         return EXIT_FAILURE;
363 }
364
365 int main(int argc, char **argv)
366 {
367         int mode = MODE_NONE;
368         FILE *inf = stdin, *palf = NULL, *overf = NULL;
369         const char *name = "stdin";
370         LBX_IMG *img;
371         int opt;
372
373         static const char *sopts = "idvf:p:O:V";
374         static const struct option lopts[] = {
375                 { "ident",    0, NULL, 'i' },
376                 { "decode",   0, NULL, 'd' },
377                 { "verbose",  0, NULL, 'v' },
378                 { "file",     1, NULL, 'f' },
379                 { "palette",  1, NULL, 'p' },
380                 { "override", 1, NULL, 'p' },
381
382                 { "version",  0, NULL, 'V' },
383                 { "usage",    0, NULL, 'U' },
384                 { "help",     0, NULL, 'H' },
385
386                 { "nopalette", 0, &usepalette, 0 },
387
388                 { 0 }
389         };
390
391         progname = "lbximg"; /* argv[0]; */
392         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
393                 switch(opt) {
394                 case 'i':
395                         mode = MODE_IDENT;
396                         break;
397                 case 'd':
398                         mode = MODE_DECODE;
399                         break;
400                 case 'v':
401                         verbose = 1;
402                         break;
403                 case 'f':
404                         if (strcmp(optarg, "-") == 0)
405                                 break;
406
407                         name = strrchr(optarg, '/');
408                         name = name ? name+1 : optarg;
409
410                         inf = fopen(optarg, "rb");
411                         if (!inf) {
412                                 errmsg("failed to open %s: %m\n", optarg);
413                                 return EXIT_FAILURE;
414                         }
415                         break;
416                 case 'p':
417                         palf = fopen(optarg, "rb");
418                         if (!palf) {
419                                 errmsg("failed to open %s: %m\n", optarg);
420                                 return EXIT_FAILURE;
421                         }
422
423                         break;
424                 case 'O':
425                         overf = fopen(optarg, "rb");
426                         if (!overf) {
427                                 errmsg("failed to open %s: %m\n", optarg);
428                                 return EXIT_FAILURE;
429                         }
430                         break;
431                 case 'V':
432                         puts(VERSION_BOILERPLATE("lbximg"));
433                         return EXIT_SUCCESS;
434                 case 'U':
435                         printusage();
436                         return EXIT_SUCCESS;
437                 case 'H':
438                         printhelp();
439                         return EXIT_SUCCESS;
440                 case '?':
441                 case ':':
442                         return EXIT_FAILURE;
443                 }
444         }
445
446         if (mode == MODE_NONE) {
447                 errmsg("you must specify a mode.\n", 0);
448                 return EXIT_FAILURE;
449         }
450
451         img = lbximg_fopen(inf);
452         if (!img) {
453                 errmsg("failed to open image: %s.\n", lbx_strerror());
454                 return EXIT_FAILURE;
455         }
456
457         if (verbose || mode == MODE_IDENT) {
458                 struct lbx_imginfo info;
459                 lbximg_getinfo(img, &info);
460
461                 printf("%s is %ux%u LBX image, %u frame(s)%s%s\n",
462                        name, info.width, info.height, info.nframes,
463                        info.palettesz ? ", embedded palette" : "",
464                        info.looping   ? ", loops" : "");
465         }
466
467         switch (mode) {
468         case MODE_DECODE:
469                 if (decode(img, palf, overf, &argv[optind])) {
470                         lbximg_close(img);
471                         return EXIT_FAILURE;
472                 }
473                 break;
474         }
475
476         lbximg_close(img);
477         return EXIT_SUCCESS;
478 }