]> icculus.org git repositories - divverent/nexuiz.git/blob - misc/tools/midi2cfg-ng.pl
midi2cfg-ng: a rewrite of midi2cfg using a config file, to later support percussion...
[divverent/nexuiz.git] / misc / tools / midi2cfg-ng.pl
1 #!/usr/bin/perl
2
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)
4 # usage:
5 #   perl midi2cfg.pl filename.mid basenote walktime "x y z" "x y z" "x y z" ... "/" "x y z" "x y z" ... > filename.cfg
6
7 use strict;
8 use warnings;
9 use MIDI;
10 use MIDI::Opus;
11 use Storable;
12
13 use constant MIDI_FIRST_NONCHANNEL => 17;
14 use constant MIDI_DRUMS_CHANNEL => 10;
15
16 my ($filename, $transpose, $timeoffset) = @ARGV;
17
18 my $opus = MIDI::Opus->new({from_file => $filename});
19 #$opus->write_to_file("/tmp/y.mid");
20 my $ticksperquarter = $opus->ticks();
21 my $tracks = $opus->tracks_r();
22 my @tempi = (); # list of start tick, time per tick pairs (calculated as seconds per quarter / ticks per quarter)
23 my $tick;
24
25 $tick = 0;
26 for($tracks->[0]->events())
27 {   
28     $tick += $_->[1];
29     if($_->[0] eq 'set_tempo')
30     {   
31         push @tempi, [$tick, $_->[2] * 0.000001 / $ticksperquarter];
32     }
33 }
34 sub tick2sec($)
35 {
36     my ($tick) = @_;
37     my $sec = 0;
38     my $curtempo = [0, 0.5 / $ticksperquarter];
39     for(@tempi)
40     {
41         if($_->[0] < $tick)
42         {
43                         # this event is in the past
44                         # we add the full time since the last one then
45                         $sec += ($_->[0] - $curtempo->[0]) * $curtempo->[1];
46         }   
47         else
48         {
49                         # if this event is in the future, we break
50                         last;
51         }
52                 $curtempo = $_;
53     }
54         $sec += ($tick - $curtempo->[0]) * $curtempo->[1];
55         return $sec;
56 }
57
58 # merge all to a single track
59 my @allmidievents = ();
60 my $sequence = 0;
61 for my $track(0..@$tracks-1)
62 {
63         $tick = 0;
64         for($tracks->[$track]->events())
65         {
66                 my ($command, $delta, @data) = @$_;
67                 $tick += $delta;
68                 push @allmidievents, [$command, $tick, $sequence++, $track, @data];
69         }
70 }
71 @allmidievents = sort { $a->[1] <=> $b->[1] or $a->[2] <=> $b->[2] } @allmidievents;
72
73
74
75
76
77
78 sub botconfig_read($)
79 {
80         my ($fn) = @_;
81         my %bots = ();
82         open my $fh, "<", $fn
83                 or die "<$fn: $!";
84         
85         my $currentbot = undef;
86         my $appendref = undef;
87         my $super = undef;
88         while(<$fh>)
89         {
90                 chomp;
91                 s/\s*#.*//;
92                 next if /^$/;
93                 if(s/^\t\t//)
94                 {
95                         my @cmd = split /\s+/, $_;
96                         if($cmd[0] eq 'super')
97                         {
98                                 push @$appendref, @$super;
99                         }
100                         else
101                         {
102                                 push @$appendref, \@cmd;
103                         }
104                 }
105                 elsif(s/^\t//)
106                 {
107                         if(/^include (.*)/)
108                         {
109                                 my $base = $bots{$1};
110                                 for(keys %$base)
111                                 {
112                                         if(ref $base->{$_})
113                                         {
114                                                 $currentbot->{$_} = Storable::dclone $base->{$_}; # copy array items as new array
115                                         }
116                                         else
117                                         {
118                                                 $currentbot->{$_} = $base->{$_};
119                                         }
120                                 }
121                                 # better: do some merging TODO
122                         }
123                         elsif(/^count (\d+)/)
124                         {
125                                 $currentbot->{count} = $1;
126                         }
127                         elsif(/^transpose (\d+)/)
128                         {
129                                 $currentbot->{transpose} += $1;
130                         }
131                         elsif(/^channels (.*)/)
132                         {
133                                 $currentbot->{channels} = { map { $_ => 1 } split /\s+/, $1 };
134                         }
135                         elsif(/^init$/)
136                         {
137                                 $super = $currentbot->{init};
138                                 $currentbot->{init} = $appendref = [];
139                         }
140                         elsif(/^note on (-?\d+)/)
141                         {
142                                 $super = $currentbot->{notes_on}->{$1};
143                                 $currentbot->{notes_on}->{$1} = $appendref = [];
144                         }
145                         elsif(/^note off (-?\d+)/)
146                         {
147                                 $super = $currentbot->{notes_off}->{$1};
148                                 $currentbot->{notes_off}->{$1} = $appendref = [];
149                         }
150                         elsif(/^percussion (\d+)/)
151                         {
152                                 $super = $currentbot->{percussion}->{$1};
153                                 $currentbot->{percussion}->{$1} = $appendref = [];
154                         }
155                         else
156                         {
157                                 print "unknown command: $_\n";
158                         }
159                 }
160                 elsif(/^bot (.*)/)
161                 {
162                         $currentbot = ($bots{$1} ||= {});
163                 }
164                 else
165                 {
166                         print "unknown command: $_\n";
167                 }
168         }
169
170         my $lowesttimeoffset = 0;
171         for(values %bots)
172         {
173                 my $l = $_->{init};
174                 next unless defined $l;
175                 next unless $l->[0]->[0] eq 'time';
176                 my $t = $l->[0]->[1];
177                 $lowesttimeoffset = $t
178                         if $t < $lowesttimeoffset;
179         }
180         print STDERR "Using a time adjustment of $lowesttimeoffset\n";
181         $timeoffset -= $lowesttimeoffset;
182
183         return \%bots;
184 }
185
186 sub busybot_cmd_bot_test($$@)
187 {
188         my ($bot, $time, @commands) = @_;
189
190         my $bottime = defined $bot->{timer} ? $bot->{timer} : -$timeoffset-1;
191         my $botbusytime = defined $bot->{busytimer} ? $bot->{busytimer} : -$timeoffset-1;
192
193         return 0
194                 if $time < $botbusytime;
195         
196         my $mintime = (@commands && ($commands[0]->[0] eq 'time')) ? $commands[0]->[1] : 0;
197
198         return 0
199                 if $time + $mintime < $bottime;
200         
201         return 1;
202 }
203
204 sub busybot_cmd_bot_execute($$@)
205 {
206         my ($bot, $time, @commands) = @_;
207
208         for(@commands)
209         {
210                 if($_->[0] eq 'time')
211                 {
212                         printf "w %d %f\n", $bot->{id}, $time + $_->[1] + $timeoffset;
213                         $bot->{timer} = $time + $_->[1];
214                 }
215                 elsif($_->[0] eq 'busy')
216                 {
217                         $bot->{busytimer} = $time + $_->[1];
218                 }
219                 elsif($_->[0] eq 'buttons')
220                 {
221                         my %buttons_release = %{$bot->{buttons} ||= {}};
222                         for(@{$_}[1..@$_-1])
223                         {
224                                 /(.*)\??/ or next;
225                                 delete $buttons_release{$1};
226                         }
227                         for(keys %buttons_release)
228                         {
229                                 printf "r %d %s\n", $bot->{id}, $_;
230                                 delete $bot->{buttons}->{$_};
231                         }
232                         for(@{$_}[1..@$_-1])
233                         {
234                                 /(.*)(\?)?/ or next;
235                                 defined $2 and next;
236                                 printf "p %d %s\n", $bot->{id}, $_;
237                                 $bot->{buttons}->{$_} = 1;
238                         }
239                 }
240                 elsif($_->[0] eq 'cmd')
241                 {
242                         printf "sv_cmd bot_cmd %d %s\n", $bot->{id}, join " ", @{$_}[1..@$_-1];
243                 }
244         }
245
246         return 1;
247 }
248
249 sub busybot_note_off_bot($$$$)
250 {
251         my ($bot, $time, $channel, $note) = @_;
252         my $cmds = $bot->{notes_off}->{$note - $bot->{transpose} - $transpose};
253         return 1
254                 if not defined $cmds; # note off cannot fail
255         busybot_cmd_bot_execute $bot, $time, @$cmds; 
256         return 1;
257 }
258
259 sub busybot_note_on_bot($$$$$)
260 {
261         my ($bot, $time, $channel, $note, $init) = @_;
262         return -1 # I won't play on this channel
263                 if defined $bot->{channels} and not grep { $_ == $channel } $bot->{channels};
264         my $cmds = $bot->{notes_on}->{$note - $bot->{transpose} - $transpose};
265         if(not defined $cmds)
266         {
267                 $cmds = $bot->{percussion}->{$note};
268                 return -1 # I won't play this note
269                         if not defined $cmds;
270         }
271         if($init && $bot->{init})
272         {
273                 return 0
274                         if not busybot_cmd_bot_test $bot, 0, @{$bot->{init}};
275                 return 0
276                         if not busybot_cmd_bot_test $bot, $time, @$cmds; 
277                 busybot_cmd_bot_execute $bot, 0, @{$bot->{init}};
278                 busybot_cmd_bot_execute $bot, $time, @$cmds; 
279         }
280         else
281         {
282                 return 0
283                         if not busybot_cmd_bot_test $bot, $time, @$cmds; 
284                 busybot_cmd_bot_execute $bot, $time, @$cmds; 
285         }
286         return 1;
287 }
288
289 my $busybots = botconfig_read "midi2cfg-ng.conf";
290 my @busybots_allocated;
291 my %notechannelbots;
292
293 sub busybot_note_off($$$)
294 {
295         my ($time, $channel, $note) = @_;
296
297         if(my $bot = $notechannelbots{$channel}{$note})
298         {
299                 busybot_note_off_bot $bot, $time, $channel, $note;
300                 delete $notechannelbots{$channel}{$note};
301                 return 1;
302         }
303
304         return 0;
305 }
306
307 sub busybot_note_on($$$)
308 {
309         my ($time, $channel, $note) = @_;
310
311         if($notechannelbots{$channel}{$note})
312         {
313                 busybot_note_off $time, $channel, $note;
314         }
315
316         my $overflow = 0;
317
318         for(@busybots_allocated)
319         {
320                 my $canplay = busybot_note_on_bot $_, $time, $channel, $note, 0;
321                 if($canplay > 0)
322                 {
323                         $notechannelbots{$channel}{$note} = $_;
324                         return 1;
325                 }
326                 $overflow = 1
327                         if $canplay == 0;
328                 # wrong
329         }
330
331         for(map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, rand] } keys %$busybots)
332         {
333                 next if $busybots->{$_}->{count} <= 0;
334                 my $bot = Storable::dclone $busybots->{$_};
335                 $bot->{id} = @busybots_allocated + 1;
336                 $bot->{classname} = $_;
337                 my $canplay = busybot_note_on_bot $bot, $time, $channel, $note, 1;
338                 if($canplay > 0)
339                 {
340                         --$busybots->{$_}->{count};
341                         $notechannelbots{$channel}{$note} = $bot;
342                         push @busybots_allocated, $bot;
343                         return 1;
344                 }
345                 $overflow = 1
346                         if $canplay == 0;
347         }
348
349         if($overflow)
350         {
351                 warn "Not enough bots to play this";
352                 use Data::Dumper;
353                 print STDERR Dumper \@busybots_allocated;
354         }
355         else
356         {
357                 warn "Note $channel:$note cannot be played by any bot"
358         }
359
360         return 0;
361 }
362
363 print 'alias p "sv_cmd bot_cmd $1 presskey $2"' . "\n";
364 print 'alias r "sv_cmd bot_cmd $1 releasekey $2"' . "\n";
365 print 'alias w "sv_cmd bot_cmd $1 wait_until $2"' . "\n";
366 print 'alias m "sv_cmd bot_cmd $1 moveto \"$2 $3 $4\""' . "\n";
367
368 my %midinotes = ();
369 my $note_min = undef;
370 my $note_max = undef;
371 my $notes_stuck = 0;
372 for(@allmidievents)
373 {
374         my $t = tick2sec $_->[1];
375         my $track = $_->[3];
376         if($_->[0] eq 'note_on')
377         {
378                 my $chan = $_->[4] + 1;
379                 $note_min = $_->[5]
380                         if not defined $note_min or $_->[5] < $note_min;
381                 $note_max = $_->[5]
382                         if not defined $note_max or $_->[5] > $note_max;
383                 if($midinotes{$chan}{$_->[5]})
384                 {
385                         --$notes_stuck;
386                         busybot_note_off($t, $chan, $_->[5]);
387                 }
388                 busybot_note_on($t, $chan, $_->[5]);
389                 ++$notes_stuck;
390                 $midinotes{$chan}{$_->[5]} = 1;
391         }
392         elsif($_->[0] eq 'note_off')
393         {
394                 my $chan = $_->[4] + 1;
395                 if($midinotes{$chan}{$_->[5]})
396                 {
397                         --$notes_stuck;
398                         busybot_note_off($t, $chan, $_->[5]);
399                 }
400                 $midinotes{$chan}{$_->[5]} = 0;
401         }
402 }
403
404 print STDERR "Range of notes: $note_min .. $note_max\n";
405 print STDERR "Safe transpose range: @{[$note_max - 19]} .. @{[$note_min + 13]}\n";
406 print STDERR "Unsafe transpose range: @{[$note_max - 27]} .. @{[$note_min + 18]}\n";
407 print STDERR "Stuck notes: $notes_stuck\n";
408 print STDERR "Bots allocated:\n";
409 for(@busybots_allocated)
410 {
411         print STDERR "$_->{id} is a $_->{classname}\n";
412 }