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);
169 my ($self, $input) = @_;
170 my ($psize, $ptype, $size, $type, $vsize, $dsize, $id, $version) = unpack q{
171 x11 x42 # file signature and comment
172 S a2 S a2 # file size, type; data size, type
174 S S # var size; content size
178 or die "Not a calculator string, thus cannot be a Wormy level file\n";
180 or warn "File size ($size) does not correspond with data size ($psize)\n";
182 or die "Not a calculator string, thus cannot be a Wormy level file\n";
183 $size == $vsize and $vsize == $dsize+2
184 or warn "Mismatch in string data size declarations\n";
185 # substr($input, -2) eq $CHECKSUM
187 $input = substr $input, 73, -2;
189 or die "Wormy level identifier not found\n";
192 warn "Override version $version to $opt{version}\n";
193 $version = $opt{version};
195 elsif ($version == 95) {
196 # level offset instead of description byte
197 $version-- if (unpack('x2Z*x2xC', $input))[1] == 0xF4;
198 warn "Ambiguous file version 95; guessing subversion $version\n";
211 offset => [1, map {$_ => 'S'} @$_], # byte location of start
212 end => [1, map {$_ => 'C'} @$_],
214 [qw/single peaworm tron deathmatch foodmatch multifood timematch race ctf/]
216 theanswer => 'C', # 42
258 my $offsetbase = 0xF080;
264 $offsetbase = 0xF400;
266 splice @FORMAT, 6, 2;
267 ref $_ and splice(@$_, -8, 2) for @{ $FORMAT[9] }; # no multifood
268 splice @FORMAT, 10, 2; # no reserved byte
271 $FORMAT[5] = 'C/a'; # length-preceding name
272 splice @FORMAT, 10, 2; # no default sprite
274 $_->[5] = $_->[7]; # no tron; deathmatch instead
275 $_->[7] = $_->[9]; # foodmatch instead
276 $_->[9] = 'linkmatch'; # replaces timematch
277 $_->[11] = $_->[13]; # race
278 $_->[13] = $_->[15]; # ctf
279 $_->[15] = 'domination';
280 } for @{ $FORMAT[9] }; # no multifood
281 push @LEVELFORM, "object$_" => ['C',
282 map {$_ => 'C'} qw(x1 y1 x2 y2)
283 ] for qw(lines boxes);
286 die "Unsupported level version $version\n";
290 my $data = Shiar_Parse::Nested->unpack(\@FORMAT, $input);
292 $offsetbase += 1 + @{ $data->{sprite} } if $data->{sprite};
293 $data->{moderef}->{offset}->{single} == $offsetbase
294 or warn "First singleplayer level is not in front\n";
297 $data->{moderef}->{end}->{single} > 0, # singleplayer slot if any levels
298 $data->{moderef}->{end}->{peaworm}, # one for each peaworm arena
299 $data->{moderef}->{end}->{tron}, # idem for tron
301 $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
302 $data->{format} = '86s';
306 [qw'multi peaworm tron deathmatch foodmatch multifood timematch'],
311 $data->{levels} = [];
312 for my $modes (@VARMODES) {
313 my $variant = shift @$modes;
314 my @modeoffsets = grep {defined} #TODO: comment
315 map { $data->{moderef}->{offset}->{$_} } @$modes;
316 @modeoffsets or next;
317 $data->{levelcount}->{$variant} = 0;
318 $offset = min(grep {$_} @modeoffsets) or next;
319 $offset -= $offsetbase;
320 my $amount = $variant eq 'single' ? 100
321 : max(grep {defined} map { $data->{moderef}->{end}->{$_} } @$modes);
323 my @varform = @LEVELFORM;
324 $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
325 unshift @varform, name => 'Z*' unless $variant eq 'single' or $version <= 91;
326 $varform[-1]->[0] = 1 if $variant eq 'race' and $version > 91;
327 $varform[-1]->[0] = 2 if $variant eq 'ctf';
329 while ($offset < length $data->{leveldata}) {
330 last if substr($data->{leveldata}, $offset, 1) eq chr(255);
332 # find references to this level offset, and set start number to matching modes
333 while (my ($mode, $location) = each %{ $data->{moderef}->{offset} }) {
334 $location == $offset + $offsetbase or next;
335 $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
338 my $level = Shiar_Parse::Nested->unpack(
339 [@varform], substr $data->{leveldata}, $offset
341 my $size = 8 # unpack length (ugh, ugly recalculation)
342 + (defined $level->{name} ? 1 + length $level->{name} : 0)
343 + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
344 + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
345 + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
346 + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
347 $level->{size} = $size;
348 $level->{offset} = $offset + $offsetbase;
350 # add objects until terminator
351 $level->{objects} = [];
352 if ($version <= 91) {
353 push @{ $level->{objects} }, { %$_, type => 2 } for map { $level->{$_} ? @{ $level->{$_} } : () } qw(objectlines);
354 push @{ $level->{objects} }, { %$_, type => 3 } for map { $level->{$_} ? @{ $level->{$_} } : () } qw(objectboxes);
355 $size += 1 + 4 * scalar @{ $level->{objects} };
358 while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
359 push @{ $level->{objects} }, Shiar_Parse::Nested->unpack(
360 [@OBJECTFORM], substr($data->{leveldata}, $offset+$size, 5)
366 # add parsed level and advance
367 push @{ $data->{levels} }, $level;
369 last if ++$data->{levelcount}->{$variant} >= $amount;
372 if ($variant eq 'single') {
374 $data->{finish}->{code} =
375 my $code = substr $data->{leveldata}, $offset, -5*$slots;
380 chr 0x21, # ld hl, MESSAGE
381 pack('v', $offsetbase + $offset + 9),
383 0xCD, 0x37, 0x4A, # call _puts
384 0xC3, 0xAA, 0x55, # jp _getkey
389 0x21, 0, 0x1C, # ld hl, $POS
390 0x22, 0x7C, 0xC3, # ld (_penCol), hl
391 0x21, # ld hl, MESSAGE
393 pack('v', $offsetbase + $offset + 15),
395 0xCD, 0xA5, 0x4A, # call _vputs
396 0xC3, 0xAA, 0x55, # jp _getkey
400 while (my ($finish, $match) = each %FINISHCODE) {
401 $match eq substr $code, 0, length $match or next;
402 $data->{finish}->{type} = $finish and
403 $data->{finish}->{message} = unpack 'Z*', substr($code, length $match);
413 package Shiar_Parse::Nested;
416 my ($self, $format) = @_;
417 # total (flattened) unpack template from nested format definitions
418 return join '', map {
419 my $value = $format->[-($_ << 1) - 1];
420 if (ref $value eq 'ARRAY') {
421 my $count = $value->[0];
422 $value = $self->template($value);
423 $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
424 : $count."X[$count]$count/($value)";
427 $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e; # length prefix
430 } reverse 0 .. ($#$format - 1) >> 1;
434 my ($self, $format, $data) = @_;
435 # map flat results into a named and nested hash
437 while (my ($field, $template) = splice @$format, 0, 2) {
438 if (ref $template eq 'ARRAY') {
439 my ($count, @subformat) = @$template;
440 my $max = $count =~ s/^(\d+)// ? $1 : 0;
441 $count = !$count ? $max
442 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
443 $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
444 splice @{ $res{$field} }, $count if $max > $count;
445 $res{$field} = $res{$field}->[0] if $max == 1;
448 elsif ($template =~ /^Ca/) {
449 $data->[0] = CORE::unpack 'C/a', $data->[0];
451 $res{$field} = shift @$data;
457 my ($self, $format, $input) = @_;
458 my @data = CORE::unpack $self->template($format), $input;
459 return $self->convert($format, \@data);
465 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
466 my @ENDTYPE = ('none', 'message', 'small message');
470 my @objtypes = map { $_->{type} } @$objects;
472 $count{$_}++ for @objtypes;
473 return (@objtypes > 1 && keys %count == 1 && 'all ') . join(', ',
474 map { $OBJTYPE[$_] ? $OBJTYPE[$_] . ($count{$_} > 1 && 's') : $_ }
479 # read and parse all input data
482 my $rawdata = readline;
483 if (substr($rawdata, 0, 11) eq "**TI86**\032\012\000") {
484 # compiled calculator file
485 $data = Shiar_Parse::WormyLevel->read($rawdata);
487 elsif (substr($rawdata, 0, 8) eq 'WormEdit') {
488 # original wormedit source
489 $data = Shiar_Parse::WormEdit->read($rawdata);
492 die "Unrecognised file type\n";
495 # output with user-preferred formatting
497 # full data in yaml (human-readable) formatting
499 local $YAML::CompressSeries;
500 $YAML::CompressSeries = 0;
501 my $yml = "# Wormy levelset\n" . YAML::Dump($data);
503 # inline format of short hashes
505 ^(\ *) - \n # array indicator
506 ((?:\1\ \ [a-z0-9]{1,5}:\ *\d+\n)+) # simple hash declaration
507 (?!\1\ ) # no further children
509 my ($indent, $value) = ($1, $2);
513 "$indent- {$value}\n";
520 print " ($data->{description})" if defined $data->{description};
522 printf "File version: %s\n", "$data->{format} v$data->{version}";
523 printf "Defaults: %s\n", join('; ',
524 $data->{sprite} ? 'sprite ' . scalar @{ $data->{sprite} } : (),
525 defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
529 for my $variant (qw/single multi race ctf/) {
530 my $count = $data->{levelcount}->{$variant};
532 printf '%s (%s)', ucfirst $variant, $count // 'invalid';
535 for (0 .. $count - 1) {
536 my $level = $data->{levels}->[$_ + $startnr];
537 printf("\n- %-22s%4s:%3s+%2s%3s %3sx%-3s%s",
538 $level->{id} || $level->{name} || '#'.($_+1),
539 @$level{qw/size bsize growth/},
540 $variant eq 'single' && "x$level->{peas}",
541 @$level{qw/width height/},
542 join(';', map {" $_"} grep {$_}
543 @{$level->{objects}} && sprintf('%2d object%s (%s)',
544 scalar @{$level->{objects}}, @{$level->{objects}} != 1 && 's',
545 objsummary($level->{objects}),
547 $level->{sprite} && @{$level->{sprite}} && sprintf('sprite %d',
548 scalar @{$level->{sprite}},
550 $level->{balls} && @{$level->{balls}} && sprintf('%d bounc%s',
551 scalar @{$level->{balls}}, @{$level->{balls}} == 1 ? 'y' : 'ies',
560 printf("-- %-21s%4s: %s (%s)\n",
562 defined $data->{finish}->{code}
563 ? length $data->{finish}->{code} : '?',
564 defined $data->{finish}->{type}
565 ? $ENDTYPE[$data->{finish}->{type}] || 'unknown' : 'code',
566 $data->{finish}->{message} // '?',
567 ) if $variant eq 'single';
575 parse-wormedit - Wormy level data parser
579 parse-wormedit [--raw] <input.lvl>
583 Reads Wormy levels (either original WormEdit source or compiled TI-86 string)
584 from STDIN or given file, and outputs contents, summarised or in full.
588 Mischa POSLAWSKY <wormy@shiar.org>