]> git.draconx.ca Git - liblbx.git/blob - src/lbximg.c
ff38c89b71f998f0dff387f5f2404e4ffb0783cf
[liblbx.git] / src / lbximg.c
1 /*
2  *  2ooM: The Master of Orion II Reverse Engineering Project
3  *  Simple command-line tool to convert an LBX image to a set of PNGs.
4  *  Copyright © 2006-2011, 2013 Nick Bowler
5  *
6  *  This program is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 #include <config.h>
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 "error.h"
33 #include "lbx.h"
34
35 /* Global flags */
36 static int verbose = 0;
37 static char *outname = "out";
38 static int usepalette = 1;
39
40 static void printusage(void)
41 {
42         puts("usage: lbximg [-i|-d] [-v] [-p palette_file] [-O override_file]"
43                           " [-f path]");
44         puts("              [frameno ...]");
45 }
46
47 static void printhelp(void)
48 {
49         printusage();
50         puts("For now, see the man page for detailed help.");
51 }
52
53 enum {
54         MODE_NONE,
55         MODE_DECODE,
56         MODE_IDENT,
57 };
58
59 int parserange(unsigned frames, char *str, unsigned char *bits)
60 {
61         unsigned long start, end;
62         unsigned int i;
63         char *endptr;
64
65         start = strtoul(str, &endptr, 0);
66         if (start >= frames) {
67                 tool_err(-1, "frame %lu out of range.", start);
68                 return -1;
69         }
70
71         if (endptr == str) {
72                 tool_err(-1, "invalid frame range: %s.", str);
73                 return -1;
74         }
75
76         switch (*endptr) {
77         case '\0':
78                 end = start;
79                 break;
80         case '-':
81                 end = strtoul(endptr+1, &endptr, 0);
82                 if (end >= frames) {
83                         tool_err(-1, "frame %lu out of range.", end);
84                         return -1;
85                 }
86
87                 if (endptr == str)
88                         end = frames - 1;
89                 break;
90         default:
91                 tool_err(-1, "invalid frame range: %s.", str);
92                 return -1;
93         }
94
95         if (end < start) {
96                 tool_err(-1, "invalid frame range: %s.", str);
97                 return -1;
98         }
99
100         for (i = start; i <= end; i++) {
101                 bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
102         }
103
104         return 0;
105 }
106
107 static int ismasked(unsigned char **mask, unsigned width, unsigned height)
108 {
109         unsigned y, x;
110         for (y = 0; y < height; y++) {
111                 for (x = 0; x < width; x++) {
112                         if (mask[y][x] == 0) return 1;
113                 }
114         }
115
116         return 0;
117 }
118
119 int outpng(unsigned int frameno,
120            unsigned char **framedata, unsigned char **mask,
121            unsigned int width, unsigned int height,
122            struct lbx_colour palette[static 256])
123 {
124         char name[strlen(outname) + sizeof ".65535.png"];
125         unsigned char *row;
126         unsigned int x, y;
127         FILE *of;
128
129         png_structp png;
130         png_infop   info;
131
132         assert(frameno < 65536);
133         snprintf(name, sizeof name, "%s.%03d.png", outname, frameno);
134
135         row = malloc(4 * width);
136         if (!row) {
137                 tool_err(0, "failed to allocate row buffer");
138                 return -1;
139         }
140
141         of = fopen(name, "wb");
142         if (!of) {
143                 tool_err(0, "failed to open %s", name);
144                 return -1;
145         }
146
147         png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
148         if (!png) {
149                 tool_err(-1, "failed to init libpng.");
150                 goto err;
151         }
152
153         info = png_create_info_struct(png);
154         if (!info) {
155                 tool_err(-1, "failed to init libpng.");
156                 png_destroy_write_struct(&png, NULL);
157                 goto err;
158         }
159
160         if (setjmp(png_jmpbuf(png))) {
161                 png_destroy_write_struct(&png, &info);
162                 goto err;
163         }
164
165         png_init_io(png, of);
166
167         if (!ismasked(mask, width, height)) {
168                 /*
169                  * This case is easy; we can just feed the palette and pixel
170                  * data to libpng and let it do its magic.
171                  */
172
173                 png_color png_palette[256];
174                 for (unsigned i = 0; i < 256; i++) {
175                         png_palette[i].red   = palette[i].red;
176                         png_palette[i].green = palette[i].green;
177                         png_palette[i].blue  = palette[i].blue;
178                 }
179
180                 png_set_IHDR(png, info, width, height, 8,
181                              PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE,
182                              PNG_COMPRESSION_TYPE_DEFAULT,
183                              PNG_FILTER_TYPE_DEFAULT);
184                 
185                 png_set_PLTE(png, info, png_palette, 256);
186                 png_set_rows(png, info, framedata);
187                 png_write_png(png, info, PNG_TRANSFORM_IDENTITY, NULL);
188         } else {
189                 /*
190                  * Unfortunately, LBX doesn't translate nicely to PNG here.
191                  * LBX has a 256 colour palette _plus_ transparency.
192                  * We'll form an RGBA PNG to deal with this.
193                  */
194
195                 png_set_IHDR(png, info, width, height, 8,
196                              PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
197                              PNG_COMPRESSION_TYPE_DEFAULT,
198                              PNG_FILTER_TYPE_DEFAULT);
199         
200                 png_write_info(png, info);
201         
202                 for (y = 0; y < height; y++) {
203                         for (x = 0; x < width; x++) {
204                                 row[4*x+0] = palette[framedata[y][x]].red;
205                                 row[4*x+1] = palette[framedata[y][x]].green;
206                                 row[4*x+2] = palette[framedata[y][x]].blue;
207                                 row[4*x+3] = (mask[y][x]) ? -1 : 0;
208                         }
209         
210                         png_write_row(png, row);
211                 }
212         
213                 png_write_end(png, NULL);
214         }
215
216         png_destroy_write_struct(&png, &info);
217         fclose(of);
218         free(row);
219
220         if (verbose)
221                 printf("wrote %s\n", name);
222         return 0;
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         struct lbx_image *overimg = lbx_img_open(f, &lbx_default_fops, NULL);
233         struct lbx_imginfo info;
234
235         if (!overimg) {
236                 tool_err(-1, "failed to open override image: %s", lbx_errmsg());
237                 return -1;
238         }
239         lbx_img_getinfo(overimg, &info);
240
241         if (!info.palettesz) {
242                 tool_err(-1, "override image has no palette.");
243                 lbx_img_close(overimg);
244                 return -1;
245         }
246
247         if (lbx_img_getpalette(overimg, palette) == -1) {
248                 tool_err(-1, "error reading override palette: %s", lbx_errmsg());
249                 lbx_img_close(overimg);
250                 return -1;
251         }
252
253         lbx_img_close(overimg);
254         return 0;
255 }
256
257 static int loadpalette(struct lbx_image *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                 tool_err(-1, "no palette available.");
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 && lbx_img_loadpalette(palf, &lbx_default_fops, palette) != 0) {
285                 tool_err(-1, "error reading external palette: %s", lbx_errmsg());
286                 return -1;
287         }
288
289         /* Read the embedded palette, if any. */
290         if (info->palettesz && lbx_img_getpalette(img, palette) == -1) {
291                 tool_err(-1, "error reading embedded palette: %s", lbx_errmsg());
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(struct lbx_image *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         lbx_img_getinfo(img, &info);
312
313         framebits = calloc(1, img->frames / 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, img->frames / CHAR_BIT + 1);
322         } else {
323                 for (i = 0; argv[i]; i++) {
324                         parserange(img->frames, 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 < img->frames; 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 = lbx_img_getframe(img, i);
341                 if (!data) {
342                         tool_err(-1, "error in frame %u: %s", i, lbx_errmsg());
343                         continue;
344                 }
345
346                 mask = lbx_img_getmask(img);
347
348                 if (!outpng(i, data, mask, img->width, img->height, palette)) {
349                         extracted = 1;
350                 }
351         }
352
353         if (!extracted) {
354                 tool_err(-1, "no frames extracted.");
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, opt, rc = EXIT_FAILURE;
368         struct lbx_pipe_state stdin_handle = { .f = stdin };
369         FILE *palf = NULL, *overf = NULL;
370         const char *file = NULL;
371         struct lbx_image *img;
372
373         static const char *sopts = "idnvf: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                 { "no-palette", 0, NULL, 'n' },
387
388                 { 0 }
389         };
390
391         tool_init("lbximg", argc, argv);
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                         file = optarg;
405                         break;
406                 case 'n':
407                         usepalette = 0;
408                         break;
409                 case 'p':
410                         palf = fopen(optarg, "rb");
411                         if (!palf) {
412                                 tool_err(0, "failed to open %s", optarg);
413                                 return EXIT_FAILURE;
414                         }
415
416                         break;
417                 case 'O':
418                         overf = fopen(optarg, "rb");
419                         if (!overf) {
420                                 tool_err(0, "failed to open %s", optarg);
421                                 return EXIT_FAILURE;
422                         }
423                         break;
424                 case 'V':
425                         tool_version();
426                         return EXIT_SUCCESS;
427                 case 'U':
428                         printusage();
429                         return EXIT_SUCCESS;
430                 case 'H':
431                         printhelp();
432                         return EXIT_SUCCESS;
433                 case '?':
434                 case ':':
435                         return EXIT_FAILURE;
436                 }
437         }
438
439         if (mode == MODE_NONE) {
440                 tool_err(-1, "you must specify a mode.");
441                 return EXIT_FAILURE;
442         }
443
444         if (file)
445                 img = lbx_img_fopen(file);
446         else
447                 img = lbx_img_open(&stdin_handle, &lbx_pipe_fops, NULL);
448
449         if (!img) {
450                 tool_err(-1, "failed to open image: %s.", lbx_errmsg());
451                 return EXIT_FAILURE;
452         }
453
454         if (verbose || mode == MODE_IDENT) {
455                 struct lbx_imginfo info;
456
457                 if (!file)
458                         file = "stdin";
459
460                 lbx_img_getinfo(img, &info);
461                 printf("%s is %ux%u LBX image, %u frame(s)%s%s\n",
462                        file, img->width, img->height, img->frames,
463                        info.palettesz ? ", embedded palette" : "",
464                        img->chunk     ? ", chunked" : "",
465                        info.looping   ? ", loops" : "");
466         }
467
468         switch (mode) {
469         case MODE_DECODE:
470                 rc = decode(img, palf, overf, &argv[optind]);
471                 break;
472         }
473
474         lbx_img_close(img);
475         return rc;
476 }