parse-wormedit: json format option
[wormy.git] / parse-wormedit
index 8136c58151c9d838f9f538860b3414db669baaf0..aa220513657bfdaf49507b9311e97ea627334025 100755 (executable)
 #!/usr/bin/env perl
+use 5.010;
 use strict;
 use warnings;
-use 5.010;
+use experimental 'switch';
+use lib 'lib';  # make runnable for simple cases
 
 use Data::Dumper;
 use Getopt::Long 2.33 qw(HelpMessage :config bundling);
+use Games::Wormy::TICalcLevels;
+use Games::Wormy::WormEdit;
 
-our $VERSION = '1.03';
+our $VERSION = '1.07';
 
 GetOptions(\my %opt,
-       'raw|r',  # full output
+       'format|f=s', # output type
+       'raw|r!',  # compatibility for yaml format
        'version=i',  # force version
+       'levels|render:i',  # image of level(s)
+       'output|o=s',  # output file
 ) or HelpMessage(-exitval => 2);
-
-
-package Shiar_Parse::WormEdit;
-
-use strict;
-use warnings;
-
-our %MAGICID = (
-       "WormEdit053\000LVL" => 53,
-       "WormEdit\34195\000LVL" => 95,
-       "WormEdit\34194\000LVL" => 94,
-       "WormEdit\34193\000LVL" => 93,
-);
-
-my @FORMAT = (
-       magic       => 'a15',
-       version     => 'C',
-       name        => 'Ca32',
-       description => 'Ca64x256',
-       levelcount  => [1,
-               single => 'C',
-               multi  => 'C',
-               race   => 'C',
-               ctf    => 'C',
-               total  => 'C',
-       ],
-       moderef     => [1,
-               map { (start => $_, end => $_) } [1,
-                       single     => 'C',
-                       peaworm    => 'C',
-                       tron       => 'C',
-                       deathmatch => 'C',
-                       foodmatch  => 'C',
-                       multifood  => 'C',
-                       timematch  => 'C',
-                       race       => 'C',
-                       ctf        => 'Cx',
-               ],
-       ],
-       sprite     => ['8C',
-               line => 'B8',
-       ],
-       finish      => [1,
-               type    => 's',
-               message => 'Ca255',
-               code    => 'Ca255x256',
-       ],
-       hiname      => 'a3',
-       levels      => ['*', # levelcount->total actually
-               id         => 'Ca22',
-               name       => 'Ca22',
-               size       => 'C',
-               peas       => 'C',
-               delay      => 'C',
-               growth     => 'C',
-               bsize      => 'C',
-               sprite     => ['8C',
-                       line => 'B8',
-               ],
-               balls      => ['32C',
-                       y   => 'C',
-                       x   => 'C',
-                       dir => 'C',
-               ],
-               worms      => [4,
-                       d => 'C',
-                       y => 'C',
-                       x => 'C',
-               ],
-               width      => 'C',
-               height     => 'C',
-               flags      => [2,
-                       y => 'C',
-                       x => 'C',
-               ],
-               objects    => ['128C',
-                       type => 'C',
-                       x1   => 'C',
-                       y1   => 'C',
-                       x2   => 'C',
-                       y2   => 'C',
-               ],
-       ],
-);
-
-sub read {
-       my ($self, $input) = @_;
-       my ($id, $version) = (substr($input, 0, 15), ord substr($input, 15, 1));
-       my $fileversion = $MAGICID{$id}
-               or die "File does not match any known WormEdit level header\n";
-
-       if ($opt{version}) {
-               warn "Override version $version to $opt{version}\n";
-               $version = $opt{version};
-       }
-       elsif ($version != $fileversion) {
-               warn "Unexpected version $version (expecting $fileversion)\n";
-       }
-       elsif ($version == 95) {
-               # auto-detect exact variant
-               if (ord substr($input, 70, 1) ~~ [1 .. 8]) {
-                       # valid sprite length instead of description byte
-                       # (which is usually a letter or nul)
-                       $version = 94;
-               }
-               elsif (ord substr($input, 147, 1) == 0) {
-                       # nul of finish type is 2 bytes later (unlike first char of message)
-                       $version = 96;
-               }
-               warn "Ambiguous file version 95; guessing subversion $version\n";
-       };
-
-       $fileversion += 100 if $fileversion < 90;  # 93..95 came before 50..53
-       given ($fileversion) {
-               when (153) { } # current @FORMAT
-                       $FORMAT[7] = 'Ca64'; # no reserved space after description
-                       $FORMAT[15]->[-1] = 'Ca255'; # enddata
-                       $FORMAT[-1]->[-1]->[0] = '32C'; # less objects
-               when ($version == 96) {
-                       ref $_ and $_->[-1] = 'C' for @{ $FORMAT[11] }; # 9 moderefs
-               }
-                       ref $_ and pop @$_ for @{ $FORMAT[11] }; # only 8 moderefs
-                       splice @FORMAT, 6, 2 if $version <= 94;  # earlier version without description
-               when (95) { }
-                       splice @{ $FORMAT[7] }, 4, 2;  # no race
-                       splice @{ $FORMAT[13] }, 4, 2; # no enddata
-                       splice @{ $FORMAT[-1] }, 1, 2; # no name
-               when (94) { }
-                       splice @FORMAT, 14, 2; # no hiname
-                       $FORMAT[-1]->[0] = 64; # constant amount of levels
-               when (93) { }
-               default {
-                       die "Cannot parse data for Wormedit $fileversion/$version\n";
-               }
-       }
-
-       # convert to an easily accessible hash
-       my @values = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', $input;
-       my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@values);
-       warn "Trailing data left unparsed\n" if grep {length} @values;
-       $data->{format} = 'WormEdit';
-       return $data;
-}
-
-
-package Shiar_Parse::WormyLevel;
-
-use strict;
-use warnings;
-
-use List::Util qw(sum min max);
-
-sub read {
-       my ($self, $input) = @_;
-       my ($psize, $ptype, $size, $type, $vsize, $dsize, $id, $subid) = unpack q{
-               x11 x42    # file signature and comment
-               S a2 S a2  # file size, type; data size, type
-               x8         # var name
-               S S        # var size; content size
-               CC         # wormy header
-       }, $input;
-       $ptype eq "\014\000"
-               or die "Not a calculator string, thus cannot be a Wormy level file\n";
-       $size == $psize - 16
-               or warn "File size ($size) does not correspond with data size ($psize)\n";
-       $type eq "\014\010"
-               or die "Not a calculator string, thus cannot be a Wormy level file\n";
-       $size == $vsize and $vsize == $dsize+2
-               or warn "Mismatch in string data size declarations\n";
-#      substr($input, -2) eq $CHECKSUM
-
-       $input = substr $input, 73, -2;
-       $id eq ord 'w'
-               or die "Wormy level identifier not found\n";
-       my @FORMAT = (
-               magic       => 'a1',
-               version     => 'C',
-               name        => 'Z*',
-               description => 'Z*',
-               levelcount  => [1,
-                       total  => 'S',
-               ],
-               moderef     => [1,
-                       map { (
-                               offset => [1, map {$_ => 'S'} @$_], # byte location of start
-                               end    => [1, map {$_ => 'C'} @$_],
-                       ) }
-                       [qw/single peaworm tron deathmatch foodmatch multifood timematch race ctf/]
-               ],
-               theanswer => 'C', # 42
-               sprite     => ['C',
-                       line => 'B8',
-               ],
-               leveldata => 'a*',
-       );
-       my @LEVELFORM = (
-               peas       => 'C',
-               delay      => 'C',
-               growth     => 'C',
-               bsize      => 'C',
-               sprite     => ['C',
-                       line => 'B8',
-               ],
-               balls      => ['C',
-                       y   => 'C',
-                       x   => 'C',
-                       dir => 'C',
-               ],
-               worms      => [1,
-                       d => 'C',
-                       y => 'C',
-                       x => 'C',
-               ],
-               width      => 'C',
-               height     => 'C',
-               flags      => [0,
-                       y => 'C',
-                       x => 'C',
-               ],
-               #levels
-               #finish code
-               #levels-multi
-               #hinames
-       );
-       my @OBJECTFORM = (
-                       type => 'C',
-                       x1   => 'C',
-                       y1   => 'C',
-                       x2   => 'C',
-                       y2   => 'C',
-       );
-
-       given ($subid) {
-               when (97) {
-                       # current @FORMAT
-               }
-               when (95) {
-                       ref $_ and splice @$_, -2 for @{ $FORMAT[11] }; # only 8 moderefs
-                       splice @FORMAT, 12, 2;  # no reserved byte
-               }
-               default {
-                       die "Unsupported level version $subid\n";
-               }
-       }
-
-       my $data = Shiar_Parse::Nested->unpack(\@FORMAT, $input);
-       my $offset = 0;
-       my $offsetbase = 0xF080 + @{ $data->{sprite} } + 1;
-       $data->{moderef}->{offset}->{single} == $offsetbase
-               or warn "First singleplayer level is not in front\n";
-
-       my $slots = sum(
-               $data->{moderef}->{end}->{single} > 0,  # singleplayer slot if any levels
-               $data->{moderef}->{end}->{peaworm},     # one for each peaworm arena
-               $data->{moderef}->{end}->{tron},        # idem for tron
-       );
-       $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
-       $data->{format} = '86s';
-
-       my @VARMODES = (
-               [qw'single  single'],
-               [qw'multi   peaworm tron deathmatch foodmatch multifood timematch'],
-               [qw'race    race'],
-               [qw'ctf     ctf'],
-       );
-
-       $data->{levels} = [];
-       for my $modes (@VARMODES) {
-               my $variant = shift @$modes;
-               $offset = min(grep {$_} map { $data->{moderef}->{offset}->{$_} } @$modes)
-                       or next;
-               $offset -= $offsetbase;
-               my $amount = $variant eq 'single' ? 100 : max(map { $data->{moderef}->{end}->{$_} } @$modes);
-
-               my @varform = @LEVELFORM;
-               $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
-               unshift @varform, name => 'Z*' unless $variant eq 'single';
-               $varform[-1]->[0] = 1 if $variant eq 'race';
-               $varform[-1]->[0] = 2 if $variant eq 'ctf';
-
-               while ($offset < length $data->{leveldata}) {
-                       last if substr($data->{leveldata}, $offset, 1) eq chr(255);
-
-                       # find references to this level offset, and set start number to matching modes
-                       while (my ($mode, $location) = each %{ $data->{moderef}->{offset} }) {
-                               $location == $offset + $offsetbase or next;
-                               $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
-                       }
-
-                       my $level = Shiar_Parse::Nested->unpack(
-                               [@varform], substr $data->{leveldata}, $offset
-                       );
-                       my $size = 8  # unpack length (ugh, ugly recalculation)
-                               + (defined $level->{name} ? 1 + length $level->{name} : 0)
-                               + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
-                               + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
-                               + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
-                               + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
-                       $level->{size} = $size;
-                       $level->{offset} = $offset + $offsetbase;
-
-                       # add objects until terminator
-                       $level->{objects} = [];
-                       while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
-                               push @{ $level->{objects} }, Shiar_Parse::Nested->unpack(
-                                       [@OBJECTFORM], substr($data->{leveldata}, $offset+$size, 5)
-                               );
-                               $size += 5;
-                       }
-
-                       # add parsed level and advance
-                       push @{ $data->{levels} }, $level;
-                       $offset += ++$size;
-                       last if ++$data->{levelcount}->{$variant} >= $amount;
-               }
-
-               if ($variant eq 'single') {
-                       $data->{finish}->{code} = substr(
-                               delete($data->{leveldata}), $offset, -5 * $slots
-                       );
-               }
-       }
-
-       return $data;
-}
-
-
-package Shiar_Parse::Nested;
-
-sub template {
-       my ($self, $format) = @_;
-       # total (flattened) unpack template from nested format definitions
-       return join '', map {
-               my $value = $format->[-($_ << 1) - 1];
-               if (ref $value eq 'ARRAY') {
-                       my $count = $value->[0];
-                       $value = $self->template($value);
-                       $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
-                               : $count."X[$count]$count/($value)";
-               }
-               else {
-                       $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e;  # length prefix
-               }
-               $value;
-       } reverse 0 .. ($#$format - 1) >> 1;
-}
-
-sub convert {
-       my ($self, $format, $data) = @_;
-       # map flat results into a named and nested hash
-       my %res;
-       while (my ($field, $template) = splice @$format, 0, 2) {
-               if (ref $template eq 'ARRAY') {
-                       my ($count, @subformat) = @$template;
-                       my $max = $count =~ s/^(\d+)// ? $1 : 0;
-                       $count = !$count ? $max
-                               : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
-                       $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
-                       splice @{ $res{$field} }, $count if $max > $count;
-                       $res{$field} = $res{$field}->[0] if $max == 1;
-                       next;
-               }
-               elsif ($template =~ /^Ca/) {
-                       $data->[0] = CORE::unpack 'C/a', $data->[0];
-               }
-               $res{$field} = shift @$data;
-       }
-       return \%res;
-}
-
-sub unpack {
-       my ($self, $format, $input) = @_;
-       my @data = CORE::unpack $self->template($format), $input;
-       return $self->convert($format, \@data);
-}
-
-
-package main;
+$opt{format} //= 'yaml' if $opt{raw};
+$opt{format} //= 'pnm'  if defined $opt{levels};
 
 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
 my @ENDTYPE = ('none', 'message', 'small message');
@@ -411,18 +42,39 @@ local $/;
 my $rawdata = readline;
 if (substr($rawdata, 0, 11) eq "**TI86**\032\012\000") {
        # compiled calculator file
-       $data = Shiar_Parse::WormyLevel->read($rawdata);
+       $data = Games::Wormy::TICalcLevels->read($rawdata, $opt{version});
 }
 elsif (substr($rawdata, 0, 8) eq 'WormEdit') {
        # original wormedit source
-       $data = Shiar_Parse::WormEdit->read($rawdata);
+       $data = Games::Wormy::WormEdit->read($rawdata, $opt{version});
 }
 else {
        die "Unrecognised file type\n";
 }
 
+if ($opt{output}) {{
+       # derive format from file extension
+       if ($opt{output} =~ /\.(yaml|json|txt)$/) {
+               $opt{format} //= $1
+       }
+       else {
+               # images are written directly to file
+               last;
+       }
+
+       # redirect standard output to given file
+       open my $output, '>', $opt{output}
+               or die "Cannot output to '$opt{output}': $!";
+       select $output;
+}}
+
 # output with user-preferred formatting
-if ($opt{raw}) {
+given ($opt{format}) {
+when ('json') {
+       require JSON;
+       say JSON->new->encode($data);
+}
+when ('yaml') {
        # full data in yaml (human-readable) formatting
        require YAML;
        local $YAML::CompressSeries;
@@ -444,21 +96,22 @@ if ($opt{raw}) {
 
        print $yml;
 }
-else {
+when ('txt') {
        print $data->{name};
        print " ($data->{description})" if defined $data->{description};
        print "\n";
        printf "File version: %s\n", "$data->{format} v$data->{version}";
        printf "Defaults: %s\n", join('; ',
-               'sprite ' . scalar @{ $data->{sprite} },
+               $data->{sprite} ? 'sprite ' . scalar @{ $data->{sprite} } : (),
                defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
        );
 
        my $startnr = 0;
-       for my $variant (qw/single multi race ctf/) {
+       for my $variant (qw/single peaworm multi race ctf/) {
                my $count = $data->{levelcount}->{$variant};
+               defined $count or next;
                print "\n";
-               printf '%s (%s)', ucfirst $variant, $count // 'invalid';
+               printf '%s (%s)', ucfirst $variant, $count;
                $count or next;
                print ":";
                for (0 .. $count - 1) {
@@ -483,8 +136,7 @@ else {
                        );
                }
                $startnr += $count;
-       }
-       continue {
+
                print "\n";
                printf("-- %-21s%4s: %s (%s)\n",
                        '(ending)',
@@ -495,6 +147,34 @@ else {
                        $data->{finish}->{message} // '?',
                ) if $variant eq 'single';
        }
+       print "\n";
+}
+default {
+       require Games::Wormy::Render;
+
+       my @request;
+       if ($opt{levels}) {
+               # find all numeric values in argument
+               @request = $opt{levels} =~ /(\d+)/g;
+       }
+       else {
+               # default to all singleplayer levels
+               @request = 0 .. $data->{levelcount}->{single} - 1;
+       }
+       @request or die "no levels found or specified\n";
+
+       my $img = Games::Wormy::Render->composite(
+               map { $data->{levels}->[$_] } @request
+       ) or die "empty result for levels\n";
+       if ($opt{format} ~~ 'pbm') {
+               $img = $img->to_paletted({make_colors => 'mono'});
+               $opt{format} = 'pnm';
+       }
+       $img->write(
+               $opt{output} ? (file => $opt{output}) : (fh => \*STDOUT),
+               type => $opt{format} // 'pnm',
+       ) or die $img->errstr;
+}
 }
 
 __END__
@@ -505,12 +185,36 @@ parse-wormedit - Wormy level data parser
 
 =head1 SYNOPSIS
 
- parse-wormedit [--raw] <input.lvl>
+ parse-wormedit [--format=<type>] [--levels=<number>] [--output=<file.ext>] <input.lvl>
 
 =head1 DESCRIPTION
 
 Reads Wormy levels (either original WormEdit source or compiled TI-86 string)
-from STDIN or given file, and outputs contents, summarised or in full.
+from STDIN or given file, and prints parsed data to STDOUT.
+
+If an I<output> file name is given, its extension determines the format,
+otherwise explicitly given by the I<format> option:
+
+=over 6
+
+=item txt
+
+Plain text summary of levelpack contents.
+
+=item yaml
+
+All parsed data in YAML syntax.
+
+=item json
+
+Parsed data in JSON syntax.
+
+=item pnm, png, bmp, ...
+
+Image drawing of rendered levels.
+Unrecognised values are interpreted as file type and converted by Imager.
+
+=back
 
 =head1 AUTHOR