]> git.draconx.ca Git - liblbx.git/blob - src/lbximg.c
Trivial manual fixes.
[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 other formats.
4  *  Copyright © 2006-2011, 2013-2014, 2021 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 <stdbool.h>
23 #include <string.h>
24 #include <limits.h>
25 #include <stdint.h>
26 #include <assert.h>
27 #include <getopt.h>
28 #include <errno.h>
29
30 #include "help.h"
31
32 #include "tools.h"
33 #include "image.h"
34 #include "error.h"
35 #include "lbx.h"
36
37 #include "imgoutput.h"
38
39 #define MIN(a, b) ((a) < (b) ? (a) : (b))
40
41 /* Global flags */
42 static int verbose = 0;
43 static char *outname = "out";
44 static int usepalette = 1;
45
46 #include "imgopts.h"
47 static const char sopts[] = SOPT_STRING;
48 static const struct option lopts[] = { LOPTS_INITIALIZER, {0} };
49
50 static void print_usage(FILE *f)
51 {
52         const char *progname = tool_invocation();
53
54         fprintf(f, "Usage: %s [options] [-i|-d] [frame ...]\n", progname);
55         if (f != stdout)
56                 fprintf(f, "Try %s --help for more information.\n", progname);
57 }
58
59 static void print_help(void)
60 {
61         const struct option *opt;
62
63         print_usage(stdout);
64
65         putchar('\n');
66         puts("Options:");
67         for (opt = lopts; opt->name; opt++) {
68                 struct lopt_help help;
69                 int w;
70
71                 if (!lopt_get_help(opt, &help))
72                         continue;
73
74                 help_print_option(opt, help.arg, help.desc, 20);
75         }
76         putchar('\n');
77
78         puts("For more information, see the lbximg(1) man page.");
79         putchar('\n');
80
81         printf("Report bugs to <%s>.\n", PACKAGE_BUGREPORT);
82 }
83
84 enum {
85         MODE_NONE,
86         MODE_DECODE,
87         MODE_IDENT,
88 };
89
90 static const struct img_format {
91         img_output_func *output;
92         char name[4];
93         bool enabled;
94 } formats[] = {
95 #if HAVE_LIBPNG
96         { img_output_png, "png", 1 },
97 #endif
98         { img_output_pam, "pam", 1 },
99         { img_output_ppm, "ppm", 1 },
100         { img_output_pbm, "pbm", 1 },
101 };
102
103 static int lookup_format(const char *fmt)
104 {
105         for (size_t i = 0; i < sizeof formats / sizeof formats[0]; i++) {
106                 assert(!formats[i].name[sizeof formats[i].name - 1]);
107
108                 if (!fmt && formats[i].enabled)
109                         return i;
110
111                 if (strcmp(formats[i].name, fmt))
112                         continue;
113
114                 if (!formats[i].enabled) {
115                         tool_err(-1, "%s support disabled at build time", fmt);
116                         return -1;
117                 }
118
119                 return i;
120         }
121
122         tool_err(-1, "unknown format %s", fmt);
123         return -1;
124 }
125
126 bool img_is_masked(unsigned char *mask, unsigned width, unsigned height)
127 {
128         unsigned long npixels = (unsigned long) width * height;
129         unsigned long mask_sz = npixels / CHAR_BIT + (npixels % CHAR_BIT != 0);
130
131         for (unsigned long i = 0; i < mask_sz; i++) {
132                 if (i+1 < mask_sz) {
133                         if (mask[i] != (unsigned char)-1)
134                                 return true;
135                 } else {
136                         unsigned char test = (1u << npixels % CHAR_BIT) - 1;
137
138                         if ((mask[i] & test) != test)
139                                 return true;
140                 }
141         }
142
143         return false;
144 }
145
146 int parserange(unsigned frames, char *str, unsigned char *bits)
147 {
148         unsigned long start, end;
149         unsigned int i;
150         char *endptr;
151
152         start = strtoul(str, &endptr, 0);
153         if (start >= frames) {
154                 tool_err(-1, "frame %lu out of range.", start);
155                 return -1;
156         }
157
158         if (endptr == str) {
159                 tool_err(-1, "invalid frame range: %s.", str);
160                 return -1;
161         }
162
163         switch (*endptr) {
164         case '\0':
165                 end = start;
166                 break;
167         case '-':
168                 end = strtoul(endptr+1, &endptr, 0);
169                 if (end >= frames) {
170                         tool_err(-1, "frame %lu out of range.", end);
171                         return -1;
172                 }
173
174                 if (endptr == str)
175                         end = frames - 1;
176                 break;
177         default:
178                 tool_err(-1, "invalid frame range: %s.", str);
179                 return -1;
180         }
181
182         if (end < start) {
183                 tool_err(-1, "invalid frame range: %s.", str);
184                 return -1;
185         }
186
187         for (i = start; i <= end; i++) {
188                 bits[i / CHAR_BIT] |= 1 << (i % CHAR_BIT);
189         }
190
191         return 0;
192 }
193
194 static int output(unsigned int frameno, const struct img_format *fmt,
195                   unsigned char *pixels, unsigned char *pixel_mask,
196                   unsigned int width, unsigned int height,
197                   struct lbx_colour *palette)
198 {
199         char name[strlen(outname) + sizeof ".65535.png"];
200         FILE *of;
201         int rc;
202
203         assert(fmt->output != NULL);
204         assert(frameno < 65536);
205         snprintf(name, sizeof name, "%s.%03d.%s", outname, frameno, fmt->name);
206
207         of = fopen(name, "wb");
208         if (!of) {
209                 tool_err(0, "failed to open %s", name);
210                 return -1;
211         }
212
213         rc = fmt->output(of, name, width, height, pixels, pixel_mask, palette);
214         if (rc < 0) {
215                 fclose(of);
216                 return -1;
217         }
218
219         if (fclose(of) == EOF) {
220                 tool_err(0, "error writing %s", name);
221                 return -1;
222         }
223
224         if (verbose)
225                 printf("wrote %s\n", name);
226
227         return 0;
228 }
229
230 static int loadoverride(FILE *f, struct lbx_colour *palette)
231 {
232         struct lbx_image *img;
233         int rc, ret = 0;
234
235         img = lbx_img_open(f, &lbx_default_fops, NULL);
236         if (!img) {
237                 tool_err(-1, "failed to open override image: %s", lbx_errmsg());
238                 return -1;
239         }
240
241         rc = lbx_img_getpalette(img, palette);
242         if (rc < 0) {
243                 tool_err(-1, "error reading override palette: %s", lbx_errmsg());
244                 ret = -1;
245         } else if (rc == 0) {
246                 tool_err(-1, "override image has no palette.");
247                 ret = -1;
248         }
249
250         lbx_img_close(img);
251         return ret;
252 }
253
254 static int loadpalette(struct lbx_image *img, FILE *palf, FILE *override,
255                        struct lbx_colour *palette)
256 {
257         int rc, ret = -1;
258
259         /* Default the palette to a wonderful pink. */
260         for (unsigned i = 0; i < 256; i++) {
261                 palette[i] = (struct lbx_colour){0x3f, 0x00, 0x3f};
262         }
263
264         /* Read the external palette, if any. */
265         if (palf) {
266                 rc = lbx_img_loadpalette(palf, &lbx_default_fops, palette);
267                 if (rc < 0) {
268                         tool_err(-1, "error reading external palette: %s", lbx_errmsg());
269                         return -1;
270                 }
271
272                 ret = 0;
273         }
274
275         /* Read the embedded palette */
276         rc = lbx_img_getpalette(img, palette);
277         if (rc < 0) {
278                 tool_err(-1, "error reading embedded palette: %s", lbx_errmsg());
279                 return -1;
280         } else if (rc > 0) {
281                 ret = 0;
282         }
283
284         /* Read the override palette, if any. */
285         if (override) {
286                 rc = loadoverride(override, palette);
287                 if (rc < 0)
288                         return -1;
289                 ret = 0;
290         }
291
292         /* If we literally have no palette data at all, may as well fail. */
293         if (ret < 0)
294                 tool_err(-1, "no palette available.");
295         return ret;
296 }
297
298 /* Return true iff a divides b. */
299 static bool divides(unsigned a, unsigned b)
300 {
301         if (b == 0)
302                 return true;
303         if (a == 0)
304                 return false;
305
306         return b % a == 0;
307 }
308
309 /* Set n bits starting from offset in the bitmap. */
310 static void
311 set_bits(unsigned char *bitmap, unsigned long offset, unsigned long n)
312 {
313         if (offset % CHAR_BIT) {
314                 bitmap[offset/CHAR_BIT] |= (n >= CHAR_BIT ? -1u : (1u << n) - 1)
315                                   << offset%CHAR_BIT;
316
317                 n -= MIN(n, CHAR_BIT - offset%CHAR_BIT);
318                 offset += CHAR_BIT - offset%CHAR_BIT;
319         }
320
321         if (n > CHAR_BIT) {
322                 memset(&bitmap[offset/CHAR_BIT], -1, n/CHAR_BIT);
323
324                 offset += n - n%CHAR_BIT;
325                 n %= CHAR_BIT;
326         }
327
328         if (n) {
329                 bitmap[offset/CHAR_BIT] |= (1u << n) - 1;
330         }
331 }
332
333 static int decode_frame(struct lbx_image *img, unsigned n,
334                         unsigned char *pixels, unsigned char *pixel_mask)
335 {
336         unsigned x, y;
337         long rc;
338
339         rc = lbx_img_seek(img, n);
340         if (rc < 0) {
341                 tool_err(-1, "frame %u: invalid frame: %s\n", n, lbx_errmsg());
342                 return -1;
343         }
344
345         while ((rc = lbx_img_read_row_header(img, &x, &y)) != 0) {
346                 unsigned long offset;
347
348                 if (rc < 0) {
349                         tool_err(-1, "frame %u: invalid row: %s", n, lbx_errmsg());
350                         return -1;
351                 }
352
353                 offset = (unsigned long) y * img->width + x;
354                 rc = lbx_img_read_row_data(img, pixels+offset);
355                 if (rc < 0) {
356                         tool_err(-1, "frame %u: error reading row: %s\n", n, lbx_errmsg());
357                         return -1;
358                 }
359
360                 set_bits(pixel_mask, offset, rc);
361         }
362
363         return 0;
364 }
365
366 static int
367 decode(struct lbx_image *img, FILE *palf, FILE *override, int fmt, char **argv)
368 {
369         unsigned char *pixels = NULL, *pixel_mask = NULL, *framebits = NULL;
370         struct lbx_colour palette[256];
371         int rc, ret = EXIT_FAILURE;
372         int extracted = 0;
373         unsigned int i;
374         size_t npixels, mask_sz;
375
376         assert(fmt >= 0 && fmt < sizeof formats / sizeof formats[0]);
377
378         npixels = img->width;
379         if (img->height && npixels >= (size_t)-1 / img->height) {
380                 tool_err(-1, "image too large");
381                 goto err;
382         }
383         npixels *= img->height;
384
385         /* Ensure there is at least 1 byte to allocate */
386         if (npixels == 0)
387                 npixels = 1;
388
389         framebits = calloc(1, img->frames / CHAR_BIT + 1);
390         if (!framebits) {
391                 tool_err(0, "failed to allocate memory");
392                 goto err;
393         }
394
395         pixels = calloc(img->width, img->height);
396         if (!pixels) {
397                 tool_err(0, "failed to allocate memory");
398                 goto err;
399         }
400
401         mask_sz = npixels / CHAR_BIT + (npixels % CHAR_BIT != 0);
402         pixel_mask = malloc(mask_sz);
403         if (!pixel_mask) {
404                 tool_err(0, "failed to allocate memory");
405                 goto err;
406         }
407
408         /* Figure out what images we're extracting. */
409         if (!argv[0]) {
410                 /* extract all images by default. */
411                 memset(framebits, -1, img->frames / CHAR_BIT + 1);
412         } else {
413                 for (i = 0; argv[i]; i++) {
414                         parserange(img->frames, argv[i], framebits);
415                 }
416         }
417
418         if (usepalette) {
419                 if (loadpalette(img, palf, override, palette) == -1) {
420                         ret = EXIT_FAILURE;
421                         goto err;
422                 }
423         }
424
425         /* Extract the images, in order. */
426         ret = EXIT_SUCCESS;
427         for (i = 0; i < img->frames; i++) {
428                 if (divides(img->chunk, i))
429                         memset(pixel_mask, 0, mask_sz);
430
431                 rc = decode_frame(img, i, pixels, pixel_mask);
432                 if (rc < 0) {
433                         ret = EXIT_FAILURE;
434                         goto err;
435                 }
436
437                 if (framebits[i / CHAR_BIT] & (1u << (i % CHAR_BIT))) {
438                         rc = output(i, &formats[fmt], pixels, pixel_mask,
439                                     img->width, img->height,
440                                     usepalette ? palette : NULL);
441
442                         if (rc == 0) {
443                                 extracted = 1;
444                         }
445                 }
446         }
447
448         if (!extracted) {
449                 tool_err(-1, "no frames extracted.");
450                 ret = EXIT_FAILURE;
451         }
452 err:
453         free(pixels);
454         free(pixel_mask);
455         free(framebits);
456         return ret;
457 }
458
459 int main(int argc, char **argv)
460 {
461         int mode = MODE_NONE, fmt, opt, rc = EXIT_FAILURE;
462         struct lbx_pipe_state stdin_handle = { .f = stdin };
463         const char *file = NULL, *fmtstring = NULL;
464         const char *ext_palette = NULL, *ovr_palette = NULL;
465         FILE *palf = NULL, *overf = NULL;
466         struct lbx_image *img;
467
468         tool_init("lbximg", argc, argv);
469         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
470                 switch(opt) {
471                 case 'i':
472                         mode = MODE_IDENT;
473                         break;
474                 case 'd':
475                         mode = MODE_DECODE;
476                         break;
477                 case 'v':
478                         verbose = 1;
479                         break;
480                 case 'F':
481                         fmtstring = optarg;
482                         break;
483                 case 'f':
484                         file = optarg;
485                         break;
486                 case 'n':
487                         usepalette = 0;
488                         break;
489                 case 'p':
490                         ext_palette = optarg;
491
492                         break;
493                 case 'O':
494                         ovr_palette = optarg;
495                         break;
496                 case LOPT_OUTPUT_PREFIX:
497                         outname = optarg;
498                         break;
499                 case 'V':
500                         tool_version();
501                         return EXIT_SUCCESS;
502                 case 'H':
503                         print_help();
504                         return EXIT_SUCCESS;
505                 default:
506                         return EXIT_FAILURE;
507                 }
508         }
509
510         if (mode == MODE_NONE) {
511                 tool_err(-1, "you must specify a mode.");
512                 return EXIT_FAILURE;
513         }
514
515         fmt = lookup_format(fmtstring);
516         if (fmt < 0)
517                 return EXIT_FAILURE;
518
519         if (file)
520                 img = lbx_img_fopen(file);
521         else
522                 img = lbx_img_open(&stdin_handle, &lbx_pipe_fops, NULL);
523
524         if (!img) {
525                 tool_err(-1, "failed to open image: %s.", lbx_errmsg());
526                 return EXIT_FAILURE;
527         }
528
529         if (ext_palette && !(palf = fopen(ext_palette, "rb"))) {
530                 tool_err(0, "failed to open %s", optarg);
531                 return EXIT_FAILURE;
532         }
533
534         if (ovr_palette && !(overf = fopen(ovr_palette, "rb"))) {
535                 tool_err(0, "failed to open %s", optarg);
536                 return EXIT_FAILURE;
537         }
538
539         if (verbose || mode == MODE_IDENT) {
540                 int palette_count;
541
542                 if (!file)
543                         file = "stdin";
544
545                 palette_count = lbx_img_getpalette(img, NULL);
546                 if (palette_count < 0) {
547                         tool_err(-1, "error reading image: %s", lbx_errmsg());
548                         return EXIT_FAILURE;
549                 }
550
551                 printf("%s is %hux%hu LBX image, %hhu frame(s)%s%s%s\n",
552                        file, img->width, img->height, img->frames,
553                        palette_count ? ", embedded palette" : "",
554                        img->chunk    ? ", chunked" : "",
555                        img->leadin+1 < img->frames ? ", loops" : "");
556         }
557
558         switch (mode) {
559         case MODE_IDENT:
560                 rc = 0;
561                 break;
562         case MODE_DECODE:
563                 rc = decode(img, palf, overf, fmt, &argv[optind]);
564                 break;
565         }
566
567         lbx_img_close(img);
568         if (palf)
569                 fclose(palf);
570         if (overf)
571                 fclose(overf);
572         return rc;
573 }