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,
63 levels => ['*', # levelcount->total actually
101 my ($self, $input) = @_;
102 my ($id, $version) = (substr($input, 0, 15), ord substr($input, 15, 1));
103 my $fileversion = $MAGICID{$id}
104 or die "File does not match any known WormEdit level header\n";
107 warn "Override version $version to $opt{version}\n";
108 $version = $opt{version};
110 elsif ($version != $fileversion) {
111 warn "Unexpected version $version (expecting $fileversion)\n";
113 elsif ($version == 95) {
114 # auto-detect exact variant
115 if (ord substr($input, 70, 1) ~~ [1 .. 8]) {
116 # valid sprite length instead of description byte
117 # (which is usually a letter or nul)
120 elsif (ord substr($input, 147, 1) == 0) {
121 # nul of finish type is 2 bytes later (unlike first char of message)
124 warn "Ambiguous file version 95; guessing subversion $version\n";
127 $fileversion += 100 if $fileversion < 90; # 93..95 came before 50..53
128 given ($fileversion) {
129 when (153) { } # current @FORMAT
130 $FORMAT[7] = 'Ca64'; # no reserved space after description
131 $FORMAT[15]->[-1] = 'Ca255'; # enddata
132 $FORMAT[-1]->[-1]->[0] = '32C'; # less objects
133 when ($version == 96) {
134 ref $_ and $_->[-1] = 'C' for @{ $FORMAT[11] }; # 9 moderefs
136 ref $_ and pop @$_ for @{ $FORMAT[11] }; # only 8 moderefs
137 splice @FORMAT, 6, 2 if $version <= 94; # earlier version without description
139 splice @{ $FORMAT[7] }, 4, 2; # no race
140 splice @{ $FORMAT[13] }, 4, 2; # no enddata
141 splice @{ $FORMAT[-1] }, 1, 2; # no name
143 splice @FORMAT, 14, 2; # no hiname
144 $FORMAT[-1]->[0] = 64; # constant amount of levels
147 die "Cannot parse data for Wormedit $fileversion/$version\n";
151 # convert to an easily accessible hash
152 my @values = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', $input;
153 my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@values);
154 warn "Trailing data left unparsed\n" if grep {length} @values;
155 $data->{format} = 'WormEdit';
160 package Shiar_Parse::WormyLevel;
165 use List::Util qw(sum min max);
168 my ($self, $input) = @_;
169 my ($psize, $ptype, $size, $type, $vsize, $dsize, $id, $subid) = unpack q{
170 x11 x42 # file signature and comment
171 S a2 S a2 # file size, type; data size, type
173 S S # var size; content size
177 or die "Not a calculator string, thus cannot be a Wormy level file\n";
179 or warn "File size ($size) does not correspond with data size ($psize)\n";
181 or die "Not a calculator string, thus cannot be a Wormy level file\n";
182 $size == $vsize and $vsize == $dsize+2
183 or warn "Mismatch in string data size declarations\n";
184 # substr($input, -2) eq $CHECKSUM
186 $input = substr $input, 73, -2;
188 or die "Wormy level identifier not found\n";
199 offset => [1, map {$_ => 'S'} @$_], # byte location of start
200 end => [1, map {$_ => 'C'} @$_],
202 [qw/single peaworm tron deathmatch foodmatch multifood timematch race ctf/]
204 theanswer => 'C', # 42
252 ref $_ and splice @$_, -2 for @{ $FORMAT[11] }; # only 8 moderefs
253 splice @FORMAT, 12, 2; # no reserved byte
256 die "Unsupported level version $subid\n";
260 my $data = Shiar_Parse::Nested->unpack(\@FORMAT, $input);
262 my $offsetbase = 0xF080 + @{ $data->{sprite} } + 1;
263 $data->{moderef}->{offset}->{single} == $offsetbase
264 or warn "First singleplayer level is not in front\n";
268 [qw'multi peaworm tron deathmatch foodmatch multifood timematch'],
273 $data->{levels} = [];
274 for my $modes (@VARMODES) {
275 my $variant = shift @$modes;
276 $offset = min(map { $data->{moderef}->{offset}->{$_} } @$modes) - $offsetbase;
277 my $amount = $variant eq 'single' ? 100 : max(map { $data->{moderef}->{end}->{$_} } @$modes);
279 my @varform = @LEVELFORM;
280 $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
281 unshift @varform, name => 'Z*' unless $variant eq 'single';
282 $varform[-1]->[0] = 1 if $variant eq 'race';
283 $varform[-1]->[0] = 2 if $variant eq 'ctf';
285 while ($offset < length $data->{leveldata}) {
286 last if substr($data->{leveldata}, $offset, 1) eq chr(255);
288 # find references to this level offset, and set start number to matching modes
289 while (my ($mode, $location) = each %{ $data->{moderef}->{offset} }) {
290 $location == $offset + $offsetbase or next;
291 $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
294 my $level = Shiar_Parse::Nested->unpack(
295 [@varform], substr $data->{leveldata}, $offset
297 my $size = 8 # unpack length (ugh, ugly recalculation)
298 + (defined $level->{name} ? 1 + length $level->{name} : 0)
299 + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
300 + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
301 + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
302 + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
303 $level->{size} = $size;
304 $level->{offset} = $offset + $offsetbase;
306 # add objects until terminator
307 $level->{objects} = [];
308 while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
309 push @{ $level->{objects} }, Shiar_Parse::Nested->unpack(
310 [@OBJECTFORM], substr($data->{leveldata}, $offset+$size, 5)
315 # add parsed level and advance
316 push @{ $data->{levels} }, $level;
318 last if ++$data->{levelcount}->{$variant} >= $amount;
323 $data->{moderef}->{end}->{single} > 0, # singleplayer slot if any levels
324 $data->{moderef}->{end}->{peaworm}, # one for each peaworm arena
325 $data->{moderef}->{end}->{tron}, # idem for tron
327 $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
328 $data->{finish}->{code} = substr delete($data->{leveldata}), $offset, -5 * $slots; #XXX
329 $data->{format} = '86s';
334 package Shiar_Parse::Nested;
337 my ($self, $format) = @_;
338 # total (flattened) unpack template from nested format definitions
339 return join '', map {
340 my $value = $format->[-($_ << 1) - 1];
341 if (ref $value eq 'ARRAY') {
342 my $count = $value->[0];
343 $value = $self->template($value);
344 $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
345 : $count."X[$count]$count/($value)";
348 $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e; # length prefix
351 } reverse 0 .. ($#$format - 1) >> 1;
355 my ($self, $format, $data) = @_;
356 # map flat results into a named and nested hash
358 while (my ($field, $template) = splice @$format, 0, 2) {
359 if (ref $template eq 'ARRAY') {
360 my ($count, @subformat) = @$template;
361 my $max = $count =~ s/^(\d+)// ? $1 : 0;
362 $count = !$count ? $max
363 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
364 $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
365 splice @{ $res{$field} }, $count if $max > $count;
366 $res{$field} = $res{$field}->[0] if $max == 1;
369 elsif ($template =~ /^Ca/) {
370 $data->[0] = CORE::unpack 'C/a', $data->[0];
372 $res{$field} = shift @$data;
378 my ($self, $format, $input) = @_;
379 my @data = CORE::unpack $self->template($format), $input;
380 return $self->convert($format, \@data);
386 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
387 my @ENDTYPE = ('none', 'message', 'small message');
391 my @objtypes = map { $_->{type} } @$objects;
393 $count{$_}++ for @objtypes;
394 return (@objtypes > 1 && keys %count == 1 && 'all ') . join(', ',
395 map { $OBJTYPE[$_] ? $OBJTYPE[$_] . ($count{$_} > 1 && 's') : $_ }
400 # read and parse all input data
403 my $rawdata = readline;
404 if (substr($rawdata, 0, 11) eq "**TI86**\032\012\000") {
405 # compiled calculator file
406 $data = Shiar_Parse::WormyLevel->read($rawdata);
408 elsif (substr($rawdata, 0, 8) eq 'WormEdit') {
409 # original wormedit source
410 $data = Shiar_Parse::WormEdit->read($rawdata);
413 die "Unrecognised file type\n";
416 # output with user-preferred formatting
418 # full data in yaml (human-readable) formatting
420 local $YAML::CompressSeries;
421 $YAML::CompressSeries = 0;
422 my $yml = "# Wormy levelset\n" . YAML::Dump($data);
424 # inline format of short hashes
426 ^(\ *) - \n # array indicator
427 ((?:\1\ \ [a-z0-9]{1,5}:\ *\d+\n)+) # simple hash declaration
428 (?!\1\ ) # no further children
430 my ($indent, $value) = ($1, $2);
434 "$indent- {$value}\n";
441 print " ($data->{description})" if defined $data->{description};
443 printf "File version: %s\n", "$data->{format} v$data->{version}";
444 printf "Defaults: %s\n", join('; ',
445 'sprite ' . scalar @{ $data->{sprite} },
446 defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
450 for my $variant (qw/single multi race ctf/) {
451 my $count = $data->{levelcount}->{$variant};
453 printf '%s (%s)', ucfirst $variant, $count // 'invalid';
456 for (0 .. $count - 1) {
457 my $level = $data->{levels}->[$_ + $startnr];
458 printf("\n- %-22s%4s:%3s+%2s%3s %3sx%-3s%s",
459 $level->{id} || $level->{name} || '#'.($_+1),
460 @$level{qw/size bsize growth/},
461 $variant eq 'single' && "x$level->{peas}",
462 @$level{qw/width height/},
463 join(';', map {" $_"} grep {$_}
464 @{$level->{objects}} && sprintf('%2d object%s (%s)',
465 scalar @{$level->{objects}}, @{$level->{objects}} != 1 && 's',
466 objsummary($level->{objects}),
468 $level->{sprite} && @{$level->{sprite}} && sprintf('sprite %d',
469 scalar @{$level->{sprite}},
471 $level->{balls} && @{$level->{balls}} && sprintf('%d bounc%s',
472 scalar @{$level->{balls}}, @{$level->{balls}} == 1 ? 'y' : 'ies',
481 printf("-- %-21s%4s: %s (%s)\n",
483 defined $data->{finish}->{code}
484 ? length $data->{finish}->{code} : '?',
485 defined $data->{finish}->{type}
486 ? $ENDTYPE[$data->{finish}->{type}] || 'unknown' : 'code',
487 $data->{finish}->{message} // '?',
488 ) if $variant eq 'single';
496 parse-wormedit - Wormy level data parser
500 parse-wormedit [--raw] <input.lvl>
504 Reads Wormy levels (either original WormEdit source or compiled TI-86 string)
505 from STDIN or given file, and outputs contents, summarised or in full.
509 Mischa POSLAWSKY <wormy@shiar.org>