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.)
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
15 use Chess::PGN::Parse;
23 require 'Position.pm';
31 my $latest_update = undef;
32 my $output_timer = undef;
33 my $http_timer = undef;
34 my $stop_pgn_fetch = 0;
35 my $tb_retry_timer = undef;
37 my $tb_lookup_running = 0;
38 my $last_written_json = undef;
40 # TODO: Persist (parts of) this so that we can restart.
41 my %clock_target_for_pos = ();
45 open(FICSLOG, ">ficslog.txt")
46 or die "ficslog.txt: $!";
47 print FICSLOG "Log starting.\n";
51 open(UCILOG, ">ucilog.txt")
52 or die "ucilog.txt: $!";
53 print UCILOG "Log starting.\n";
57 open(TBLOG, ">tblog.txt")
58 or die "tblog.txt: $!";
59 print TBLOG "Log starting.\n";
65 # open the chess engine
66 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
67 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
70 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
72 uciprint($engine, "setoption name UCI_AnalyseMode value true");
73 while (my ($key, $value) = each %remoteglotconf::engine_config) {
74 uciprint($engine, "setoption name $key value $value");
76 uciprint($engine, "ucinewgame");
78 if (defined($engine2)) {
79 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
80 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
81 uciprint($engine2, "setoption name $key value $value");
83 uciprint($engine2, "setoption name MultiPV value 500");
84 uciprint($engine2, "ucinewgame");
87 print "Chess engine ready.\n";
90 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
91 $t->input_log(\*FICSLOG);
92 $t->open($remoteglotconf::server);
93 $t->print($remoteglotconf::nick);
94 $t->waitfor('/Press return to enter the server/');
98 $t->cmd("set shout 0");
99 $t->cmd("set seek 0");
100 $t->cmd("set style 12");
102 my $ev1 = AnyEvent->io(
105 cb => sub { # what callback to execute
107 my $line = $t->getline(Timeout => 0, errmode => 'return');
108 return if (!defined($line));
116 if (defined($remoteglotconf::target)) {
117 if ($remoteglotconf::target =~ /^http:/) {
118 fetch_pgn($remoteglotconf::target);
120 $t->cmd("observe $remoteglotconf::target");
123 print "FICS ready.\n";
125 # Engine events have already been set up by Engine.pm.
129 my ($engine, $line, $primary) = @_;
131 return if $line =~ /(upper|lower)bound/;
133 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
134 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
135 if ($line =~ /^info/) {
136 my (@infos) = split / /, $line;
139 parse_infos($engine, @infos);
141 if ($line =~ /^id/) {
142 my (@ids) = split / /, $line;
145 parse_ids($engine, @ids);
147 if ($line =~ /^bestmove/) {
149 return if (!$remoteglotconf::uci_assume_full_compliance);
150 if (defined($pos_waiting)) {
151 uciprint($engine, "position fen " . $pos_waiting->fen());
152 uciprint($engine, "go infinite");
154 $pos_calculating = $pos_waiting;
155 $pos_waiting = undef;
158 $engine2->{'info'} = {};
159 my $pos = $pos_waiting // $pos_calculating;
160 uciprint($engine2, "position fen " . $pos->fen());
161 uciprint($engine2, "go infinite");
162 $pos_calculating_second_engine = $pos;
168 my $getting_movelist = 0;
169 my $pos_for_movelist = undef;
170 my @uci_movelist = ();
171 my @pretty_movelist = ();
175 if ($line =~ /^<12> /) {
176 handle_position(Position->new($line));
179 if ($line =~ /^Movelist for game /) {
180 my $pos = $pos_waiting // $pos_calculating;
183 @pretty_movelist = ();
184 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
185 $getting_movelist = 1;
188 if ($getting_movelist &&
189 $line =~ /^\s* \d+\. \s+ # move number
190 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
191 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
195 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
196 push @uci_movelist, $uci_move;
197 push @pretty_movelist, $1;
200 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
201 push @uci_movelist, $uci_move;
202 push @pretty_movelist, $2;
206 warn "Error when getting FICS move history: $@";
207 $getting_movelist = 0;
210 if ($getting_movelist &&
211 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
213 for my $pos ($pos_waiting, $pos_calculating) {
214 next if (!defined($pos));
215 if ($pos->fen() eq $pos_for_movelist->fen()) {
216 $pos->{'pretty_history'} = \@pretty_movelist;
219 $getting_movelist = 0;
221 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
222 my ($who, $msg) = ($1, $2);
224 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
226 if ($msg =~ /^fics (.*?)$/) {
227 $t->cmd("tell $who Executing '$1' on FICS.");
229 } elsif ($msg =~ /^uci (.*?)$/) {
230 $t->cmd("tell $who Sending '$1' to the engine.");
231 print { $engine->{'write'} } "$1\n";
232 } elsif ($msg =~ /^pgn (.*?)$/) {
234 $t->cmd("tell $who Starting to poll '$url'.");
236 } elsif ($msg =~ /^stoppgn$/) {
237 $t->cmd("tell $who Stopping poll.");
240 } elsif ($msg =~ /^quit$/) {
241 $t->cmd("tell $who Bye bye.");
244 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
247 #print "FICS: [$line]\n";
250 # Starts periodic fetching of PGNs from the given URL.
253 AnyEvent::HTTP::http_get($url, sub {
254 handle_pgn(@_, $url);
258 my ($last_pgn_white, $last_pgn_black);
259 my @last_pgn_uci_moves = ();
260 my $pgn_hysteresis_counter = 0;
263 my ($body, $header, $url) = @_;
265 if ($stop_pgn_fetch) {
271 my $pgn = Chess::PGN::Parse->new(undef, $body);
272 if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
273 warn "Error in parsing PGN from $url\n";
276 $pgn->parse_game({ save_comments => 'yes' });
277 my $pos = Position->start_pos($pgn->white, $pgn->black);
278 my $moves = $pgn->moves;
280 for my $move (@$moves) {
282 ($pos, $uci_move) = $pos->make_pretty_move($move);
283 push @uci_moves, $uci_move;
285 $pos->{'result'} = $pgn->result;
286 $pos->{'pretty_history'} = $moves;
288 extract_clock($pgn, $pos);
290 # Sometimes, PGNs lose a move or two for a short while,
291 # or people push out new ones non-atomically.
292 # Thus, if we PGN doesn't change names but becomes
293 # shorter, we mistrust it for a few seconds.
295 if (defined($last_pgn_white) && defined($last_pgn_black) &&
296 $last_pgn_white eq $pgn->white &&
297 $last_pgn_black eq $pgn->black &&
298 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
299 if (++$pgn_hysteresis_counter < 3) {
304 $last_pgn_white = $pgn->white;
305 $last_pgn_black = $pgn->black;
306 @last_pgn_uci_moves = @uci_moves;
307 $pgn_hysteresis_counter = 0;
308 handle_position($pos);
312 warn "Error in parsing moves from $url\n";
316 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
321 sub handle_position {
323 find_clock_start($pos);
325 # if this is already in the queue, ignore it
326 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
328 # if we're already chewing on this and there's nothing else in the queue,
330 return if (!defined($pos_waiting) && defined($pos_calculating) &&
331 $pos->fen() eq $pos_calculating->fen());
333 # if we're already thinking on something, stop and wait for the engine
335 if (defined($pos_calculating)) {
336 # Store the final data we have for this position in the history,
337 # with the precise clock information we just got from the new
338 # position. (Historic positions store the clock at the end of
341 # Do not output anything new to the main analysis; that's
342 # going to be obsolete really soon.
343 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
344 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
345 delete $pos_calculating->{'white_clock_target'};
346 delete $pos_calculating->{'black_clock_target'};
349 if (!defined($pos_waiting)) {
350 uciprint($engine, "stop");
352 if ($remoteglotconf::uci_assume_full_compliance) {
355 uciprint($engine, "position fen " . $pos->fen());
356 uciprint($engine, "go infinite");
357 $pos_calculating = $pos;
360 # it's wrong just to give the FEN (the move history is useful,
361 # and per the UCI spec, we should really have sent "ucinewgame"),
363 uciprint($engine, "position fen " . $pos->fen());
364 uciprint($engine, "go infinite");
365 $pos_calculating = $pos;
368 if (defined($engine2)) {
369 if (defined($pos_calculating_second_engine)) {
370 uciprint($engine2, "stop");
372 uciprint($engine2, "position fen " . $pos->fen());
373 uciprint($engine2, "go infinite");
374 $pos_calculating_second_engine = $pos;
376 $engine2->{'info'} = {};
379 $engine->{'info'} = {};
382 schedule_tb_lookup();
385 # Output a command every move to note that we're
386 # still paying attention -- this is a good tradeoff,
387 # since if no move has happened in the last half
388 # hour, the analysis/relay has most likely stopped
389 # and we should stop hogging server resources.
395 my ($engine, @x) = @_;
398 my $info = $engine->{'info'};
400 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
401 for my $i (0..$#x - 1) {
402 if ($x[$i] eq 'multipv') {
408 while (scalar @x > 0) {
409 if ($x[0] eq 'multipv') {
415 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
417 my $value = shift @x;
418 $info->{$key} = $value;
421 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
422 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
425 my $value = shift @x;
426 $info->{$key . $mpv} = $value;
429 if ($x[0] eq 'score') {
432 delete $info->{'score_cp' . $mpv};
433 delete $info->{'score_mate' . $mpv};
435 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
438 $info->{'score_cp' . $mpv} = shift @x;
439 } elsif ($x[0] eq 'mate') {
441 $info->{'score_mate' . $mpv} = shift @x;
449 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
452 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
456 #print "unknown info '$x[0]', trying to recover...\n";
458 die "Unknown info '" . join(',', @x) . "'";
464 my ($engine, @x) = @_;
466 while (scalar @x > 0) {
467 if ($x[0] =~ /^(name|author)$/) {
469 my $value = join(' ', @x);
470 $engine->{'id'}{$key} = $value;
479 sub prettyprint_pv_no_cache {
480 my ($board, @pvs) = @_;
482 if (scalar @pvs == 0 || !defined($pvs[0])) {
487 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
488 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
489 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
493 my ($pos, @pvs) = @_;
495 my $cachekey = join('', @pvs);
496 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
497 return @{$pos->{'prettyprint_cache'}{$cachekey}};
499 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
500 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
508 return if (!defined($pos_calculating));
510 # Don't update too often.
511 my $age = Time::HiRes::tv_interval($latest_update);
512 if ($age < $remoteglotconf::update_max_interval) {
513 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
514 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
518 my $info = $engine->{'info'};
521 # If we have tablebase data from a previous lookup, replace the
522 # engine data with the data from the tablebase.
524 my $fen = $pos_calculating->fen();
525 if (exists($tb_cache{$fen})) {
526 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
527 delete $info->{$key . '1'};
528 delete $info->{$key};
530 $info->{'nodes'} = 0;
532 $info->{'depth'} = 0;
533 $info->{'seldepth'} = 0;
534 $info->{'tbhits'} = 0;
536 my $t = $tb_cache{$fen};
538 my $matelen = int((1 + $t->{'score'}) / 2);
539 if ($t->{'result'} eq '1/2-1/2') {
540 $info->{'score_cp'} = 0;
541 } elsif ($t->{'result'} eq '1-0') {
542 if ($pos_calculating->{'toplay'} eq 'B') {
543 $info->{'score_mate'} = -$matelen;
545 $info->{'score_mate'} = $matelen;
548 if ($pos_calculating->{'toplay'} eq 'B') {
549 $info->{'score_mate'} = $matelen;
551 $info->{'score_mate'} = -$matelen;
555 $info->{'tablebase'} = 1;
557 $info->{'tablebase'} = 0;
561 # Some programs _always_ report MultiPV, even with only one PV.
562 # In this case, we simply use that data as if MultiPV was never
565 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
566 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
567 if (exists($info->{$key . '1'})) {
568 $info->{$key} = $info->{$key . '1'};
574 # Check the PVs first. if they're invalid, just wait, as our data
575 # is most likely out of sync. This isn't a very good solution, as
576 # it can frequently miss stuff, but it's good enough for most users.
580 if (exists($info->{'pv'})) {
581 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
585 while (exists($info->{'pv' . $mpv})) {
586 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
591 $engine->{'info'} = {};
597 $latest_update = [Time::HiRes::gettimeofday];
601 my $info = $engine->{'info'};
602 my $id = $engine->{'id'};
604 my $text = 'Analysis';
605 if ($pos_calculating->{'last_move'} ne 'none') {
606 if ($pos_calculating->{'toplay'} eq 'W') {
607 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
609 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
611 if (exists($id->{'name'})) {
616 if (exists($id->{'name'})) {
617 $text .= " by $id->{'name'}:\n\n";
622 return unless (exists($pos_calculating->{'board'}));
624 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
627 while (exists($info->{'pv' . $mpv})) {
628 $text .= sprintf " PV%2u", $mpv;
629 my $score = short_score($info, $pos_calculating, $mpv);
630 $text .= " ($score)" if (defined($score));
633 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
634 if ($info->{'tbhits' . $mpv} == 1) {
635 $tbhits = ", 1 tbhit";
637 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
641 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
642 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
643 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
647 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
653 my $score = long_score($info, $pos_calculating, '');
654 $text .= " $score\n" if defined($score);
655 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
658 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
659 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
660 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
662 if (exists($info->{'seldepth'})) {
663 $text .= sprintf " (%u selective)", $info->{'seldepth'};
665 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
666 if ($info->{'tbhits'} == 1) {
667 $text .= ", one Syzygy hit";
669 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
675 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
677 my @refutation_lines = ();
678 if (defined($engine2)) {
679 for (my $mpv = 1; $mpv < 500; ++$mpv) {
680 my $info = $engine2->{'info'};
681 last if (!exists($info->{'pv' . $mpv}));
683 my $pv = $info->{'pv' . $mpv};
685 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
686 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
687 if (scalar @pretty_pv > 5) {
688 @pretty_pv = @pretty_pv[0..4];
689 push @pretty_pv, "...";
691 my $key = $pretty_move;
692 my $line = sprintf(" %-6s %6s %3s %s",
694 short_score($info, $pos_calculating_second_engine, $mpv),
695 "d" . $info->{'depth' . $mpv},
696 join(', ', @pretty_pv));
697 push @refutation_lines, [ $key, $line ];
702 if ($#refutation_lines >= 0) {
703 $text .= "Shallow search of all legal moves:\n\n";
704 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
705 $text .= $line->[1] . "\n";
710 if ($last_text ne $text) {
711 print "
\e[H
\e[2J"; # clear the screen
718 my $historic_json_only = shift;
719 my $info = $engine->{'info'};
722 $json->{'position'} = $pos_calculating->to_json_hash();
723 $json->{'id'} = $engine->{'id'};
724 $json->{'score'} = long_score($info, $pos_calculating, '');
725 $json->{'short_score'} = short_score($info, $pos_calculating, '');
727 $json->{'nodes'} = $info->{'nodes'};
728 $json->{'nps'} = $info->{'nps'};
729 $json->{'depth'} = $info->{'depth'};
730 $json->{'tbhits'} = $info->{'tbhits'};
731 $json->{'seldepth'} = $info->{'seldepth'};
732 $json->{'tablebase'} = $info->{'tablebase'};
734 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
735 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
737 my %refutation_lines = ();
738 my @refutation_lines = ();
739 if (defined($engine2)) {
740 for (my $mpv = 1; $mpv < 500; ++$mpv) {
741 my $info = $engine2->{'info'};
742 my $pretty_move = "";
744 last if (!exists($info->{'pv' . $mpv}));
747 my $pv = $info->{'pv' . $mpv};
748 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
749 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
750 $refutation_lines{$pv->[0]} = {
751 sort_key => $pretty_move,
752 depth => $info->{'depth' . $mpv},
753 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
754 pretty_score => short_score($info, $pos_calculating, $mpv),
755 pretty_move => $pretty_move,
756 pv_pretty => \@pretty_pv,
761 $json->{'refutation_lines'} = \%refutation_lines;
763 my $encoded = JSON::XS::encode_json($json);
764 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
765 (defined($last_written_json) && $last_written_json eq $encoded)) {
766 atomic_set_contents($remoteglotconf::json_output, $encoded);
767 $last_written_json = $encoded;
770 if (exists($pos_calculating->{'pretty_history'}) &&
771 defined($remoteglotconf::json_history_dir)) {
772 my $filename = $remoteglotconf::json_history_dir . "/" . id_for_pos($pos_calculating) . ".json";
774 # Overwrite old analysis (assuming it exists at all) if we're
775 # using a different engine, or if we've calculated deeper.
776 # nodes is used as a tiebreaker. Don't bother about Multi-PV
777 # data; it's not that important.
778 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
779 my $new_depth = $json->{'depth'} // 0;
780 my $new_nodes = $json->{'nodes'} // 0;
781 if (!defined($old_engine) ||
782 $old_engine ne $json->{'id'}{'name'} ||
783 $new_depth > $old_depth ||
784 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
785 atomic_set_contents($filename, $encoded);
790 sub atomic_set_contents {
791 my ($filename, $contents) = @_;
793 open my $fh, ">", $filename . ".tmp"
797 rename($filename . ".tmp", $filename);
803 my $halfmove_num = scalar @{$pos->{'pretty_history'}};
804 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
805 return "move$halfmove_num-$fen";
808 sub get_json_analysis_stats {
809 my $filename = shift;
811 my ($engine, $depth, $nodes);
813 open my $fh, "<", $filename
817 my $json = JSON::XS::decode_json(<$fh>);
818 $engine = $json->{'id'}{'name'} // die;
819 $depth = $json->{'depth'} // 0;
820 $nodes = $json->{'nodes'} // 0;
824 warn "Error in decoding $filename: $@";
827 return ($engine, $depth, $nodes);
831 my ($engine, $msg) = @_;
832 $engine->print($msg);
833 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
837 my ($info, $pos, $mpv) = @_;
839 my $invert = ($pos->{'toplay'} eq 'B');
840 if (defined($info->{'score_mate' . $mpv})) {
842 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
844 return sprintf "M%3d", $info->{'score_mate' . $mpv};
847 if (exists($info->{'score_cp' . $mpv})) {
848 my $score = $info->{'score_cp' . $mpv} * 0.01;
850 if ($info->{'tablebase'}) {
859 return sprintf "%+5.2f", $score;
867 my ($info, $pos, $mpv, $invert) = @_;
869 if (defined($info->{'score_mate' . $mpv})) {
870 my $mate = $info->{'score_mate' . $mpv};
874 $score = 99999 - $mate;
876 # Side to move is getting mated (note the double negative for $mate)
877 $score = -99999 - $mate;
884 if (exists($info->{'score_cp' . $mpv})) {
885 my $score = $info->{'score_cp' . $mpv};
897 my ($info, $pos, $mpv) = @_;
899 if (defined($info->{'score_mate' . $mpv})) {
900 my $mate = $info->{'score_mate' . $mpv};
901 if ($pos->{'toplay'} eq 'B') {
905 return sprintf "White mates in %u", $mate;
907 return sprintf "Black mates in %u", -$mate;
910 if (exists($info->{'score_cp' . $mpv})) {
911 my $score = $info->{'score_cp' . $mpv} * 0.01;
913 if ($info->{'tablebase'}) {
914 return "Theoretical draw";
916 return "Score: 0.00";
919 if ($pos->{'toplay'} eq 'B') {
922 return sprintf "Score: %+5.2f", $score;
931 my ($fen, $board, $toplay) = @_;
933 if (exists($book_cache{$fen})) {
934 return $book_cache{$fen};
937 my $ret = `./booklook $fen`;
938 return "" if ($ret =~ /Not found/ || $ret eq '');
942 for my $m (split /\n/, $ret) {
943 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
947 $pmove = '(current)';
949 ($pmove) = prettyprint_pv_no_cache($board, $move);
950 $pmove .= $annotation;
954 if ($toplay eq 'W') {
955 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
957 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
959 my $n = $win + $draw + $lose;
965 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
968 push @moves, [ $pmove, $n, $percent, $rating ];
971 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
973 my $text = "Book moves:\n\n Perf. N Rating\n\n";
975 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
982 my ($pgn, $pos) = @_;
984 # Look for extended PGN clock tags.
985 my $tags = $pgn->tags;
986 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
987 $pos->{'white_clock'} = $tags->{'WhiteClock'};
988 $pos->{'black_clock'} = $tags->{'BlackClock'};
990 $pos->{'white_clock'} =~ s/\b(\d)\b/0$1/g;
991 $pos->{'black_clock'} =~ s/\b(\d)\b/0$1/g;
995 # Look for TCEC-style time comments.
996 my $moves = $pgn->moves;
997 my $comments = $pgn->comments;
998 my $last_black_move = int((scalar @$moves) / 2);
999 my $last_white_move = int((1 + scalar @$moves) / 2);
1001 my $black_key = $last_black_move . "b";
1002 my $white_key = $last_white_move . "w";
1004 if (exists($comments->{$white_key}) &&
1005 exists($comments->{$black_key}) &&
1006 $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/ &&
1007 $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/) {
1008 $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/;
1009 $pos->{'white_clock'} = $1;
1010 $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/;
1011 $pos->{'black_clock'} = $1;
1016 sub find_clock_start {
1019 # If the game is over, the clock is stopped.
1020 if (exists($pos->{'result'}) &&
1021 ($pos->{'result'} eq '1-0' ||
1022 $pos->{'result'} eq '1/2-1/2' ||
1023 $pos->{'result'} eq '0-1')) {
1027 # When we don't have any moves, we assume the clock hasn't started yet.
1028 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1032 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1033 if (!exists($pos->{'pretty_history'})) {
1037 my $id = id_for_pos($pos);
1038 if (exists($clock_target_for_pos{$id})) {
1039 if ($pos->{'toplay'} eq 'W') {
1040 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1042 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1047 # OK, we haven't seen this position before, so we assume the move
1048 # happened right now.
1049 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1050 if (!exists($pos->{$key})) {
1051 # No clock information.
1054 $pos->{$key} =~ /(\d+):(\d+):(\d+)/;
1055 my $time_left = $1 * 3600 + $2 * 60 + $3;
1056 $clock_target_for_pos{$id} = time + $time_left;
1057 if ($pos->{'toplay'} eq 'W') {
1058 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1060 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1064 sub schedule_tb_lookup {
1065 return if (!defined($remoteglotconf::tb_serial_key));
1066 my $pos = $pos_waiting // $pos_calculating;
1067 return if (exists($tb_cache{$pos->fen()}));
1069 # If there's more than seven pieces, there's not going to be an answer,
1071 return if ($pos->num_pieces() > 7);
1073 # Max one at a time. If it's still relevant when it returns,
1074 # schedule_tb_lookup() will be called again.
1075 return if ($tb_lookup_running);
1077 $tb_lookup_running = 1;
1078 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1079 $remoteglotconf::tb_serial_key .
1080 '&auth.password=aquarium&type=0&fen=' .
1081 URI::Escape::uri_escape($pos->fen());
1082 print TBLOG "Downloading $url...\n";
1083 AnyEvent::HTTP::http_get($url, sub {
1084 handle_tb_lookup_return(@_, $pos, $pos->fen());
1088 sub handle_tb_lookup_return {
1089 my ($body, $header, $pos, $fen) = @_;
1090 print TBLOG "Response for [$fen]:\n";
1091 print TBLOG $header . "\n\n";
1092 print TBLOG $body . "\n\n";
1094 my $response = JSON::XS::decode_json($body);
1095 if ($response->{'ErrorCode'} != 0) {
1096 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1098 my $state = $response->{'Response'}{'StateString'};
1099 if ($state eq 'COMPLETE') {
1100 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1101 if (!defined($pgn) || !$pgn->read_game()) {
1102 warn "Error in parsing PGN\n";
1104 $pgn->quick_parse_game;
1106 my $moves = $pgn->moves;
1108 for my $move (@$moves) {
1110 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1111 push @uci_moves, $uci_move;
1114 result => $pgn->result,
1116 score => $response->{'Response'}{'Score'},
1120 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1121 # Try again in a second. Note that if we have changed
1122 # position in the meantime, we might query a completely
1123 # different position! But that's fine.
1125 die "Unknown response state " . $state;
1128 # Wait a second before we schedule another one.
1129 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1130 $tb_lookup_running = 0;
1131 schedule_tb_lookup();
1135 warn "Error in tablebase lookup: $@";
1137 # Don't try this one again, but don't block new lookups either.
1138 $tb_lookup_running = 0;
1143 my ($cmdline, $tag, $cb) = @_;
1144 return undef if (!defined($cmdline));
1145 return Engine->open($cmdline, $tag, $cb);
1148 sub col_letter_to_num {
1149 return ord(shift) - ord('a');
1152 sub row_letter_to_num {
1153 return 7 - (ord(shift) - ord('1'));
1156 sub parse_uci_move {
1158 my $from_col = col_letter_to_num(substr($move, 0, 1));
1159 my $from_row = row_letter_to_num(substr($move, 1, 1));
1160 my $to_col = col_letter_to_num(substr($move, 2, 1));
1161 my $to_row = row_letter_to_num(substr($move, 3, 1));
1162 my $promo = substr($move, 4, 1);
1163 return ($from_col, $from_row, $to_col, $to_row, $promo);