3 # converter from Type 1 MIDI files to CFG files that control bots with the Tuba and other weapons for percussion (requires g_weaponarena all)
11 # workaround for possible refire time problems
12 use constant SYS_TICRATE => 0.033333;
13 #use constant SYS_TICRATE => 0;
15 use constant MIDI_FIRST_NONCHANNEL => 17;
16 use constant MIDI_DRUMS_CHANNEL => 10;
18 die "Usage: $0 filename.conf midifile1 transpose1 midifile2 transpose2 ..."
19 unless @ARGV > 1 and @ARGV % 2;
21 my $timeoffset_preinit = 2;
22 my $timeoffset_postinit = 2;
23 my $timeoffset_predone = 2;
24 my $timeoffset_postdone = 2;
25 my $timeoffset_preintermission = 2;
26 my $timeoffset_postintermission = 2;
27 my $time_forgetfulness = 1.5;
29 my ($config, @midilist) = @ARGV;
33 return map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, rand] } @_;
39 my ($dest, $src) = @_;
40 if(ref $src eq 'HASH')
46 $dest->{$_} = override $dest->{$_}, $src->{$_};
49 elsif(ref $src eq 'ARRAY')
55 push @$dest, override undef, $_;
60 $dest = Storable::dclone $src;
72 my @busybots_allocated;
76 my $lowestnotestart = undef;
85 my $currentbot = undef;
86 my $appendref = undef;
95 my @cmd = split /\s+/, $_;
96 if($cmd[0] eq 'super')
98 push @$appendref, @$super
101 elsif($cmd[0] eq 'percussion') # simple import
103 push @$appendref, @{$currentbot->{percussion}->{$cmd[1]}};
107 push @$appendref, \@cmd;
114 my $base = $bots{$1};
115 $currentbot = override $currentbot, $base;
117 elsif(/^count (\d+)/)
119 $currentbot->{count} = $1;
121 elsif(/^transpose (\d+)/)
123 $currentbot->{transpose} ||= 0;
124 $currentbot->{transpose} += $1;
126 elsif(/^channels (.*)/)
128 $currentbot->{channels} = { map { $_ => 1 } split /\s+/, $1 };
130 elsif(/^programs (.*)/)
132 $currentbot->{programs} = { map { $_ => 1 } split /\s+/, $1 };
136 $super = $currentbot->{init};
137 $currentbot->{init} = $appendref = [];
139 elsif(/^intermission$/)
141 $super = $currentbot->{intermission};
142 $currentbot->{intermission} = $appendref = [];
146 $super = $currentbot->{done};
147 $currentbot->{done} = $appendref = [];
149 elsif(/^note on (-?\d+)/)
151 $super = $currentbot->{notes_on}->{$1};
152 $currentbot->{notes_on}->{$1} = $appendref = [];
154 elsif(/^note off (-?\d+)/)
156 $super = $currentbot->{notes_off}->{$1};
157 $currentbot->{notes_off}->{$1} = $appendref = [];
159 elsif(/^percussion (\d+)/)
161 $super = $currentbot->{percussion}->{$1};
162 $currentbot->{percussion}->{$1} = $appendref = [];
166 $super = $currentbot->{vocals};
167 $currentbot->{vocals} = $appendref = [];
171 print "unknown command: $_\n";
176 $currentbot = ($bots{$1} ||= {count => 0});
180 $precommands .= "$1\n";
182 elsif(/^timeoffset_preinit (.*)/)
184 $timeoffset_preinit = $1;
186 elsif(/^timeoffset_postinit (.*)/)
188 $timeoffset_postinit = $1;
190 elsif(/^timeoffset_predone (.*)/)
192 $timeoffset_predone = $1;
194 elsif(/^timeoffset_postdone (.*)/)
196 $timeoffset_postdone = $1;
198 elsif(/^timeoffset_preintermission (.*)/)
200 $timeoffset_preintermission = $1;
202 elsif(/^timeoffset_postintermission (.*)/)
204 $timeoffset_postintermission = $1;
206 elsif(/^time_forgetfulness (.*)/)
208 $time_forgetfulness = $1;
212 print "unknown command: $_\n";
218 for(values %{$_->{notes_on}}, values %{$_->{percussion}})
220 my $t = $_->[0]->[0] eq 'time' ? $_->[0]->[1] : 0;
221 $lowestnotestart = $t if not defined $lowestnotestart or $t < $lowestnotestart;
227 my $busybots_orig = botconfig_read $config;
230 # returns: ($mintime, $maxtime, $busytime)
231 sub busybot_cmd_bot_cmdinfo(@)
237 my $busytime = undef;
241 if($_->[0] eq 'time')
244 if not defined $mintime or $_->[1] < $mintime;
245 $maxtime = $_->[1] + SYS_TICRATE
246 if not defined $maxtime or $_->[1] + SYS_TICRATE > $maxtime;
248 elsif($_->[0] eq 'busy')
250 $busytime = $_->[1] + SYS_TICRATE;
254 return ($mintime, $maxtime, $busytime);
257 sub busybot_cmd_bot_matchtime($$$@)
259 my ($bot, $targettime, $targetbusytime, @commands) = @_;
261 # I want to execute @commands so that I am free on $targettime and $targetbusytime
262 # when do I execute it then?
264 my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @commands;
266 my $tstart_max = defined $maxtime ? $targettime - $maxtime : $targettime;
267 my $tstart_busy = defined $busytime ? $targetbusytime - $busytime : $targettime;
269 return $tstart_max < $tstart_busy ? $tstart_max : $tstart_busy;
272 # TODO function to find out whether, and when, to insert a command before another command to make it possible
273 # (note-off before note-on)
275 sub busybot_cmd_bot_test($$$@)
277 my ($bot, $time, $force, @commands) = @_;
279 my $bottime = defined $bot->{timer} ? $bot->{timer} : -1;
280 my $botbusytime = defined $bot->{busytimer} ? $bot->{busytimer} : -1;
282 my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @commands;
284 if($time < $botbusytime)
286 warn "FORCE: $time < $botbusytime"
291 if(defined $mintime and $time + $mintime < $bottime)
293 warn "FORCE: $time + $mintime < $bottime"
301 sub busybot_cmd_bot_execute($$@)
303 my ($bot, $time, @commands) = @_;
307 if($_->[0] eq 'time')
309 $commands .= sprintf "sv_cmd bot_cmd %d wait_until %f\n", $bot->{id}, $time + $_->[1];
310 if($bot->{timer} > $time + $_->[1] + SYS_TICRATE)
312 #use Carp; carp "Negative wait: $bot->{timer} <= @{[$time + $_->[1] + SYS_TICRATE]}";
314 $bot->{timer} = $time + $_->[1] + SYS_TICRATE;
316 elsif($_->[0] eq 'busy')
318 $bot->{busytimer} = $time + $_->[1] + SYS_TICRATE;
320 elsif($_->[0] eq 'buttons')
322 my %buttons_release = %{$bot->{buttons} ||= {}};
326 delete $buttons_release{$1};
328 for(keys %buttons_release)
330 $commands .= sprintf "sv_cmd bot_cmd %d releasekey %s\n", $bot->{id}, $_;
331 delete $bot->{buttons}->{$_};
337 $commands .= sprintf "sv_cmd bot_cmd %d presskey %s\n", $bot->{id}, $_;
338 $bot->{buttons}->{$_} = 1;
341 elsif($_->[0] eq 'cmd')
343 $commands .= sprintf "sv_cmd bot_cmd %d %s\n", $bot->{id}, join " ", @{$_}[1..@$_-1];
345 elsif($_->[0] eq 'barrier')
347 $commands .= sprintf "sv_cmd bot_cmd %d barrier\n", $bot->{id};
348 $bot->{timer} = $bot->{busytimer} = 0;
349 undef $bot->{lastuse};
351 elsif($_->[0] eq 'raw')
353 $commands .= sprintf "%s\n", join " ", @{$_}[1..@$_-1];
360 my $intermissions = 0;
362 sub busybot_intermission_bot($)
365 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preintermission];
366 busybot_cmd_bot_execute $bot, 0, ['barrier'];
367 if($bot->{intermission})
369 busybot_cmd_bot_execute $bot, 0, @{$bot->{intermission}};
371 busybot_cmd_bot_execute $bot, 0, ['barrier'];
372 $notetime = $timeoffset_postintermission - $lowestnotestart;
376 sub busybot_note_off_bot($$$$)
378 my ($bot, $time, $channel, $note) = @_;
379 #print STDERR "note off $bot:$time:$channel:$note\n";
380 my ($busychannel, $busynote, $cmds) = @{$bot->{busy}};
382 if not defined $cmds; # note off cannot fail
383 die "Wrong note-off?!?"
384 if $busychannel != $channel || $busynote ne $note;
385 $bot->{busy} = undef;
387 my $t = $time + $notetime;
388 my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @$cmds;
390 # perform note-off "as soon as we can"
391 $t = $bot->{busytimer}
392 if $t < $bot->{busytimer};
393 $t = $bot->{timer} - $mintime
394 if $t < $bot->{timer} - $mintime;
396 busybot_cmd_bot_execute $bot, $t, @$cmds;
400 sub busybot_get_cmds_bot($$$)
402 my ($bot, $channel, $note) = @_;
403 my ($k0, $k1, $cmds, $cmds_off) = (undef, undef, undef, undef);
407 $cmds = $bot->{vocals};
410 $cmds = [ map { [ map { $_ eq '%s' ? $note : $_ } @$_ ] } @$cmds ];
415 elsif($channel == 10)
418 $cmds = $bot->{percussion}->{$note};
425 $cmds = $bot->{notes_on}->{$note - ($bot->{transpose} || 0) - $transpose};
426 $cmds_off = $bot->{notes_off}->{$note - ($bot->{transpose} || 0) - $transpose};
428 $k1 = $note - ($bot->{transpose} || 0) - $transpose;
430 return ($cmds, $cmds_off, $k0, $k1);
433 sub busybot_note_on_bot($$$$$$$)
435 my ($bot, $time, $channel, $program, $note, $init, $force) = @_;
436 return -1 # I won't play on this channel
437 if defined $bot->{channels} and not $bot->{channels}->{$channel};
438 return -1 # I won't play this program
439 if defined $bot->{programs} and not $bot->{programs}->{$program};
441 my ($cmds, $cmds_off, $k0, $k1) = busybot_get_cmds_bot($bot, $channel, $note);
443 return -1 # I won't play this note
444 if not defined $cmds;
447 #print STDERR "note on $bot:$time:$channel:$note\n";
451 if not busybot_cmd_bot_test $bot, $time + $notetime, $force, @$cmds;
452 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
453 busybot_cmd_bot_execute $bot, 0, ['barrier'];
454 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
456 busybot_cmd_bot_execute $bot, 0, ['barrier'];
457 for(1..$intermissions)
459 busybot_intermission_bot $bot;
461 # we always did a barrier, so we know this works
462 busybot_cmd_bot_execute $bot, $time + $notetime, @$cmds;
467 if not busybot_cmd_bot_test $bot, $time + $notetime, $force, @$cmds;
468 busybot_cmd_bot_execute $bot, $time + $notetime, @$cmds;
470 if(defined $cmds and defined $cmds_off)
472 $bot->{busy} = [$channel, $note, $cmds_off];
474 ++$bot->{seen}{$k0}{$k1};
476 if(($bot->{lastuse} // -666) >= $time - $time_forgetfulness && $channel == $bot->{lastchannel})
478 $bot->{lastchannelsequence} += 1;
482 $bot->{lastchannelsequence} = 1;
484 $bot->{lastuse} = $time;
485 $bot->{lastchannel} = $channel;
487 # print STDERR "$time $bot->{id} $channel:$note\n"
495 $busybots = Storable::dclone $busybots_orig;
496 @busybots_allocated = ();
497 %notechannelbots = ();
499 $notetime = $timeoffset_postinit - $lowestnotestart;
502 sub busybot_note_off($$$)
504 my ($time, $channel, $note) = @_;
506 # print STDERR "note off $time:$channel:$note\n";
513 if(my $bot = $notechannelbots{$channel}{$note})
515 busybot_note_off_bot $bot, $time, $channel, $note;
516 delete $notechannelbots{$channel}{$note};
525 my ($time, $channel, $program, $note, @bots) = @_;
535 ($a->[0]->{lastuse} // -666) <=> ($b->[0]->{lastuse} // -666)
542 if(($_->{lastuse} // -666) >= $time - $time_forgetfulness)
544 if($channel == $_->{lastchannel})
546 $q += $_->{lastchannelsequence};
550 # better leave this one alone
551 $q -= $_->{lastchannelsequence};
559 sub busybot_note_on($$$$)
561 my ($time, $channel, $program, $note) = @_;
563 if($notechannelbots{$channel}{$note})
565 busybot_note_off $time, $channel, $note;
568 # print STDERR "note on $time:$channel:$note\n";
572 my @epicfailbots = ();
574 for(botsort $time, $channel, $program, $note, @busybots_allocated)
576 my $canplay = busybot_note_on_bot $_, $time, $channel, $program, $note, 0, 0;
579 $notechannelbots{$channel}{$note} = $_;
582 push @epicfailbots, $_
589 for(unsort keys %$busybots)
591 next if $busybots->{$_}->{count} <= 0;
592 my $bot = Storable::dclone $busybots->{$_};
593 $bot->{id} = @busybots_allocated + 1;
594 $bot->{classname} = $_;
595 my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 1, 0;
604 --$busybots->{$_}->{count};
605 $notechannelbots{$channel}{$note} = $bot;
606 push @busybots_allocated, $bot;
610 die "Fresh bot cannot play stuff"
616 # we cannot add a new bot to play this
617 # we could try finding a bot that could play this, and force him to stop the note!
619 my @candidates = (); # contains: [$bot, $score, $offtime]
621 # put in all currently busy bots that COULD play this, if they did a note-off first
622 for my $bot(@epicfailbots)
625 if $busybots->{$bot->{classname}}->{count} != 0;
628 my ($busy_chan, $busy_note, $busy_cmds_off) = @{$bot->{busy}};
630 unless $busy_cmds_off;
631 my ($cmds, $cmds_off, $k0, $k1) = busybot_get_cmds_bot $bot, $channel, $note;
634 my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @$cmds;
635 my ($mintime_off, $maxtime_off, $busytime_off) = busybot_cmd_bot_cmdinfo @$busy_cmds_off;
637 my $noteofftime = busybot_cmd_bot_matchtime $bot, $time + $notetime + $mintime, $time + $notetime, @$busy_cmds_off;
639 if $noteofftime < $bot->{busytimer};
641 if $noteofftime + $mintime_off < $bot->{timer};
644 # prefer turning off long notes
645 $score += 100 * ($noteofftime - $bot->{timer});
646 # prefer turning off low notes
647 $score += 1 * (-$note);
648 # prefer turning off notes that already play on another channel
649 $score += 1000 * (grep { $_ != $busy_chan && $notechannelbots{$_}{$busy_note} && $notechannelbots{$_}{$busy_note}{busy} } keys %notechannelbots);
651 push @candidates, [$bot, $score, $noteofftime];
658 @candidates = sort { $a->[1] <=> $b->[1] } @candidates;
659 my ($bot, $score, $offtime) = @{(pop @candidates)};
660 my $oldchan = $bot->{busy}->[0];
661 my $oldnote = $bot->{busy}->[1];
662 busybot_note_off $offtime - $notetime, $oldchan, $oldnote;
663 my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 0, 1;
664 die "Canplay but not?"
666 warn "Made $channel:$note play by stopping $oldchan:$oldnote";
667 $notechannelbots{$channel}{$note} = $bot;
677 warn "Not enough bots to play this (when playing $channel:$note)";
680 # my $b = $_->{busy};
681 # warn "$_->{classname} -> @{[$b ? qq{$b->[0]:$b->[1]} : 'none']} @{[$_->{timer} - $notetime]} ($time)\n";
686 warn "Note $channel:$note cannot be played by any bot";
694 my (@preallocate) = @_;
698 die "Cannot preallocate any more $_ bots"
699 if $busybots->{$_}->{count} <= 0;
700 my $bot = Storable::dclone $busybots->{$_};
701 $bot->{id} = @busybots_allocated + 1;
702 $bot->{classname} = $_;
703 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
704 busybot_cmd_bot_execute $bot, 0, ['barrier'];
705 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
707 busybot_cmd_bot_execute $bot, 0, ['barrier'];
708 --$busybots->{$_}->{count};
709 push @busybots_allocated, $bot;
715 my ($filename, $trans) = @_;
718 my $opus = MIDI::Opus->new({from_file => $filename});
719 my $ticksperquarter = $opus->ticks();
720 my $tracks = $opus->tracks_r();
721 my @tempi = (); # list of start tick, time per tick pairs (calculated as seconds per quarter / ticks per quarter)
725 for($tracks->[0]->events())
728 if($_->[0] eq 'set_tempo')
730 push @tempi, [$tick, $_->[2] * 0.000001 / $ticksperquarter];
737 my $curtempo = [0, 0.5 / $ticksperquarter];
742 # this event is in the past
743 # we add the full time since the last one then
744 $sec += ($_->[0] - $curtempo->[0]) * $curtempo->[1];
748 # if this event is in the future, we break
753 $sec += ($tick - $curtempo->[0]) * $curtempo->[1];
757 # merge all to a single track
758 my @allmidievents = ();
760 for my $track(0..@$tracks-1)
763 for($tracks->[$track]->events())
765 my ($command, $delta, @data) = @$_;
766 $command = 'note_off' if $command eq 'note_on' and $data[2] == 0;
768 push @allmidievents, [$command, $tick, $sequence++, $track, @data];
772 if(open my $fh, "$filename.vocals")
779 my ($tick, $file) = split /\s+/, $_;
784 elsif($tick eq 'shift')
790 push @allmidievents, ['note_on', $tick * $scale + $shift, $sequence++, -1, -1, $file];
791 push @allmidievents, ['note_off', $tick * $scale + $shift, $sequence++, -1, -1, $file];
796 @allmidievents = sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] } @allmidievents;
805 $t = $tick2sec->($_->[1]);
807 if($_->[0] eq 'note_on')
809 my $chan = $_->[4] + 1;
810 ++$notes_seen{$chan}{($programs{$chan} || 1)}{$_->[5]};
811 if($midinotes{$chan}{$_->[5]})
814 busybot_note_off($t - SYS_TICRATE - 0.001, $chan, $_->[5]);
816 busybot_note_on($t, $chan, $programs{$chan} || 1, $_->[5]);
818 $midinotes{$chan}{$_->[5]} = 1;
820 elsif($_->[0] eq 'note_off')
822 my $chan = $_->[4] + 1;
823 if($midinotes{$chan}{$_->[5]})
826 busybot_note_off($t - SYS_TICRATE - 0.001, $chan, $_->[5]);
828 $midinotes{$chan}{$_->[5]} = 0;
830 elsif($_->[0] eq 'patch_change')
832 my $chan = $_->[4] + 1;
833 my $program = $_->[5] + 1;
834 $programs{$chan} = $program;
838 print STDERR "For file $filename:\n";
839 print STDERR " Stuck notes: $notes_stuck\n";
841 for my $testtranspose(-127..127)
846 for my $channel(sort keys %notes_seen)
848 next if $channel == 10 or $channel < 0;
849 for my $program(sort keys %{$notes_seen{$channel}})
851 for my $note(sort keys %{$notes_seen{$channel}{$program}})
853 my $cnt = $notes_seen{$channel}{$program}{$note};
857 for(@busybots_allocated)
859 next # I won't play on this channel
860 if defined $_->{channels} and not $_->{channels}->{$channel};
861 next # I won't play this program
862 if defined $_->{programs} and not $_->{programs}->{$program};
863 my $transposed = $note - ($_->{transpose} || 0) - $testtranspose;
864 if(exists $_->{notes_on}{$transposed})
870 ++$votehigh if $transposed >= 0;
871 ++$votelow if $transposed < 0;
878 elsif($votelow >= $votehigh)
889 next if !$toohigh != !$toolow;
890 print STDERR " Transpose $testtranspose: $toohigh too high, $toolow too low, $good good\n";
893 for my $program(sort keys %{$notes_seen{10}})
895 for my $note(sort keys %{$notes_seen{10}{$program}})
897 my $cnt = $notes_seen{10}{$program}{$note};
899 for(@busybots_allocated)
901 next # I won't play on this channel
902 if defined $_->{channels} and not $_->{channels}->{10};
903 next # I won't play this program
904 if defined $_->{programs} and not $_->{programs}->{$program};
905 if(exists $_->{percussion}{$note})
912 print STDERR "Failed percussion $note ($cnt times)\n";
917 while(my ($k1, $v1) = each %midinotes)
919 while(my ($k2, $v2) = each %$v1)
921 busybot_note_off($t, $k1, $k2);
925 for(@busybots_allocated)
927 busybot_intermission_bot $_;
934 print STDERR "Bots allocated:\n";
937 for(@busybots_allocated)
939 print STDERR "$_->{id} is a $_->{classname}\n";
940 ++$counthash{$_->{classname}};
941 while(my ($type, $notehash) = each %{$_->{seen}})
943 while(my ($k, $v) = each %$notehash)
945 $notehash{$_->{classname}}{$type}{$k} += $v;
949 for my $cn(sort keys %counthash)
951 print STDERR "$counthash{$cn} bots of $cn have played:\n";
952 for my $type(sort keys %{$notehash{$cn}})
954 for my $note(sort { $a <=> $b } keys %{$notehash{$cn}{$type}})
956 my $cnt = $notehash{$cn}{$type}{$note};
957 print STDERR " $type $note ($cnt times)\n";
961 for(@busybots_allocated)
963 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_predone];
964 busybot_cmd_bot_execute $_, 0, ['barrier'];
967 busybot_cmd_bot_execute $_, 0, @{$_->{done}};
969 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_postdone];
970 busybot_cmd_bot_execute $_, 0, ['barrier'];
974 my @preallocate = ();
981 Preallocate(@preallocate);
985 my $filename = shift @l;
986 my $transpose = shift @l;
987 ConvertMIDI($filename, $transpose);
990 my @preallocate_new = map { $_->{classname} } @busybots_allocated;
991 if(@preallocate_new == @preallocate)
993 print "$precommands$commands";
996 @preallocate = @preallocate_new;
1001 unless $@ eq "noalloc\n";