]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
2e0f2206bba780b5a2fd8c81674adc7168dd35fa
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 #              analysis, or for live analysis of relayed games. (Do not use for
6 #              cheating! Cheating is bad for your karma, and your abuser flag.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use Net::Telnet;
13 use FileHandle;
14 use IPC::Open2;
15 use Time::HiRes;
16 use strict;
17 use warnings;
18
19 # Configuration
20 my $server = "freechess.org";
21 my $target = "GMCarlsen";
22 my $engine_cmdline = "'./Deep Rybka 4 SSE42 x64'";
23 my $engine2_cmdline = "./stockfish_13111119_x64_modern_sse42";
24 my $telltarget = undef;   # undef to be silent
25 my @tell_intervals = (5, 20, 60, 120, 240, 480, 960);  # after each move
26 my $uci_assume_full_compliance = 0;                    # dangerous :-)
27 my $second_engine_start_depth = 8;
28 my @masters = (
29         'Sesse',
30         'Sessse',
31         'Sesssse',
32         'greatestguns',
33         'beuki'
34 );
35
36 # Program starts here
37 $SIG{ALRM} = sub { output_screen(); };
38
39 $| = 1;
40
41 open(FICSLOG, ">ficslog.txt")
42         or die "ficslog.txt: $!";
43 print FICSLOG "Log starting.\n";
44 select(FICSLOG);
45 $| = 1;
46
47 open(UCILOG, ">ucilog.txt")
48         or die "ucilog.txt: $!";
49 print UCILOG "Log starting.\n";
50 select(UCILOG);
51 $| = 1;
52 select(STDOUT);
53
54 # open the chess engine
55 my $engine = open_engine($engine_cmdline);
56 my $engine2 = open_engine($engine2_cmdline);
57 my ($last_move, $last_tell);
58 my $last_text = '';
59 my $last_told_text = '';
60 my ($pos_waiting, $pos_calculating, $move_calculating_second_engine);
61 my %refutation_moves = ();
62
63 uciprint($engine, "setoption name UCI_AnalyseMode value true");
64 # uciprint($engine, "setoption name NalimovPath value /srv/tablebase");
65 uciprint($engine, "setoption name NalimovUsage value Rarely");
66 uciprint($engine, "setoption name Hash value 1024");
67 # uciprint($engine, "setoption name MultiPV value 2");
68 uciprint($engine, "ucinewgame");
69
70 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
71 # uciprint($engine2, "setoption name NalimovPath value /srv/tablebase");
72 uciprint($engine2, "setoption name NalimovUsage value Rarely");
73 uciprint($engine2, "setoption name Hash value 1024");
74 uciprint($engine2, "setoption name Threads value 8");
75 # uciprint($engine2, "setoption name MultiPV value 2");
76 uciprint($engine2, "ucinewgame");
77
78 print "Chess engine ready.\n";
79
80 # now talk to FICS
81 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
82 $t->input_log(\*FICSLOG);
83 $t->open($server);
84 $t->print("SesseBOT");
85 $t->waitfor('/Press return to enter the server/');
86 $t->cmd("");
87
88 # set some options
89 $t->cmd("set shout 0");
90 $t->cmd("set seek 0");
91 $t->cmd("set style 12");
92 $t->cmd("observe $target");
93
94 # main loop
95 print "FICS ready.\n";
96 while (1) {
97         my $rin = '';
98         my $rout;
99         vec($rin, fileno($engine->{'read'}), 1) = 1;
100         vec($rin, fileno($engine2->{'read'}), 1) = 1;
101         vec($rin, fileno($t), 1) = 1;
102
103         my ($nfound, $timeleft) = select($rout=$rin, undef, undef, 5.0);
104         my $sleep = 1.0;
105
106         while (1) {
107                 my $line = $t->getline(Timeout => 0, errmode => 'return');
108                 last if (!defined($line));
109
110                 chomp $line;
111                 $line =~ tr/\r//d;
112                 if ($line =~ /^<12> /) {
113                         my $pos = style12_to_pos($line);
114                         
115                         # if this is already in the queue, ignore it
116                         next if (defined($pos_waiting) && $pos->{'fen'} eq $pos_waiting->{'fen'});
117
118                         # if we're already chewing on this and there's nothing else in the queue,
119                         # also ignore it
120                         next if (!defined($pos_waiting) && defined($pos_calculating) &&
121                                  $pos->{'fen'} eq $pos_calculating->{'fen'});
122
123                         # if we're already thinking on something, stop and wait for the engine
124                         # to approve
125                         if (defined($pos_calculating)) {
126                                 if (!defined($pos_waiting)) {
127                                         uciprint($engine, "stop");
128                                 }
129                                 if ($uci_assume_full_compliance) {
130                                         $pos_waiting = $pos;
131                                 } else {
132                                         uciprint($engine, "position fen " . $pos->{'fen'});
133                                         uciprint($engine, "go infinite");
134                                         $pos_calculating = $pos;
135                                 }
136                         } else {
137                                 # it's wrong just to give the FEN (the move history is useful,
138                                 # and per the UCI spec, we should really have sent "ucinewgame"),
139                                 # but it's easier
140                                 uciprint($engine, "position fen " . $pos->{'fen'});
141                                 uciprint($engine, "go infinite");
142                                 $pos_calculating = $pos;
143                         }
144
145                         %refutation_moves = calculate_refutation_moves($pos);
146                         if (defined($move_calculating_second_engine)) {
147                                 uciprint($engine2, "stop");
148                                 $move_calculating_second_engine = undef;
149                         } else {
150                                 give_new_move_to_second_engine($pos);
151                         }
152
153                         $engine->{'info'} = {};
154                         $engine2->{'info'} = {};
155                         $last_move = time;
156
157                         # 
158                         # Output a command every move to note that we're
159                         # still paying attention -- this is a good tradeoff,
160                         # since if no move has happened in the last half
161                         # hour, the analysis/relay has most likely stopped
162                         # and we should stop hogging server resources.
163                         #
164                         $t->cmd("date");
165                 }
166                 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
167                         my ($who, $msg) = ($1, $2);
168
169                         next if (grep { $_ eq $who } (@masters) == 0);
170         
171                         if ($msg =~ /^fics (.*?)$/) {
172                                 $t->cmd("tell $who Executing '$1' on FICS.");
173                                 $t->cmd($1);
174                         } elsif ($msg =~ /^uci (.*?)$/) {
175                                 $t->cmd("tell $who Sending '$1' to the engine.");
176                                 print { $engine->{'write'} } "$1\n";
177                         } else {
178                                 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
179                         }
180                 }
181                 #print "FICS: [$line]\n";
182                 $sleep = 0;
183         }
184         
185         # any fun on the UCI channel?
186         if ($nfound > 0 && vec($rout, fileno($engine->{'read'}), 1) == 1) {
187                 my $line = read_line($engine->{'read'});
188                 handle_uci($engine, $line, 1);
189                 $sleep = 0;
190
191                 # don't update too often
192                 Time::HiRes::alarm(0.2);
193         }
194         if ($nfound > 0 && vec($rout, fileno($engine2->{'read'}), 1) == 1) {
195                 my $line = read_line($engine2->{'read'});
196                 handle_uci($engine2, $line, 0);
197                 $sleep = 0;
198
199                 # don't update too often
200                 Time::HiRes::alarm(0.2);
201         }
202
203         sleep $sleep;
204 }
205
206 sub handle_uci {
207         my ($engine, $line, $primary) = @_;
208
209         chomp $line;
210         $line =~ tr/\r//d;
211         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
212         print UCILOG localtime() . " <= $line\n";
213         if ($line =~ /^info/) {
214                 my (@infos) = split / /, $line;
215                 shift @infos;
216
217                 parse_infos($engine, @infos);
218         }
219         if ($line =~ /^id/) {
220                 my (@ids) = split / /, $line;
221                 shift @ids;
222
223                 parse_ids($engine, @ids);
224         }
225         if ($line =~ /^bestmove/) {
226                 if ($primary) {
227                         return if (!$uci_assume_full_compliance);
228                         if (defined($pos_waiting)) {
229                                 uciprint($engine, "position fen " . $pos_waiting->{'fen'});
230                                 uciprint($engine, "go infinite");
231
232                                 $pos_calculating = $pos_waiting;
233                                 $pos_waiting = undef;
234                         }
235                 } else {
236                         if (defined($move_calculating_second_engine)) { 
237                                 my $move = $refutation_moves{$move_calculating_second_engine};
238                                 $move->{'pv'} = $engine->{'info'}{'pv'};
239                                 $move->{'score_cp'} = $engine->{'info'}{'score_cp'} // $engine->{'info'}{'score_cp1'} // 0;
240                                 $move->{'score_mate'} = $engine->{'info'}{'score_mate'} // $engine->{'info'}{'score_mate1'};
241                                 $move->{'toplay'} = $pos_calculating->{'toplay'};
242                         }
243                         give_new_move_to_second_engine($pos_waiting // $pos_calculating);
244                 }
245         }
246 }
247
248 sub parse_infos {
249         my ($engine, @x) = @_;
250         my $mpv = '';
251
252         my $info = $engine->{'info'};
253
254         while (scalar @x > 0) {
255                 if ($x[0] =~ 'multipv') {
256                         shift @x;
257                         $mpv = shift @x;
258                         next;
259                 }
260                 if ($x[0] =~ /^(currmove|currmovenumber|cpuload)$/) {
261                         my $key = shift @x;
262                         my $value = shift @x;
263                         $info->{$key} = $value;
264                         next;
265                 }
266                 if ($x[0] =~ /^(depth|seldepth|hashfull|time|nodes|nps|tbhits)$/) {
267                         my $key = shift @x;
268                         my $value = shift @x;
269                         $info->{$key . $mpv} = $value;
270                         next;
271                 }
272                 if ($x[0] eq 'score') {
273                         shift @x;
274
275                         delete $info->{'score_cp' . $mpv};
276                         delete $info->{'score_mate' . $mpv};
277
278                         while ($x[0] =~ /^(cp|mate|lowerbound|upperbound)$/) {
279                                 if ($x[0] eq 'cp') {
280                                         shift @x;
281                                         $info->{'score_cp' . $mpv} = shift @x;
282                                 } elsif ($x[0] eq 'mate') {
283                                         shift @x;
284                                         $info->{'score_mate' . $mpv} = shift @x;
285                                 } else {
286                                         shift @x;
287                                 }
288                         }
289                         next;
290                 }
291                 if ($x[0] eq 'pv') {
292                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
293                         last;
294                 }
295                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
296                         last;
297                 }
298
299                 #print "unknown info '$x[0]', trying to recover...\n";
300                 #shift @x;
301                 die "Unknown info '" . join(',', @x) . "'";
302
303         }
304 }
305
306 sub parse_ids {
307         my ($engine, @x) = @_;
308
309         while (scalar @x > 0) {
310                 if ($x[0] =~ /^(name|author)$/) {
311                         my $key = shift @x;
312                         my $value = join(' ', @x);
313                         $engine->{'id'}{$key} = $value;
314                         last;
315                 }
316
317                 # unknown
318                 shift @x;
319         }
320 }
321
322 sub style12_to_pos {
323         my $str = shift;
324         my %pos = ();
325         my (@x) = split / /, $str;
326         
327         $pos{'board'} = [ @x[1..8] ];
328         $pos{'toplay'} = $x[9];
329         $pos{'ep_file_num'} = $x[10];
330         $pos{'white_castle_k'} = $x[11];
331         $pos{'white_castle_q'} = $x[12];
332         $pos{'black_castle_k'} = $x[13];
333         $pos{'black_castle_q'} = $x[14];
334         $pos{'time_to_100move_rule'} = $x[15];
335         $pos{'move_num'} = $x[26];
336         $pos{'last_move'} = $x[29];
337         $pos{'fen'} = make_fen(\%pos);
338
339         return \%pos;
340 }
341
342 sub make_fen {
343         my $pos = shift;
344
345         # the board itself
346         my (@board) = @{$pos->{'board'}};
347         for my $rank (0..7) {
348                 $board[$rank] =~ s/(-+)/length($1)/ge;
349         }
350         my $fen = join('/', @board);
351
352         # white/black to move
353         $fen .= " ";
354         $fen .= lc($pos->{'toplay'});
355
356         # castling
357         my $castling = "";
358         $castling .= "K" if ($pos->{'white_castle_k'} == 1);
359         $castling .= "Q" if ($pos->{'white_castle_q'} == 1);
360         $castling .= "k" if ($pos->{'black_castle_k'} == 1);
361         $castling .= "q" if ($pos->{'black_castle_q'} == 1);
362         $castling = "-" if ($castling eq "");
363         # $castling = "-"; # chess960
364         $fen .= " ";
365         $fen .= $castling;
366
367         # en passant
368         my $ep = "-";
369         if ($pos->{'ep_file_num'} != -1) {
370                 my $col = $pos->{'ep_file_num'};
371                 my $nep = (qw(a b c d e f g h))[$col];
372
373                 if ($pos->{'toplay'} eq 'B') {
374                         $nep .= "3";
375                 } else {
376                         $nep .= "6";
377                 }
378
379                 #
380                 # Showing the en passant square when actually no capture can be made
381                 # seems to confuse at least Rybka. Thus, check if there's actually
382                 # a pawn of the opposite side that can do the en passant move, and if
383                 # not, just lie -- it doesn't matter anyway. I'm unsure what's the
384                 # "right" thing as per the standard, though.
385                 #
386                 if ($pos->{'toplay'} eq 'B') {
387                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[4], $col-1, 1) eq 'p');
388                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[4], $col+1, 1) eq 'p');
389                 } else {
390                         $ep = $nep if ($col > 0 && substr($pos->{'board'}[3], $col-1, 1) eq 'P');
391                         $ep = $nep if ($col < 7 && substr($pos->{'board'}[3], $col+1, 1) eq 'P');
392                 }
393         }
394         $fen .= " ";
395         $fen .= $ep;
396
397         # half-move clock
398         $fen .= " ";
399         $fen .= $pos->{'time_to_100move_rule'};
400
401         # full-move clock
402         $fen .= " ";
403         $fen .= $pos->{'move_num'};
404
405         return $fen;
406 }
407
408 sub make_move {
409         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
410         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
411         my $piece = substr($board->[$from_row], $from_col, 1);
412         my @nb = @$board;
413
414         if ($piece eq '-') {
415                 die "Invalid move $move";
416         }
417
418         # white short castling
419         if ($move eq 'e1g1' && $piece eq 'K') {
420                 # king
421                 substr($nb[7], 4, 1, '-');
422                 substr($nb[7], 6, 1, $piece);
423                 
424                 # rook
425                 substr($nb[7], 7, 1, '-');
426                 substr($nb[7], 5, 1, 'R');
427                                 
428                 return \@nb;
429         }
430
431         # white long castling
432         if ($move eq 'e1c1' && $piece eq 'K') {
433                 # king
434                 substr($nb[7], 4, 1, '-');
435                 substr($nb[7], 2, 1, $piece);
436                 
437                 # rook
438                 substr($nb[7], 0, 1, '-');
439                 substr($nb[7], 3, 1, 'R');
440                                 
441                 return \@nb;
442         }
443
444         # black short castling
445         if ($move eq 'e8g8' && $piece eq 'k') {
446                 # king
447                 substr($nb[0], 4, 1, '-');
448                 substr($nb[0], 6, 1, $piece);
449                 
450                 # rook
451                 substr($nb[0], 7, 1, '-');
452                 substr($nb[0], 5, 1, 'r');
453                                 
454                 return \@nb;
455         }
456
457         # black long castling
458         if ($move eq 'e8c8' && $piece eq 'k') {
459                 # king
460                 substr($nb[0], 4, 1, '-');
461                 substr($nb[0], 2, 1, $piece);
462                 
463                 # rook
464                 substr($nb[0], 0, 1, '-');
465                 substr($nb[0], 3, 1, 'r');
466                                 
467                 return \@nb;
468         }
469
470         # check if the from-piece is a pawn
471         if (lc($piece) eq 'p') {
472                 # attack?
473                 if ($from_col != $to_col) {
474                         # en passant?
475                         if (substr($board->[$to_row], $to_col, 1) eq '-') {
476                                 if ($piece eq 'p') {
477                                         substr($nb[$to_row + 1], $to_col, 1, '-');
478                                 } else {
479                                         substr($nb[$to_row - 1], $to_col, 1, '-');
480                                 }
481                         }
482                 } else {
483                         if ($promo ne '') {
484                                 if ($piece eq 'p') {
485                                         $piece = $promo;
486                                 } else {
487                                         $piece = uc($promo);
488                                 }
489                         }
490                 }
491         }
492
493         # update the board
494         substr($nb[$from_row], $from_col, 1, '-');
495         substr($nb[$to_row], $to_col, 1, $piece);
496
497         return \@nb;
498 }
499
500 sub prettyprint_pv {
501         my ($board, @pvs) = @_;
502
503         if (scalar @pvs == 0 || !defined($pvs[0])) {
504                 return ();
505         }
506
507         my $pv = shift @pvs;
508         my $from_col = col_letter_to_num(substr($pv, 0, 1));
509         my $from_row = row_letter_to_num(substr($pv, 1, 1));
510         my $to_col   = col_letter_to_num(substr($pv, 2, 1));
511         my $to_row   = row_letter_to_num(substr($pv, 3, 1));
512         my $promo    = substr($pv, 4, 1);
513
514         my $nb = make_move($board, $from_row, $from_col, $to_row, $to_col, $promo);
515         my $piece = substr($board->[$from_row], $from_col, 1);
516
517         if ($piece eq '-') {
518                 die "Invalid move $pv";
519         }
520
521         # white short castling
522         if ($pv eq 'e1g1' && $piece eq 'K') {
523                 return ('0-0', prettyprint_pv($nb, @pvs));
524         }
525
526         # white long castling
527         if ($pv eq 'e1c1' && $piece eq 'K') {
528                 return ('0-0-0', prettyprint_pv($nb, @pvs));
529         }
530
531         # black short castling
532         if ($pv eq 'e8g8' && $piece eq 'k') {
533                 return ('0-0', prettyprint_pv($nb, @pvs));
534         }
535
536         # black long castling
537         if ($pv eq 'e8c8' && $piece eq 'k') {
538                 return ('0-0-0', prettyprint_pv($nb, @pvs));
539         }
540
541         my $pretty;
542
543         # check if the from-piece is a pawn
544         if (lc($piece) eq 'p') {
545                 # attack?
546                 if ($from_col != $to_col) {
547                         $pretty = substr($pv, 0, 1) . 'x' . substr($pv, 2, 2);
548                 } else {
549                         $pretty = substr($pv, 2, 2);
550
551                         if (length($pv) == 5) {
552                                 # promotion
553                                 $pretty .= "=";
554                                 $pretty .= uc(substr($pv, 4, 1));
555
556                                 if ($piece eq 'p') {
557                                         $piece = substr($pv, 4, 1);
558                                 } else {
559                                         $piece = uc(substr($pv, 4, 1));
560                                 }
561                         }
562                 }
563         } else {
564                 $pretty = uc($piece);
565
566                 # see how many of these pieces could go here, in all
567                 my $num_total = 0;
568                 for my $col (0..7) {
569                         for my $row (0..7) {
570                                 next unless (substr($board->[$row], $col, 1) eq $piece);
571                                 ++$num_total if (can_reach($board, $piece, $row, $col, $to_row, $to_col));
572                         }
573                 }
574
575                 # see how many of these pieces from the given row could go here
576                 my $num_row = 0;
577                 for my $col (0..7) {
578                         next unless (substr($board->[$from_row], $col, 1) eq $piece);
579                         ++$num_row if (can_reach($board, $piece, $from_row, $col, $to_row, $to_col));
580                 }
581                 
582                 # and same for columns
583                 my $num_col = 0;
584                 for my $row (0..7) {
585                         next unless (substr($board->[$row], $from_col, 1) eq $piece);
586                         ++$num_col if (can_reach($board, $piece, $row, $from_col, $to_row, $to_col));
587                 }
588                 
589                 # see if we need to disambiguate
590                 if ($num_total > 1) {
591                         if ($num_col == 1) {
592                                 $pretty .= substr($pv, 0, 1);
593                         } elsif ($num_row == 1) {
594                                 $pretty .= substr($pv, 1, 1);
595                         } else {
596                                 $pretty .= substr($pv, 0, 2);
597                         }
598                 }
599
600                 # attack?
601                 if (substr($board->[$to_row], $to_col, 1) ne '-') {
602                         $pretty .= 'x';
603                 }
604
605                 $pretty .= substr($pv, 2, 2);
606         }
607
608         if (in_mate($nb)) {
609                 $pretty .= '#';
610         } elsif (in_check($nb) ne 'none') {
611                 $pretty .= '+';
612         }
613         return ($pretty, prettyprint_pv($nb, @pvs));
614 }
615
616 sub output_screen {
617         #return;
618         
619         return if (!defined($pos_calculating));
620
621         my $info = $engine->{'info'};
622         my $id = $engine->{'id'};
623
624         #
625         # Check the PVs first. if they're invalid, just wait, as our data
626         # is most likely out of sync. This isn't a very good solution, as
627         # it can frequently miss stuff, but it's good enough for most users.
628         #
629         eval {
630                 my $dummy;
631                 if (exists($info->{'pv'})) {
632                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}});
633                 }
634         
635                 my $mpv = 1;
636                 while (exists($info->{'pv' . $mpv})) {
637                         $dummy = prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}});
638                         ++$mpv;
639                 }
640         };
641         if ($@) {
642                 $engine->{'info'} = {};
643                 return;
644         }
645
646         my $text = 'Analysis';
647         if ($pos_calculating->{'last_move'} ne 'none') {
648                 if ($pos_calculating->{'toplay'} eq 'W') {
649                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
650                 } else {
651                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
652                 }
653                 if (exists($id->{'name'})) {
654                         $text .= ',';
655                 }
656         }
657
658         if (exists($id->{'name'})) {
659                 $text .= " by $id->{'name'}:\n\n";
660         } else {
661                 $text .= ":\n\n";
662         }
663
664         return unless (exists($pos_calculating->{'board'}));
665                 
666         #
667         # Some programs _always_ report MultiPV, even with only one PV.
668         # In this case, we simply use that data as if MultiPV was never
669         # specified.
670         #
671         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
672                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
673                         if (exists($info->{$key . '1'}) && !exists($info->{$key})) {
674                                 $info->{$key} = $info->{$key . '1'};
675                         }
676                 }
677         }
678
679         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
680                 # multi-PV
681                 my $mpv = 1;
682                 while (exists($info->{'pv' . $mpv})) {
683                         $text .= sprintf "  PV%2u", $mpv;
684                         my $score = short_score($info, $pos_calculating, $mpv);
685                         $text .= "  ($score)" if (defined($score));
686
687                         my $tbhits = '';
688                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
689                                 if ($info->{'tbhits' . $mpv} == 1) {
690                                         $tbhits = ", 1 tbhit";
691                                 } else {
692                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
693                                 }
694                         }
695
696                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
697                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
698                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
699                         }
700
701                         $text .= ":\n";
702                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}})) . "\n";
703                         $text .= "\n";
704                         ++$mpv;
705                 }
706         } else {
707                 # single-PV
708                 my $score = long_score($info, $pos_calculating, '');
709                 $text .= "  $score\n" if defined($score);
710                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
711                 $text .=  "\n";
712
713                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
714                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
715                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
716                 }
717                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
718                         if ($info->{'tbhits'} == 1) {
719                                 $text .= ", one Nalimov hit";
720                         } else {
721                                 $text .= sprintf ", %u Nalimov hits", $info->{'tbhits'};
722                         }
723                 }
724                 if (exists($info->{'seldepth'})) {
725                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
726                 }
727                 $text .= "\n\n";
728         }
729
730         #$text .= book_info($pos_calculating->{'fen'}, $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
731
732         my @refutation_lines = ();
733         for my $move (keys %refutation_moves) {
734                 eval {
735                         my $m = $refutation_moves{$move};
736                         next if ($m->{'depth'} < $second_engine_start_depth);
737                         my $pretty_move = join('', prettyprint_pv($pos_calculating->{'board'}, $move));
738                         my @pretty_pv = prettyprint_pv($pos_calculating->{'board'}, $move, @{$m->{'pv'}});
739                         if (scalar @pretty_pv > 5) {
740                                 @pretty_pv = @pretty_pv[0..4];
741                                 push @pretty_pv, "...";
742                         }
743                         #my $key = score_sort_key($refutation_moves{$move}, $pos_calculating, '', 1);
744                         my $key = $pretty_move;
745                         my $line = sprintf("  %-6s %6s %3s  %s",
746                                 $pretty_move,
747                                 short_score($refutation_moves{$move}, $pos_calculating, '', 1),
748                                 "d" . $m->{'depth'},
749                                 join(', ', @pretty_pv));
750                         push @refutation_lines, [ $key, $line ];
751                 };
752         }
753
754         if ($#refutation_lines >= 0) {
755                 $text .= "Shallow search of all legal moves:\n\n";
756                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
757                         $text .= $line->[1] . "\n";
758                 }
759                 $text .= "\n\n";        
760         }       
761
762         if ($last_text ne $text) {
763                 print "\e[H\e[2J"; # clear the screen
764                 print $text;
765                 $last_text = $text;
766         }
767
768         # Now construct the tell text, if any
769         return if (!defined($telltarget));
770
771         my $tell_text = '';
772
773         if (exists($id->{'name'})) {
774                 $tell_text .= "Analysis by $id->{'name'} -- see http://analysis.sesse.net/ for more information\n";
775         } else {
776                 $tell_text .= "Computer analysis -- http://analysis.sesse.net/ for more information\n";
777         }
778
779         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
780                 # multi-PV
781                 my $mpv = 1;
782                 while (exists($info->{'pv' . $mpv})) {
783                         $tell_text .= sprintf "  PV%2u", $mpv;
784                         my $score = short_score($info, $pos_calculating, $mpv);
785                         $tell_text .= "  ($score)" if (defined($score));
786
787                         if (exists($info->{'depth' . $mpv})) {
788                                 $tell_text .= sprintf " (%2u ply)", $info->{'depth' . $mpv};
789                         }
790
791                         $tell_text .= ": ";
792                         $tell_text .= join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv' . $mpv}}));
793                         $tell_text .= "\n";
794                         ++$mpv;
795                 }
796         } else {
797                 # single-PV
798                 my $score = long_score($info, $pos_calculating, '');
799                 $tell_text .= "  $score\n" if defined($score);
800                 $tell_text .= "  PV: " . join(', ', prettyprint_pv($pos_calculating->{'board'}, @{$info->{'pv'}}));
801                 if (exists($info->{'depth'})) {
802                         $tell_text .= sprintf " (depth %u ply)", $info->{'depth'};
803                 }
804                 $tell_text .=  "\n";
805         }
806
807         # see if a new tell is called for -- it is if the delay has expired _and_
808         # this is not simply a repetition of the last one
809         if ($last_told_text ne $tell_text) {
810                 my $now = time;
811                 for my $iv (@tell_intervals) {
812                         last if ($now - $last_move < $iv);
813                         next if ($last_tell - $last_move >= $iv);
814
815                         for my $line (split /\n/, $tell_text) {
816                                 $t->print("tell $telltarget [$target] $line");
817                         }
818
819                         $last_told_text = $text;
820                         $last_tell = $now;
821
822                         last;
823                 }
824         }
825 }
826
827 sub find_kings {
828         my $board = shift;
829         my ($wkr, $wkc, $bkr, $bkc);
830
831         for my $row (0..7) {
832                 for my $col (0..7) {
833                         my $piece = substr($board->[$row], $col, 1);
834                         if ($piece eq 'K') {
835                                 ($wkr, $wkc) = ($row, $col);
836                         } elsif ($piece eq 'k') {
837                                 ($bkr, $bkc) = ($row, $col);
838                         }
839                 }
840         }
841
842         return ($wkr, $wkc, $bkr, $bkc);
843 }
844
845 sub in_mate {
846         my $board = shift;
847         my $check = in_check($board);
848         return 0 if ($check eq 'none');
849
850         # try all possible moves for the side in check
851         for my $row (0..7) {
852                 for my $col (0..7) {
853                         my $piece = substr($board->[$row], $col, 1);
854                         next if ($piece eq '-');
855
856                         if ($check eq 'white') {
857                                 next if ($piece eq lc($piece));
858                         } else {
859                                 next if ($piece eq uc($piece));
860                         }
861
862                         for my $dest_row (0..7) {
863                                 for my $dest_col (0..7) {
864                                         next if ($row == $dest_row && $col == $dest_col);
865                                         next unless (can_reach($board, $piece, $row, $col, $dest_row, $dest_col));
866
867                                         my @nb = @$board;
868                                         substr($nb[$row], $col, 1, '-');
869                                         substr($nb[$dest_row], $dest_col, 1, $piece);
870
871                                         my $new_check = in_check(\@nb);
872                                         return 0 if ($new_check ne $check && $new_check ne 'both');
873                                 }
874                         }
875                 }
876         }
877
878         # nothing to do; mate
879         return 1;
880 }
881
882 sub in_check {
883         my $board = shift;
884         my ($black_check, $white_check) = (0, 0);
885
886         my ($wkr, $wkc, $bkr, $bkc) = find_kings($board);
887
888         # check all pieces for the possibility of threatening the two kings
889         for my $row (0..7) {
890                 for my $col (0..7) {
891                         my $piece = substr($board->[$row], $col, 1);
892                         next if ($piece eq '-');
893                 
894                         if (uc($piece) eq $piece) {
895                                 # white piece
896                                 $black_check = 1 if (can_reach($board, $piece, $row, $col, $bkr, $bkc));
897                         } else {
898                                 # black piece
899                                 $white_check = 1 if (can_reach($board, $piece, $row, $col, $wkr, $wkc));
900                         }
901                 }
902         }
903
904         if ($black_check && $white_check) {
905                 return 'both';
906         } elsif ($black_check) {
907                 return 'black';
908         } elsif ($white_check) {
909                 return 'white';
910         } else {
911                 return 'none';
912         }
913 }
914
915 sub can_reach {
916         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
917         
918         # can't eat your own piece
919         my $dest_piece = substr($board->[$to_row], $to_col, 1);
920         if ($dest_piece ne '-') {
921                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
922         }
923
924         if (lc($piece) eq 'k') {
925                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
926         }
927         if (lc($piece) eq 'r') {
928                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
929
930                 # check that there's a clear passage
931                 if ($from_row == $to_row) {
932                         if ($from_col > $to_col) {
933                                 ($to_col, $from_col) = ($from_col, $to_col);
934                         }
935
936                         for my $c (($from_col+1)..($to_col-1)) {
937                                 my $middle_piece = substr($board->[$to_row], $c, 1);
938                                 return 0 if ($middle_piece ne '-');     
939                         }
940
941                         return 1;
942                 } else {
943                         if ($from_row > $to_row) {
944                                 ($to_row, $from_row) = ($from_row, $to_row);
945                         }
946
947                         for my $r (($from_row+1)..($to_row-1)) {
948                                 my $middle_piece = substr($board->[$r], $to_col, 1);
949                                 return 0 if ($middle_piece ne '-');     
950                         }
951
952                         return 1;
953                 }
954         }
955         if (lc($piece) eq 'b') {
956                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
957
958                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
959                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
960
961                 my $r = $from_row + $dr;
962                 my $c = $from_col + $dc;
963
964                 while ($r != $to_row) {
965                         my $middle_piece = substr($board->[$r], $c, 1);
966                         return 0 if ($middle_piece ne '-');
967                         
968                         $r += $dr;
969                         $c += $dc;
970                 }
971
972                 return 1;
973         }
974         if (lc($piece) eq 'n') {
975                 my $diff_r = abs($from_row - $to_row);
976                 my $diff_c = abs($from_col - $to_col);
977                 return 1 if ($diff_r == 2 && $diff_c == 1);
978                 return 1 if ($diff_r == 1 && $diff_c == 2);
979                 return 0;
980         }
981         if ($piece eq 'q') {
982                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
983                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
984         }
985         if ($piece eq 'Q') {
986                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
987                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
988         }
989
990         # TODO: en passant
991         if ($piece eq 'p') {
992                 # black pawn
993                 if ($to_col == $from_col && $to_row == $from_row + 1) {
994                         return ($dest_piece eq '-');
995                 }
996                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
997                         my $middle_piece = substr($board->[2], $to_col, 1);
998                         return ($dest_piece eq '-' && $middle_piece eq '-');
999                 }
1000                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
1001                         return ($dest_piece ne '-');
1002                 }
1003                 return 0;
1004         }
1005         if ($piece eq 'P') {
1006                 # white pawn
1007                 if ($to_col == $from_col && $to_row == $from_row - 1) {
1008                         return ($dest_piece eq '-');
1009                 }
1010                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
1011                         my $middle_piece = substr($board->[5], $to_col, 1);
1012                         return ($dest_piece eq '-' && $middle_piece eq '-');
1013                 }
1014                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
1015                         return ($dest_piece ne '-');
1016                 }
1017                 return 0;
1018         }
1019         
1020         # unknown piece
1021         return 0;
1022 }
1023
1024 sub uciprint {
1025         my ($engine, $msg) = @_;
1026         print { $engine->{'write'} } "$msg\n";
1027         print UCILOG localtime() . " => $msg\n";
1028 }
1029
1030 sub short_score {
1031         my ($info, $pos, $mpv, $invert) = @_;
1032
1033         $invert //= 0;
1034         if ($pos->{'toplay'} eq 'B') {
1035                 $invert = !$invert;
1036         }
1037
1038         if (defined($info->{'score_mate' . $mpv})) {
1039                 if ($invert) {
1040                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1041                 } else {
1042                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1043                 }
1044         } else {
1045                 if (exists($info->{'score_cp' . $mpv})) {
1046                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1047                         if ($invert) {
1048                                 $score = -$score;
1049                         }
1050                         return sprintf "%+5.2f", $score;
1051                 }
1052         }
1053
1054         return undef;
1055 }
1056
1057 sub score_sort_key {
1058         my ($info, $pos, $mpv, $invert) = @_;
1059
1060         $invert //= 0;
1061         if ($pos->{'toplay'} eq 'B') {
1062                 $invert = !$invert;
1063         }
1064
1065         if (defined($info->{'score_mate' . $mpv})) {
1066                 if ($invert) {
1067                         return -(99999 - $info->{'score_mate' . $mpv});
1068                 } else {
1069                         return 99999 - $info->{'score_mate' . $mpv};
1070                 }
1071         } else {
1072                 if (exists($info->{'score_cp' . $mpv})) {
1073                         my $score = $info->{'score_cp' . $mpv};
1074                         if ($invert) {
1075                                 $score = -$score;
1076                         }
1077                         return $score;
1078                 }
1079         }
1080
1081         return undef;
1082 }
1083
1084 sub long_score {
1085         my ($info, $pos, $mpv) = @_;
1086
1087         if (defined($info->{'score_mate' . $mpv})) {
1088                 my $mate = $info->{'score_mate' . $mpv};
1089                 if ($pos->{'toplay'} eq 'B') {
1090                         $mate = -$mate;
1091                 }
1092                 if ($mate > 0) {
1093                         return sprintf "White mates in %u", $mate;
1094                 } else {
1095                         return sprintf "Black mates in %u", -$mate;
1096                 }
1097         } else {
1098                 if (exists($info->{'score_cp' . $mpv})) {
1099                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1100                         if ($pos->{'toplay'} eq 'B') {
1101                                 $score = -$score;
1102                         }
1103                         return sprintf "Score: %+5.2f", $score;
1104                 }
1105         }
1106
1107         return undef;
1108 }
1109
1110 my %book_cache = ();
1111 sub book_info {
1112         my ($fen, $board, $toplay) = @_;
1113
1114         if (exists($book_cache{$fen})) {
1115                 return $book_cache{$fen};
1116         }
1117
1118         my $ret = `./booklook $fen`;
1119         return "" if ($ret =~ /Not found/ || $ret eq '');
1120
1121         my @moves = ();
1122
1123         for my $m (split /\n/, $ret) {
1124                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1125
1126                 my $pmove;
1127                 if ($move eq '')  {
1128                         $pmove = '(current)';
1129                 } else {
1130                         ($pmove) = prettyprint_pv($board, $move);
1131                         $pmove .= $annotation;
1132                 }
1133
1134                 my $score;
1135                 if ($toplay eq 'W') {
1136                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1137                 } else {
1138                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1139                 }
1140                 my $n = $win + $draw + $lose;
1141                 
1142                 my $percent;
1143                 if ($n == 0) {
1144                         $percent = "     ";
1145                 } else {
1146                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1147                 }
1148
1149                 push @moves, [ $pmove, $n, $percent, $rating ];
1150         }
1151
1152         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1153         
1154         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1155         for my $m (@moves) {
1156                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1157         }
1158
1159         return $text;
1160 }
1161
1162 sub open_engine {
1163         my $cmdline = shift;
1164         my ($uciread, $uciwrite);
1165         my $pid = IPC::Open2::open2($uciread, $uciwrite, $cmdline);
1166
1167         my $engine = {
1168                 pid => $pid,
1169                 read => $uciread,
1170                 write => $uciwrite,
1171                 info => {},
1172                 ids => {}
1173         };
1174
1175         uciprint($engine, "uci");
1176
1177         # gobble the options
1178         while (<$uciread>) {
1179                 /uciok/ && last;
1180                 handle_uci($engine, $_);
1181         }
1182         
1183         return $engine;
1184 }
1185
1186 sub read_line {
1187         my $fh = shift;
1188
1189         # 
1190         # Read until we've got a full line -- if the engine sends part of
1191         # a line and then stops we're pretty much hosed, but that should
1192         # never happen.
1193         #
1194         my $line = '';
1195         while ($line !~ /\n/) {
1196                 my $tmp;
1197                 my $ret = sysread $fh, $tmp, 1;
1198
1199                 if (!defined($ret)) {
1200                         next if ($!{EINTR});
1201                         die "error in reading from the UCI engine: $!";
1202                 } elsif ($ret == 0) {
1203                         die "EOF from UCI engine";
1204                 }
1205
1206                 $line .= $tmp;
1207         }
1208
1209         $line =~ tr/\r\n//d;
1210         return $line;
1211 }
1212
1213 # Find all possible legal moves.
1214 sub calculate_refutation_moves {
1215         my $pos = shift;
1216         my $board = $pos->{'board'};
1217         my %refutation_moves = ();
1218         for my $col (0..7) {
1219                 for my $row (0..7) {
1220                         my $piece = substr($board->[$row], $col, 1);
1221
1222                         # Check that there's a piece of the right color on this square.
1223                         next if ($piece eq '-');
1224                         if ($pos->{'toplay'} eq 'W') {
1225                                 next if ($piece ne uc($piece));
1226                         } else {
1227                                 next if ($piece ne lc($piece));
1228                         }
1229
1230                         for my $to_col (0..7) {
1231                                 for my $to_row (0..7) {
1232                                         next if ($col == $to_col && $row == $to_row);
1233                                         next unless (can_reach($board, $piece, $row, $col, $to_row, $to_col));
1234
1235                                         my $promo = "";  # FIXME
1236                                         my $nb = make_move($board, $row, $col, $to_row, $to_col, $promo);
1237                                         my $check = in_check($nb);
1238                                         next if ($check eq 'both');
1239                                         if ($pos->{'toplay'} eq 'W') {
1240                                                 next if ($check eq 'white');
1241                                         } else {
1242                                                 next if ($check eq 'black');
1243                                         }
1244                                         my $move = move_to_uci_notation($row, $col, $to_row, $to_col, $promo);
1245                                         $refutation_moves{$move} = { depth => $second_engine_start_depth - 1, score_cp => 0, pv => '' };
1246                                 }
1247                         }
1248                 }
1249         }
1250         return %refutation_moves;
1251 }
1252
1253 sub give_new_move_to_second_engine {
1254         my $pos = shift;
1255                                 
1256         # Find the move that's been analyzed the shortest but is most promising.
1257         # Tie-break on UCI move representation.
1258         my $best_move = undef;
1259         for my $move (sort keys %refutation_moves) {
1260                 if (!defined($best_move)) {
1261                         $best_move = $move;
1262                         next;
1263                 }
1264                 my $best = $refutation_moves{$best_move};
1265                 my $this = $refutation_moves{$move};
1266
1267                 if ($this->{'depth'} < $best->{'depth'} ||
1268                     ($this->{'depth'} == $best->{'depth'} && $this->{'score_cp'} < $best->{'score_cp'})) {
1269                         $best_move = $move;
1270                         next;
1271                 }
1272         }
1273
1274         my $m = $refutation_moves{$best_move};
1275         ++$m->{'depth'};
1276         uciprint($engine2, "position fen " . $pos->{'fen'} . " moves " . $best_move);
1277         uciprint($engine2, "go depth " . $m->{'depth'});
1278         $move_calculating_second_engine = $best_move;
1279 }
1280
1281 sub col_letter_to_num {
1282         return ord(shift) - ord('a');
1283 }
1284
1285 sub row_letter_to_num {
1286         return 7 - (ord(shift) - ord('1'));
1287 }
1288
1289 sub move_to_uci_notation {
1290         my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
1291         $promo //= "";
1292         return sprintf("%c%d%c%d%s", ord('a') + $from_col, 8 - $from_row, ord('a') + $to_col, 8 - $to_row, $promo);
1293 }