7 use Getopt::Long 2.33 qw(HelpMessage :config bundling);
12 'raw|r', # full output
13 'version=i', # force version
14 ) or HelpMessage(-exitval => 2);
17 package Shiar_Parse::WormEdit;
23 "WormEdit053\000LVL" => 53,
24 "WormEdit\34195\000LVL" => 95,
25 "WormEdit\34194\000LVL" => 94,
26 "WormEdit\34193\000LVL" => 93,
33 description => 'Ca64x256',
42 map { (start => $_, end => $_) } [1,
59 enddata => 'Ca255x256',
61 levels => ['*', # levelcount->total actually
99 my ($self, $input) = @_;
100 my ($id, $version) = (substr($input, 0, 15), ord substr($input, 15, 1));
101 my $fileversion = $MAGICID{$id}
102 or die "File does not match any known WormEdit level header\n";
105 warn "Override version $version to $opt{version}\n";
106 $version = $opt{version};
108 elsif ($version != $fileversion) {
109 warn "Unexpected version $version (expecting $fileversion)\n";
111 elsif ($version == 95) {
112 # auto-detect exact variant
113 if (ord substr($input, 70, 1) ~~ [1 .. 8]) {
114 # valid sprite length instead of description byte
115 # (which is usually a letter or nul)
118 elsif (ord substr($input, 147, 1) == 0) {
119 # nul of end type is 2 bytes later (unlike first char of endstr)
122 warn "Ambiguous file version 95; guessing subversion $version\n";
125 $fileversion += 100 if $fileversion < 90; # 93..95 came before 50..53
126 given ($fileversion) {
127 when (153) { } # current @FORMAT
128 $FORMAT[7] = 'Ca64'; # no reserved space after description
129 $FORMAT[19] = 'Ca255'; # enddata
130 $FORMAT[-1]->[-1]->[0] = '32C'; # less objects
131 when ($version == 96) {
132 ref $_ and $_->[-1] = 'C' for @{ $FORMAT[11] }; # 9 moderefs
134 ref $_ and pop @$_ for @{ $FORMAT[11] }; # only 8 moderefs
135 splice @FORMAT, 6, 2 if $version <= 94; # earlier version without description
137 splice @{ $FORMAT[7] }, 4, 2; # no race
138 splice @FORMAT, 16, 2; # no enddata
139 splice @{ $FORMAT[-1] }, 1, 2; # no name
141 splice @FORMAT, 16, 2; # no hiname
142 $FORMAT[-1]->[0] = 64; # constant amount of levels
145 die "Cannot parse data for Wormedit $fileversion/$version\n";
149 # convert to an easily accessible hash
150 my @values = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', $input;
151 my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@values);
152 warn "Trailing data left unparsed\n" if grep {length} @values;
153 $data->{format} = 'WormEdit';
158 package Shiar_Parse::WormyLevel;
163 use List::Util qw(sum min max);
166 my ($self, $input) = @_;
167 my ($psize, $ptype, $size, $type, $vsize, $dsize, $id, $subid) = unpack q{
168 x11 x42 # file signature and comment
169 S a2 S a2 # file size, type; data size, type
171 S S # var size; content size
175 or die "Not a calculator string, thus cannot be a Wormy level file\n";
177 or warn "File size ($size) does not correspond with data size ($psize)\n";
179 or die "Not a calculator string, thus cannot be a Wormy level file\n";
180 $size == $vsize and $vsize == $dsize+2
181 or warn "Mismatch in string data size declarations\n";
182 # substr($input, -2) eq $CHECKSUM
184 $input = substr $input, 73, -2;
186 or die "Wormy level identifier not found\n";
197 offset => [1, map {$_ => 'S'} @$_], # byte location of start
198 end => [1, map {$_ => 'C'} @$_],
200 [qw/single peaworm tron deathmatch foodmatch multifood timematch race ctf/]
202 theanswer => 'C', # 42
250 ref $_ and splice @$_, -2 for @{ $FORMAT[11] }; # only 8 moderefs
251 splice @FORMAT, 12, 2; # no reserved byte
254 die "Unsupported level version $subid\n";
258 my $data = Shiar_Parse::Nested->unpack(\@FORMAT, $input);
260 my $offsetbase = 0xF080 + @{ $data->{sprite} } + 1;
261 $data->{moderef}->{offset}->{single} == $offsetbase
262 or warn "First singleplayer level is not in front\n";
266 [qw'multi peaworm tron deathmatch foodmatch multifood timematch'],
271 $data->{levels} = [];
272 for my $modes (@VARMODES) {
273 my $variant = shift @$modes;
274 $offset = min(map { $data->{moderef}->{offset}->{$_} } @$modes) - $offsetbase;
275 my $amount = $variant eq 'single' ? 100 : max(map { $data->{moderef}->{end}->{$_} } @$modes);
277 my @varform = @LEVELFORM;
278 $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
279 unshift @varform, name => 'Z*' unless $variant eq 'single';
280 $varform[-1]->[0] = 1 if $variant eq 'race';
281 $varform[-1]->[0] = 2 if $variant eq 'ctf';
283 while ($offset < length $data->{leveldata}) {
284 last if substr($data->{leveldata}, $offset, 1) eq chr(255);
286 # find references to this level offset, and set start number to matching modes
287 while (my ($mode, $location) = each %{ $data->{moderef}->{offset} }) {
288 $location == $offset + $offsetbase or next;
289 $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
292 my $level = Shiar_Parse::Nested->unpack(
293 [@varform], substr $data->{leveldata}, $offset
295 my $size = 8 # unpack length (ugh, ugly recalculation)
296 + (defined $level->{name} ? 1 + length $level->{name} : 0)
297 + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
298 + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
299 + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
300 + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
301 $level->{size} = $size;
302 $level->{offset} = $offset + $offsetbase;
304 # add objects until terminator
305 $level->{objects} = [];
306 while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
307 push @{ $level->{objects} }, Shiar_Parse::Nested->unpack(
308 [@OBJECTFORM], substr($data->{leveldata}, $offset+$size, 5)
313 # add parsed level and advance
314 push @{ $data->{levels} }, $level;
316 last if ++$data->{levelcount}->{$variant} >= $amount;
321 $data->{moderef}->{end}->{single} > 0, # singleplayer slot if any levels
322 $data->{moderef}->{end}->{peaworm}, # one for each peaworm arena
323 $data->{moderef}->{end}->{tron}, # idem for tron
325 $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
326 $data->{enddata} = substr delete($data->{leveldata}), $offset, -5 * $slots; #XXX
327 $data->{format} = '86s';
332 package Shiar_Parse::Nested;
335 my ($self, $format) = @_;
336 # total (flattened) unpack template from nested format definitions
337 return join '', map {
338 my $value = $format->[-($_ << 1) - 1];
339 if (ref $value eq 'ARRAY') {
340 my $count = $value->[0];
341 $value = $self->template($value);
342 $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
343 : $count."X[$count]$count/($value)";
346 $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e; # length prefix
349 } reverse 0 .. ($#$format - 1) >> 1;
353 my ($self, $format, $data) = @_;
354 # map flat results into a named and nested hash
356 while (my ($field, $template) = splice @$format, 0, 2) {
357 if (ref $template eq 'ARRAY') {
358 my ($count, @subformat) = @$template;
359 my $max = $count =~ s/^(\d+)// ? $1 : 0;
360 $count = !$count ? $max
361 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
362 $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
363 splice @{ $res{$field} }, $count if $max > $count;
364 $res{$field} = $res{$field}->[0] if $max == 1;
367 elsif ($template =~ /^Ca/) {
368 $data->[0] = CORE::unpack 'C/a', $data->[0];
370 $res{$field} = shift @$data;
376 my ($self, $format, $input) = @_;
377 my @data = CORE::unpack $self->template($format), $input;
378 return $self->convert($format, \@data);
384 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
385 my @ENDTYPE = ('none', 'message', 'small message');
389 my @objtypes = map { $_->{type} } @$objects;
391 $count{$_}++ for @objtypes;
392 return (@objtypes > 1 && keys %count == 1 && 'all ') . join(', ',
393 map { $OBJTYPE[$_] ? $OBJTYPE[$_] . ($count{$_} > 1 && 's') : $_ }
398 # read and parse all input data
401 my $rawdata = readline;
402 if (substr($rawdata, 0, 11) eq "**TI86**\032\012\000") {
403 # compiled calculator file
404 $data = Shiar_Parse::WormyLevel->read($rawdata);
406 elsif (substr($rawdata, 0, 8) eq 'WormEdit') {
407 # original wormedit source
408 $data = Shiar_Parse::WormEdit->read($rawdata);
411 die "Unrecognised file type\n";
414 # output with user-preferred formatting
416 # full data in yaml (human-readable) formatting
418 local $YAML::CompressSeries;
419 $YAML::CompressSeries = 0;
420 my $yml = "# Wormy levelset\n" . YAML::Dump($data);
422 # inline format of short hashes
424 ^(\ *) - \n # array indicator
425 ((?:\1\ \ [a-z0-9]{1,5}:\ *\d+\n)+) # simple hash declaration
426 (?!\1\ ) # no further children
428 my ($indent, $value) = ($1, $2);
432 "$indent- {$value}\n";
439 print " ($data->{description})" if defined $data->{description};
441 printf "File version: %s\n", "$data->{format} v$data->{version}";
442 printf "Defaults: %s\n", join('; ',
443 'sprite ' . scalar @{ $data->{sprite} },
444 defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
448 for my $variant (qw/single multi race ctf/) {
449 my $count = $data->{levelcount}->{$variant};
451 printf '%s (%s)', ucfirst $variant, $count // 'invalid';
454 for (0 .. $count - 1) {
455 my $level = $data->{levels}->[$_ + $startnr];
456 printf("\n- %-22s%4s:%3s+%2s%3s %3sx%-3s%s",
457 $level->{id} || $level->{name} || '#'.($_+1),
458 @$level{qw/size bsize growth/},
459 $variant eq 'single' && "x$level->{peas}",
460 @$level{qw/width height/},
461 join(';', map {" $_"} grep {$_}
462 @{$level->{objects}} && sprintf('%2d object%s (%s)',
463 scalar @{$level->{objects}}, @{$level->{objects}} != 1 && 's',
464 objsummary($level->{objects}),
466 $level->{sprite} && @{$level->{sprite}} && sprintf('sprite %d',
467 scalar @{$level->{sprite}},
469 $level->{balls} && @{$level->{balls}} && sprintf('%d bounc%s',
470 scalar @{$level->{balls}}, @{$level->{balls}} == 1 ? 'y' : 'ies',
479 printf("-- %-21s%4s: %s (%s)\n",
481 defined $data->{enddata} ? length $data->{enddata} : '?',
482 defined $data->{endtype} ? $ENDTYPE[$data->{endtype}] || 'unknown' : 'code',
483 $data->{endstr} // '?',
484 ) if $variant eq 'single';
492 parse-wormedit - Wormy level data parser
496 parse-wormedit [--raw] <input.lvl>
500 Reads Wormy levels (either original WormEdit source or compiled TI-86 string)
501 from STDIN or given file, and outputs contents, summarised or in full.
505 Mischa POSLAWSKY <wormy@shiar.org>