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 'aim_random')
347 $commands .= sprintf "sv_cmd bot_cmd %d aim %f 0 %f\n", $bot->{id}, $_->[1] + rand($_->[2] - $_->[1]), $_->[3];
349 elsif($_->[0] eq 'barrier')
351 $commands .= sprintf "sv_cmd bot_cmd %d barrier\n", $bot->{id};
352 $bot->{timer} = $bot->{busytimer} = 0;
353 undef $bot->{lastuse};
355 elsif($_->[0] eq 'raw')
357 $commands .= sprintf "%s\n", join " ", @{$_}[1..@$_-1];
364 my $intermissions = 0;
366 sub busybot_intermission_bot($)
369 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preintermission];
370 busybot_cmd_bot_execute $bot, 0, ['barrier'];
371 if($bot->{intermission})
373 busybot_cmd_bot_execute $bot, 0, @{$bot->{intermission}};
375 busybot_cmd_bot_execute $bot, 0, ['barrier'];
376 $notetime = $timeoffset_postintermission - $lowestnotestart;
380 sub busybot_note_off_bot($$$$)
382 my ($bot, $time, $channel, $note) = @_;
383 #print STDERR "note off $bot:$time:$channel:$note\n";
384 my ($busychannel, $busynote, $cmds) = @{$bot->{busy}};
386 if not defined $cmds; # note off cannot fail
387 die "Wrong note-off?!?"
388 if $busychannel != $channel || $busynote ne $note;
389 $bot->{busy} = undef;
391 my $t = $time + $notetime;
392 my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @$cmds;
394 # perform note-off "as soon as we can"
395 $t = $bot->{busytimer}
396 if $t < $bot->{busytimer};
397 $t = $bot->{timer} - $mintime
398 if $t < $bot->{timer} - $mintime;
400 busybot_cmd_bot_execute $bot, $t, @$cmds;
404 sub busybot_get_cmds_bot($$$)
406 my ($bot, $channel, $note) = @_;
407 my ($k0, $k1, $cmds, $cmds_off) = (undef, undef, undef, undef);
411 $cmds = $bot->{vocals};
414 $cmds = [ map { [ map { $_ eq '%s' ? $note : $_ } @$_ ] } @$cmds ];
419 elsif($channel == 10)
422 $cmds = $bot->{percussion}->{$note};
429 $cmds = $bot->{notes_on}->{$note - ($bot->{transpose} || 0) - $transpose};
430 $cmds_off = $bot->{notes_off}->{$note - ($bot->{transpose} || 0) - $transpose};
432 $k1 = $note - ($bot->{transpose} || 0) - $transpose;
434 return ($cmds, $cmds_off, $k0, $k1);
437 sub busybot_note_on_bot($$$$$$$)
439 my ($bot, $time, $channel, $program, $note, $init, $force) = @_;
440 return -1 # I won't play on this channel
441 if defined $bot->{channels} and not $bot->{channels}->{$channel};
442 return -1 # I won't play this program
443 if defined $bot->{programs} and not $bot->{programs}->{$program};
445 my ($cmds, $cmds_off, $k0, $k1) = busybot_get_cmds_bot($bot, $channel, $note);
447 return -1 # I won't play this note
448 if not defined $cmds;
451 #print STDERR "note on $bot:$time:$channel:$note\n";
455 if not busybot_cmd_bot_test $bot, $time + $notetime, $force, @$cmds;
456 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
457 busybot_cmd_bot_execute $bot, 0, ['barrier'];
458 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
460 busybot_cmd_bot_execute $bot, 0, ['barrier'];
461 for(1..$intermissions)
463 busybot_intermission_bot $bot;
465 # we always did a barrier, so we know this works
466 busybot_cmd_bot_execute $bot, $time + $notetime, @$cmds;
471 if not busybot_cmd_bot_test $bot, $time + $notetime, $force, @$cmds;
472 busybot_cmd_bot_execute $bot, $time + $notetime, @$cmds;
474 if(defined $cmds and defined $cmds_off)
476 $bot->{busy} = [$channel, $note, $cmds_off];
478 ++$bot->{seen}{$k0}{$k1};
480 if(($bot->{lastuse} // -666) >= $time - $time_forgetfulness && $channel == $bot->{lastchannel})
482 $bot->{lastchannelsequence} += 1;
486 $bot->{lastchannelsequence} = 1;
488 $bot->{lastuse} = $time;
489 $bot->{lastchannel} = $channel;
491 # print STDERR "$time $bot->{id} $channel:$note\n"
499 $busybots = Storable::dclone $busybots_orig;
500 @busybots_allocated = ();
501 %notechannelbots = ();
503 $notetime = $timeoffset_postinit - $lowestnotestart;
506 sub busybot_note_off($$$)
508 my ($time, $channel, $note) = @_;
510 # print STDERR "note off $time:$channel:$note\n";
517 if(my $bot = $notechannelbots{$channel}{$note})
519 busybot_note_off_bot $bot, $time, $channel, $note;
520 delete $notechannelbots{$channel}{$note};
529 my ($time, $channel, $program, $note, @bots) = @_;
539 ($a->[0]->{lastuse} // -666) <=> ($b->[0]->{lastuse} // -666)
546 if($channel != 10) # percussion just should do round robin
548 if(($_->{lastuse} // -666) >= $time - $time_forgetfulness)
550 if($channel == $_->{lastchannel})
552 $q += $_->{lastchannelsequence};
556 # better leave this one alone
557 $q -= $_->{lastchannelsequence};
566 sub busybot_note_on($$$$)
568 my ($time, $channel, $program, $note) = @_;
570 if($notechannelbots{$channel}{$note})
572 busybot_note_off $time, $channel, $note;
575 # print STDERR "note on $time:$channel:$note\n";
579 my @epicfailbots = ();
581 for(botsort $time, $channel, $program, $note, @busybots_allocated)
583 my $canplay = busybot_note_on_bot $_, $time, $channel, $program, $note, 0, 0;
586 $notechannelbots{$channel}{$note} = $_;
589 push @epicfailbots, $_
596 for(unsort keys %$busybots)
598 next if $busybots->{$_}->{count} <= 0;
599 my $bot = Storable::dclone $busybots->{$_};
600 $bot->{id} = @busybots_allocated + 1;
601 $bot->{classname} = $_;
602 my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 1, 0;
611 --$busybots->{$_}->{count};
612 $notechannelbots{$channel}{$note} = $bot;
613 push @busybots_allocated, $bot;
617 die "Fresh bot cannot play stuff"
623 # we cannot add a new bot to play this
624 # we could try finding a bot that could play this, and force him to stop the note!
626 my @candidates = (); # contains: [$bot, $score, $offtime]
628 # put in all currently busy bots that COULD play this, if they did a note-off first
629 for my $bot(@epicfailbots)
632 if $busybots->{$bot->{classname}}->{count} != 0;
635 my ($busy_chan, $busy_note, $busy_cmds_off) = @{$bot->{busy}};
637 unless $busy_cmds_off;
638 my ($cmds, $cmds_off, $k0, $k1) = busybot_get_cmds_bot $bot, $channel, $note;
641 my ($mintime, $maxtime, $busytime) = busybot_cmd_bot_cmdinfo @$cmds;
642 my ($mintime_off, $maxtime_off, $busytime_off) = busybot_cmd_bot_cmdinfo @$busy_cmds_off;
644 my $noteofftime = busybot_cmd_bot_matchtime $bot, $time + $notetime + $mintime, $time + $notetime, @$busy_cmds_off;
646 if $noteofftime < $bot->{busytimer};
648 if $noteofftime + $mintime_off < $bot->{timer};
651 # prefer turning off long notes
652 $score += 100 * ($noteofftime - $bot->{timer});
653 # prefer turning off low notes
654 $score += 1 * (-$note);
655 # prefer turning off notes that already play on another channel
656 $score += 1000 * (grep { $_ != $busy_chan && $notechannelbots{$_}{$busy_note} && $notechannelbots{$_}{$busy_note}{busy} } keys %notechannelbots);
658 push @candidates, [$bot, $score, $noteofftime];
665 @candidates = sort { $a->[1] <=> $b->[1] } @candidates;
666 my ($bot, $score, $offtime) = @{(pop @candidates)};
667 my $oldchan = $bot->{busy}->[0];
668 my $oldnote = $bot->{busy}->[1];
669 busybot_note_off $offtime - $notetime, $oldchan, $oldnote;
670 my $canplay = busybot_note_on_bot $bot, $time, $channel, $program, $note, 0, 1;
671 die "Canplay but not?"
673 warn "Made $channel:$note play by stopping $oldchan:$oldnote";
674 $notechannelbots{$channel}{$note} = $bot;
684 warn "Not enough bots to play this (when playing $channel:$note)";
687 # my $b = $_->{busy};
688 # warn "$_->{classname} -> @{[$b ? qq{$b->[0]:$b->[1]} : 'none']} @{[$_->{timer} - $notetime]} ($time)\n";
693 warn "Note $channel:$note cannot be played by any bot";
701 my (@preallocate) = @_;
705 die "Cannot preallocate any more $_ bots"
706 if $busybots->{$_}->{count} <= 0;
707 my $bot = Storable::dclone $busybots->{$_};
708 $bot->{id} = @busybots_allocated + 1;
709 $bot->{classname} = $_;
710 busybot_cmd_bot_execute $bot, 0, ['cmd', 'wait', $timeoffset_preinit];
711 busybot_cmd_bot_execute $bot, 0, ['barrier'];
712 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}}
714 busybot_cmd_bot_execute $bot, 0, ['barrier'];
715 --$busybots->{$_}->{count};
716 push @busybots_allocated, $bot;
722 my ($filename, $trans) = @_;
725 my $opus = MIDI::Opus->new({from_file => $filename});
726 my $ticksperquarter = $opus->ticks();
727 my $tracks = $opus->tracks_r();
728 my @tempi = (); # list of start tick, time per tick pairs (calculated as seconds per quarter / ticks per quarter)
732 for($tracks->[0]->events())
735 if($_->[0] eq 'set_tempo')
737 push @tempi, [$tick, $_->[2] * 0.000001 / $ticksperquarter];
744 my $curtempo = [0, 0.5 / $ticksperquarter];
749 # this event is in the past
750 # we add the full time since the last one then
751 $sec += ($_->[0] - $curtempo->[0]) * $curtempo->[1];
755 # if this event is in the future, we break
760 $sec += ($tick - $curtempo->[0]) * $curtempo->[1];
764 # merge all to a single track
765 my @allmidievents = ();
767 for my $track(0..@$tracks-1)
770 for($tracks->[$track]->events())
772 my ($command, $delta, @data) = @$_;
773 $command = 'note_off' if $command eq 'note_on' and $data[2] == 0;
775 push @allmidievents, [$command, $tick, $sequence++, $track, @data];
779 if(open my $fh, "$filename.vocals")
786 my ($tick, $file) = split /\s+/, $_;
791 elsif($tick eq 'shift')
797 push @allmidievents, ['note_on', $tick * $scale + $shift, $sequence++, -1, -1, $file];
798 push @allmidievents, ['note_off', $tick * $scale + $shift, $sequence++, -1, -1, $file];
803 @allmidievents = sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] } @allmidievents;
815 my $chan = $ev->[4] + 1;
816 ++$notes_seen{$chan}{($programs{$chan} || 1)}{$ev->[5]};
817 if($midinotes{$chan}{$ev->[5]})
820 busybot_note_off($t - SYS_TICRATE - 0.001, $chan, $ev->[5]);
822 busybot_note_on($t, $chan, $programs{$chan} || 1, $ev->[5]);
824 $midinotes{$chan}{$ev->[5]} = 1;
830 my $chan = $ev->[4] + 1;
831 if(exists $sustain{$chan})
833 push @{$sustain{$chan}}, $ev;
836 if($midinotes{$chan}{$ev->[5]})
839 busybot_note_off($t - SYS_TICRATE - 0.001, $chan, $ev->[5]);
841 $midinotes{$chan}{$ev->[5]} = 0;
844 my $patch_change = sub
847 my $chan = $ev->[4] + 1;
848 my $program = $ev->[5] + 1;
849 $programs{$chan} = $program;
852 my $sustain_change = sub
855 my $chan = $ev->[4] + 1;
858 # release all currently not pressed notes
859 my $s = $sustain{$chan};
860 delete $sustain{$chan};
869 $sustain{$chan} = [];
875 $t = $tick2sec->($_->[1]);
876 # my $track = $_->[3];
877 if($_->[0] eq 'note_on')
881 elsif($_->[0] eq 'note_off')
885 elsif($_->[0] eq 'patch_change')
889 elsif($_->[0] eq 'control_change' && $_->[5] == 64) # sustain pedal
891 $sustain_change->($_);
895 # fake events for releasing pedal
898 $sustain_change->(['control_change', $t, undef, undef, $_ - 1, 64, 0]);
901 print STDERR "For file $filename:\n";
902 print STDERR " Stuck notes: $notes_stuck\n";
904 for my $testtranspose(-127..127)
909 for my $channel(sort keys %notes_seen)
911 next if $channel == 10 or $channel < 0;
912 for my $program(sort keys %{$notes_seen{$channel}})
914 for my $note(sort keys %{$notes_seen{$channel}{$program}})
916 my $cnt = $notes_seen{$channel}{$program}{$note};
920 for(@busybots_allocated, grep { $_->{count} > 0 } values %$busybots)
922 next # I won't play on this channel
923 if defined $_->{channels} and not $_->{channels}->{$channel};
924 next # I won't play this program
925 if defined $_->{programs} and not $_->{programs}->{$program};
926 my $transposed = $note - ($_->{transpose} || 0) - $testtranspose;
927 if(exists $_->{notes_on}{$transposed})
933 ++$votehigh if $transposed >= 0;
934 ++$votelow if $transposed < 0;
941 elsif($votelow >= $votehigh)
952 next if !$toohigh != !$toolow;
953 print STDERR " Transpose $testtranspose: $toohigh too high, $toolow too low, $good good\n";
956 for my $program(sort keys %{$notes_seen{10}})
958 for my $note(sort keys %{$notes_seen{10}{$program}})
960 my $cnt = $notes_seen{10}{$program}{$note};
962 for(@busybots_allocated)
964 next # I won't play on this channel
965 if defined $_->{channels} and not $_->{channels}->{10};
966 next # I won't play this program
967 if defined $_->{programs} and not $_->{programs}->{$program};
968 if(exists $_->{percussion}{$note})
975 print STDERR "Failed percussion $note ($cnt times)\n";
980 while(my ($k1, $v1) = each %midinotes)
982 while(my ($k2, $v2) = each %$v1)
984 busybot_note_off($t, $k1, $k2);
988 for(@busybots_allocated)
990 busybot_intermission_bot $_;
997 print STDERR "Bots allocated:\n";
1000 for(@busybots_allocated)
1002 print STDERR "$_->{id} is a $_->{classname}\n";
1003 ++$counthash{$_->{classname}};
1004 while(my ($type, $notehash) = each %{$_->{seen}})
1006 while(my ($k, $v) = each %$notehash)
1008 $notehash{$_->{classname}}{$type}{$k} += $v;
1012 for my $cn(sort keys %counthash)
1014 print STDERR "$counthash{$cn} bots of $cn have played:\n";
1015 for my $type(sort keys %{$notehash{$cn}})
1017 for my $note(sort { $a <=> $b } keys %{$notehash{$cn}{$type}})
1019 my $cnt = $notehash{$cn}{$type}{$note};
1020 print STDERR " $type $note ($cnt times)\n";
1024 for(@busybots_allocated)
1026 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_predone];
1027 busybot_cmd_bot_execute $_, 0, ['barrier'];
1030 busybot_cmd_bot_execute $_, 0, @{$_->{done}};
1032 busybot_cmd_bot_execute $_, 0, ['cmd', 'wait', $timeoffset_postdone];
1033 busybot_cmd_bot_execute $_, 0, ['barrier'];
1037 my @preallocate = ();
1044 Preallocate(@preallocate);
1048 my $filename = shift @l;
1049 my $transpose = shift @l;
1050 ConvertMIDI($filename, $transpose);
1053 my @preallocate_new = map { $_->{classname} } @busybots_allocated;
1054 if(@preallocate_new == @preallocate)
1056 print "sv_cmd bot_cmd reset\n";
1057 print "sv_cmd bot_cmd setbots @{[scalar @preallocate_new]}\n";
1058 print "$precommands$commands";
1061 @preallocate = @preallocate_new;
1066 unless $@ eq "noalloc\n";