4f9295904e9d49356bd49034df801aeefbd66e9a
[wormy.git] / parse-wormedit
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4
5 use Data::Dumper;
6 use Getopt::Long 2.33 qw(HelpMessage :config bundling);
7
8 our $VERSION = '1.00';
9
10 GetOptions(\my %opt,
11         'raw|r',
12 ) or HelpMessage(-exitval => 2);
13
14 my $MAGICID = "WormEdit053\000LVL";
15
16 my @FORMAT = (
17         magic       => 'a15',
18         version     => 'C',
19         name        => 'Ca32',
20         description => 'Ca64x256',
21         levelcount  => [1,
22                 single => 'C',
23                 multi  => 'C',
24                 race   => 'C',
25                 ctf    => 'C',
26                 total  => 'C',
27         ],
28         moderef     => [1,
29                 map { (start => $_, end => $_) } [1,
30                         single     => 'C',
31                         peaworm    => 'C',
32                         tron       => 'C',
33                         deathmatch => 'C',
34                         foodmatch  => 'C',
35                         multifood  => 'C',
36                         timematch  => 'C',
37                         race       => 'C',
38                         ctf        => 'Cx',
39                 ],
40         ],
41         sprite     => ['8C',
42                 line => 'B8',
43         ],
44         endtype     => 's',
45         endstr      => 'Ca255',
46         enddata     => 'Ca255x256',
47         hiname      => 'a3',
48         levels      => ['*', # levelcount->total actually
49                 id         => 'Ca22',
50                 name       => 'Ca22',
51                 size       => 'C',
52                 peas       => 'C',
53                 delay      => 'C',
54                 growth     => 'C',
55                 bsize      => 'C',
56                 sprite     => ['8C',
57                         line => 'B8',
58                 ],
59                 balls      => ['32C',
60                         y   => 'C',
61                         x   => 'C',
62                         dir => 'C',
63                 ],
64                 worms      => [4,
65                         d => 'C',
66                         y => 'C',
67                         x => 'C',
68                 ],
69                 width      => 'C',
70                 height     => 'C',
71                 flags      => [2,
72                         y => 'C',
73                         x => 'C',
74                 ],
75                 objects    => ['128C',
76                         type => 'C',
77                         x1   => 'C',
78                         y1   => 'C',
79                         x2   => 'C',
80                         y2   => 'C',
81                 ],
82         ],
83 );
84
85 # read and parse all input data
86 local $/;
87 my @rawdata = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', readline;
88 $rawdata[0] eq $MAGICID
89         or die "File does not match WormEdit level header\n";
90 $rawdata[1] == 53
91         or warn "Unsupported version $rawdata[1] (expecting 53)\n";
92
93 # convert to an easily accessible hash
94 my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@rawdata);
95 warn "Trailing data left unparsed\n" if grep {length} @rawdata;
96
97 # output with user-preferred formatting
98 if ($opt{raw}) {
99         require JSON::XS;
100         my $output = JSON::XS->new->ascii->canonical->pretty->allow_nonref;
101         print $output->encode($data), "\n";
102 }
103 else {
104         print "$data->{name} ($data->{description})\n";
105         my $startnr = 0;
106         for my $variant (qw/single multi race ctf/) {
107                 print "\n";
108                 my $count = $data->{levelcount}->{$variant};
109                 printf "\u$variant ($count)";
110                 $count or next;
111                 print ":";
112                 printf("\n- %-22s (%3sx%3s, %d objects)",
113                         $_->{id}, $_->{width}, $_->{height}, scalar @{ $_->{objects} },
114                 ) for map { $data->{levels}->[$_ + $startnr] }
115                         0 .. $count - 1;
116                 $startnr += $count;
117         }
118         continue {
119                 print "\n";
120         }
121 }
122
123 package Shiar_Parse::Nested;
124
125 sub template {
126         my ($self, $format) = @_;
127         # total (flattened) unpack template from nested format definitions
128         return join '', map {
129                 my $value = $format->[-($_ << 1) - 1];
130                 if (ref $value eq 'ARRAY') {
131                         my $count = $value->[0];
132                         $value = $self->template($value);
133                         $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
134                                 : $count."X[$count]$count/($value)";
135                 }
136                 else {
137                         $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e;  # length prefix
138                 }
139                 $value;
140         } reverse 0 .. ($#$format - 1) >> 1;
141 }
142
143 sub convert {
144         my ($self, $format, $data) = @_;
145         # map flat results into a named and nested hash
146         my %res;
147         while (my ($field, $template) = splice @$format, 0, 2) {
148                 if (ref $template eq 'ARRAY') {
149                         my ($count, @subformat) = @$template;
150                         my $max = $count =~ s/^(\d+)// ? $1 : 0;
151                         $count = !$count ? $max
152                                 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
153                         $max ||= $count;
154                         $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. $max-1;
155                         splice @{ $res{$field} }, $count if $max > $count;
156                         $res{$field} = $res{$field}->[0] if $max == 1;
157                         next;
158                 }
159                 elsif ($template =~ /^Ca/) {
160                         $data->[0] = unpack 'C/a', $data->[0];
161                 }
162                 $res{$field} = shift @$data;
163         }
164         return \%res;
165 }
166
167 __END__
168
169 =head1 NAME
170
171 parse-wormedit - WormEdit level data parser
172
173 =head1 SYNOPSIS
174
175  parse-wormedit [--raw] <input.lvl>
176
177 =head1 DESCRIPTION
178
179 Reads WormEdit v0.53 levels from STDIN or given file,
180 and outputs contents, summarised or in full.
181
182 =head1 AUTHOR
183
184 Mischa POSLAWSKY <wormy@shiar.org>
185
186 =head1 LICENSE
187
188 GPL version 3.
189