2eb9e277e417596d6d9a72204e5caba48a2815dd
[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.01';
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 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
86 my @ENDTYPE = ('none', 'message', 'small message');
87
88 sub objsummary {
89         my ($objects) = @_;
90         my @objtypes = map { $_->{type} } @$objects;
91         my %count;
92         $count{$_}++ for @objtypes;
93         return (@objtypes > 1 && keys %count == 1 && 'all ') . join(', ',
94                 map { $OBJTYPE[$_] ? $OBJTYPE[$_] . ($count{$_} > 1 && 's') : $_ }
95                 sort keys %count
96         );
97 }
98
99 # read and parse all input data
100 local $/;
101 my @rawdata = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', readline;
102 $rawdata[0] eq $MAGICID
103         or die "File does not match WormEdit level header\n";
104 $rawdata[1] == 53
105         or warn "Unsupported version $rawdata[1] (expecting 53)\n";
106
107 # convert to an easily accessible hash
108 my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@rawdata);
109 warn "Trailing data left unparsed\n" if grep {length} @rawdata;
110
111 # output with user-preferred formatting
112 if ($opt{raw}) {
113         require JSON::XS;
114         my $output = JSON::XS->new->ascii->canonical->pretty->allow_nonref;
115         print $output->encode($data), "\n";
116 }
117 else {
118         print "$data->{name} ($data->{description})\n";
119         printf "File version: %s\n", "WormEdit v$data->{version}";
120         printf "Defaults: %s\n", join('; ',
121                 'sprite ' . scalar @{ $data->{sprite} },
122                 'hiscore by ' . $data->{hiname},
123         );
124
125         my $startnr = 0;
126         for my $variant (qw/single multi race ctf/) {
127                 print "\n";
128                 my $count = $data->{levelcount}->{$variant};
129                 printf "\u$variant ($count)";
130                 $count or next;
131                 print ":";
132                 printf("\n- %-22s%4s:%3s+%2s%3s %3sx%-3s%s",
133                         $_->{id} || $_->{name},
134                         @$_{qw/size bsize growth/},
135                         $variant eq 'single' && "x$_->{peas}",
136                         @$_{qw/width height/},
137                         join(';', map {" $_"} grep {$_}
138                                 @{$_->{objects}} && sprintf('%2d object%s (%s)',
139                                         scalar @{$_->{objects}}, @{$_->{objects}} != 1 && 's',
140                                         objsummary($_->{objects}),
141                                 ),
142                                 @{$_->{sprite}} && sprintf('sprite %d',
143                                         scalar @{$_->{sprite}},
144                                 ),
145                         ),
146                 ) for map { $data->{levels}->[$_ + $startnr] }
147                         0 .. $count - 1;
148                 $startnr += $count;
149         }
150         continue {
151                 print "\n";
152                 printf("-- %-21s%4d: %s (%s)\n",
153                         '(ending)',
154                         length $data->{enddata},
155                         $ENDTYPE[$data->{endtype}] || 'unknown', $data->{endstr},
156                 ) if $variant eq 'single';
157         }
158 }
159
160 package Shiar_Parse::Nested;
161
162 sub template {
163         my ($self, $format) = @_;
164         # total (flattened) unpack template from nested format definitions
165         return join '', map {
166                 my $value = $format->[-($_ << 1) - 1];
167                 if (ref $value eq 'ARRAY') {
168                         my $count = $value->[0];
169                         $value = $self->template($value);
170                         $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
171                                 : $count."X[$count]$count/($value)";
172                 }
173                 else {
174                         $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e;  # length prefix
175                 }
176                 $value;
177         } reverse 0 .. ($#$format - 1) >> 1;
178 }
179
180 sub convert {
181         my ($self, $format, $data) = @_;
182         # map flat results into a named and nested hash
183         my %res;
184         while (my ($field, $template) = splice @$format, 0, 2) {
185                 if (ref $template eq 'ARRAY') {
186                         my ($count, @subformat) = @$template;
187                         my $max = $count =~ s/^(\d+)// ? $1 : 0;
188                         $count = !$count ? $max
189                                 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
190                         $max ||= $count;
191                         $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. $max-1;
192                         splice @{ $res{$field} }, $count if $max > $count;
193                         $res{$field} = $res{$field}->[0] if $max == 1;
194                         next;
195                 }
196                 elsif ($template =~ /^Ca/) {
197                         $data->[0] = unpack 'C/a', $data->[0];
198                 }
199                 $res{$field} = shift @$data;
200         }
201         return \%res;
202 }
203
204 __END__
205
206 =head1 NAME
207
208 parse-wormedit - WormEdit level data parser
209
210 =head1 SYNOPSIS
211
212  parse-wormedit [--raw] <input.lvl>
213
214 =head1 DESCRIPTION
215
216 Reads WormEdit v0.53 levels from STDIN or given file,
217 and outputs contents, summarised or in full.
218
219 =head1 AUTHOR
220
221 Mischa POSLAWSKY <wormy@shiar.org>
222
223 =head1 LICENSE
224
225 GPL version 3.
226