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 ref $_ and splice(@$_, -8, 2) for @{ $FORMAT[11] }; # no multifood
267 splice @FORMAT, 12, 2; # no reserved byte
269 splice @FORMAT, 6, 2; # no description
272 $FORMAT[5] = 'C/a'; # length-preceding name
273 splice @FORMAT, 10, 2; # no default sprite
275 $_->[5] = $_->[7]; # no tron; deathmatch instead
276 $_->[7] = $_->[9]; # foodmatch instead
277 $_->[9] = 'linkmatch'; # replaces timematch
278 $_->[11] = $_->[13]; # race
279 $_->[13] = $_->[15]; # ctf
280 $_->[15] = 'domination';
281 } for @{ $FORMAT[9] }; # no multifood
282 push @LEVELFORM, "object$_" => ['C',
283 map {$_ => 'C'} qw(x1 y1 x2 y2)
284 ] for qw(lines boxes);
287 die "Unsupported level version $version\n";
291 my $data = Shiar_Parse::Nested->unpack(\@FORMAT, $input);
293 $offsetbase += 1 + @{ $data->{sprite} } if $data->{sprite};
294 $data->{moderef}->{offset}->{single} == $offsetbase
295 or warn "First singleplayer level is not in front\n";
298 $data->{moderef}->{end}->{single} > 0, # singleplayer slot if any levels
299 $data->{moderef}->{end}->{peaworm}, # one for each peaworm arena
300 $data->{moderef}->{end}->{tron}, # idem for tron
302 $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
303 $data->{format} = '86s';
307 [qw'multi peaworm tron deathmatch foodmatch multifood timematch'],
312 $data->{levels} = [];
313 for my $modes (@VARMODES) {
314 my $variant = shift @$modes;
315 my @modeoffsets = grep {defined} #TODO: comment
316 map { $data->{moderef}->{offset}->{$_} } @$modes;
317 @modeoffsets or next;
318 $data->{levelcount}->{$variant} = 0;
319 $offset = min(grep {$_} @modeoffsets) or next;
320 $offset -= $offsetbase;
321 my $amount = $variant eq 'single' ? 100
322 : max(grep {defined} map { $data->{moderef}->{end}->{$_} } @$modes);
324 my @varform = @LEVELFORM;
325 $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
326 unshift @varform, name => 'Z*' unless $variant eq 'single' or $version <= 91;
327 $varform[-1]->[0] = 1 if $variant eq 'race' and $version > 91;
328 $varform[-1]->[0] = 2 if $variant eq 'ctf';
330 while ($offset < length $data->{leveldata}) {
331 last if substr($data->{leveldata}, $offset, 1) eq chr(255);
333 # find references to this level offset, and set start number to matching modes
334 while (my ($mode, $location) = each %{ $data->{moderef}->{offset} }) {
335 $location == $offset + $offsetbase or next;
336 $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
339 my $level = Shiar_Parse::Nested->unpack(
340 [@varform], substr $data->{leveldata}, $offset
342 my $size = 8 # unpack length (ugh, ugly recalculation)
343 + (defined $level->{name} ? 1 + length $level->{name} : 0)
344 + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
345 + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
346 + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
347 + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
348 $level->{size} = $size;
349 $level->{offset} = $offset + $offsetbase;
351 # add objects until terminator
352 $level->{objects} = [];
353 if ($version <= 91) {
354 push @{ $level->{objects} }, { %$_, type => 2 } for map { $level->{$_} ? @{ $level->{$_} } : () } qw(objectlines);
355 push @{ $level->{objects} }, { %$_, type => 3 } for map { $level->{$_} ? @{ $level->{$_} } : () } qw(objectboxes);
356 $size += 1 + 4 * scalar @{ $level->{objects} };
359 while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
360 push @{ $level->{objects} }, Shiar_Parse::Nested->unpack(
361 [@OBJECTFORM], substr($data->{leveldata}, $offset+$size, 5)
367 # add parsed level and advance
368 push @{ $data->{levels} }, $level;
370 last if ++$data->{levelcount}->{$variant} >= $amount;
373 if ($variant eq 'single') {
375 $data->{finish}->{code} =
376 my $code = substr $data->{leveldata}, $offset, -5*$slots;
381 chr 0x21, # ld hl, MESSAGE
382 pack('v', $offsetbase + $offset + 9),
384 0xCD, 0x37, 0x4A, # call _puts
385 0xC3, 0xAA, 0x55, # jp _getkey
390 0x21, 0, 0x1C, # ld hl, $POS
391 0x22, 0x7C, 0xC3, # ld (_penCol), hl
392 0x21, # ld hl, MESSAGE
394 pack('v', $offsetbase + $offset + 15),
396 0xCD, 0xA5, 0x4A, # call _vputs
397 0xC3, 0xAA, 0x55, # jp _getkey
401 while (my ($finish, $match) = each %FINISHCODE) {
402 $match eq substr $code, 0, length $match or next;
403 $data->{finish}->{type} = $finish and
404 $data->{finish}->{message} = unpack 'Z*', substr($code, length $match);
414 package Shiar_Parse::Nested;
417 my ($self, $format) = @_;
418 # total (flattened) unpack template from nested format definitions
419 return join '', map {
420 my $value = $format->[-($_ << 1) - 1];
421 if (ref $value eq 'ARRAY') {
422 my $count = $value->[0];
423 $value = $self->template($value);
424 $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
425 : $count."X[$count]$count/($value)";
428 $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e; # length prefix
431 } reverse 0 .. ($#$format - 1) >> 1;
435 my ($self, $format, $data) = @_;
436 # map flat results into a named and nested hash
438 while (my ($field, $template) = splice @$format, 0, 2) {
439 if (ref $template eq 'ARRAY') {
440 my ($count, @subformat) = @$template;
441 my $max = $count =~ s/^(\d+)// ? $1 : 0;
442 $count = !$count ? $max
443 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
444 $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
445 splice @{ $res{$field} }, $count if $max > $count;
446 $res{$field} = $res{$field}->[0] if $max == 1;
449 elsif ($template =~ /^Ca/) {
450 $data->[0] = CORE::unpack 'C/a', $data->[0];
452 $res{$field} = shift @$data;
458 my ($self, $format, $input) = @_;
459 my @data = CORE::unpack $self->template($format), $input;
460 return $self->convert($format, \@data);
466 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
467 my @ENDTYPE = ('none', 'message', 'small message');
471 my @objtypes = map { $_->{type} } @$objects;
473 $count{$_}++ for @objtypes;
474 return (@objtypes > 1 && keys %count == 1 && 'all ') . join(', ',
475 map { $OBJTYPE[$_] ? $OBJTYPE[$_] . ($count{$_} > 1 && 's') : $_ }
480 # read and parse all input data
483 my $rawdata = readline;
484 if (substr($rawdata, 0, 11) eq "**TI86**\032\012\000") {
485 # compiled calculator file
486 $data = Shiar_Parse::WormyLevel->read($rawdata);
488 elsif (substr($rawdata, 0, 8) eq 'WormEdit') {
489 # original wormedit source
490 $data = Shiar_Parse::WormEdit->read($rawdata);
493 die "Unrecognised file type\n";
496 # output with user-preferred formatting
498 # full data in yaml (human-readable) formatting
500 local $YAML::CompressSeries;
501 $YAML::CompressSeries = 0;
502 my $yml = "# Wormy levelset\n" . YAML::Dump($data);
504 # inline format of short hashes
506 ^(\ *) - \n # array indicator
507 ((?:\1\ \ [a-z0-9]{1,5}:\ *\d+\n)+) # simple hash declaration
508 (?!\1\ ) # no further children
510 my ($indent, $value) = ($1, $2);
514 "$indent- {$value}\n";
521 print " ($data->{description})" if defined $data->{description};
523 printf "File version: %s\n", "$data->{format} v$data->{version}";
524 printf "Defaults: %s\n", join('; ',
525 $data->{sprite} ? 'sprite ' . scalar @{ $data->{sprite} } : (),
526 defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
530 for my $variant (qw/single multi race ctf/) {
531 my $count = $data->{levelcount}->{$variant};
533 printf '%s (%s)', ucfirst $variant, $count // 'invalid';
536 for (0 .. $count - 1) {
537 my $level = $data->{levels}->[$_ + $startnr];
538 printf("\n- %-22s%4s:%3s+%2s%3s %3sx%-3s%s",
539 $level->{id} || $level->{name} || '#'.($_+1),
540 @$level{qw/size bsize growth/},
541 $variant eq 'single' && "x$level->{peas}",
542 @$level{qw/width height/},
543 join(';', map {" $_"} grep {$_}
544 @{$level->{objects}} && sprintf('%2d object%s (%s)',
545 scalar @{$level->{objects}}, @{$level->{objects}} != 1 && 's',
546 objsummary($level->{objects}),
548 $level->{sprite} && @{$level->{sprite}} && sprintf('sprite %d',
549 scalar @{$level->{sprite}},
551 $level->{balls} && @{$level->{balls}} && sprintf('%d bounc%s',
552 scalar @{$level->{balls}}, @{$level->{balls}} == 1 ? 'y' : 'ies',
561 printf("-- %-21s%4s: %s (%s)\n",
563 defined $data->{finish}->{code}
564 ? length $data->{finish}->{code} : '?',
565 defined $data->{finish}->{type}
566 ? $ENDTYPE[$data->{finish}->{type}] || 'unknown' : 'code',
567 $data->{finish}->{message} // '?',
568 ) if $variant eq 'single';
576 parse-wormedit - Wormy level data parser
580 parse-wormedit [--raw] <input.lvl>
584 Reads Wormy levels (either original WormEdit source or compiled TI-86 string)
585 from STDIN or given file, and outputs contents, summarised or in full.
589 Mischa POSLAWSKY <wormy@shiar.org>