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;
24 require 'Position.pm';
32 my $latest_update = undef;
33 my $output_timer = undef;
34 my $http_timer = undef;
35 my $stop_pgn_fetch = 0;
36 my $tb_retry_timer = undef;
38 my $tb_lookup_running = 0;
39 my $last_written_json = undef;
41 # Persisted so that we can restart.
42 tie my %clock_info_for_pos, 'Tie::Persistent', 'clock_info.db', 'rw';
43 (tied %clock_info_for_pos)->autosync(1); # turn on write back on every modify
47 open(FICSLOG, ">ficslog.txt")
48 or die "ficslog.txt: $!";
49 print FICSLOG "Log starting.\n";
53 open(UCILOG, ">ucilog.txt")
54 or die "ucilog.txt: $!";
55 print UCILOG "Log starting.\n";
59 open(TBLOG, ">tblog.txt")
60 or die "tblog.txt: $!";
61 print TBLOG "Log starting.\n";
67 # open the chess engine
68 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
69 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
72 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
74 uciprint($engine, "setoption name UCI_AnalyseMode value true");
75 while (my ($key, $value) = each %remoteglotconf::engine_config) {
76 uciprint($engine, "setoption name $key value $value");
78 uciprint($engine, "ucinewgame");
80 if (defined($engine2)) {
81 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
82 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
83 uciprint($engine2, "setoption name $key value $value");
85 uciprint($engine2, "setoption name MultiPV value 500");
86 uciprint($engine2, "ucinewgame");
89 print "Chess engine ready.\n";
92 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
93 $t->input_log(\*FICSLOG);
94 $t->open($remoteglotconf::server);
95 $t->print($remoteglotconf::nick);
96 $t->waitfor('/Press return to enter the server/');
100 $t->cmd("set shout 0");
101 $t->cmd("set seek 0");
102 $t->cmd("set style 12");
104 my $ev1 = AnyEvent->io(
107 cb => sub { # what callback to execute
109 my $line = $t->getline(Timeout => 0, errmode => 'return');
110 return if (!defined($line));
118 if (defined($remoteglotconf::target)) {
119 if ($remoteglotconf::target =~ /^http:/) {
120 fetch_pgn($remoteglotconf::target);
122 $t->cmd("observe $remoteglotconf::target");
125 print "FICS ready.\n";
127 # Engine events have already been set up by Engine.pm.
131 my ($engine, $line, $primary) = @_;
133 return if $line =~ /(upper|lower)bound/;
135 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
136 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
137 if ($line =~ /^info/) {
138 my (@infos) = split / /, $line;
141 parse_infos($engine, @infos);
143 if ($line =~ /^id/) {
144 my (@ids) = split / /, $line;
147 parse_ids($engine, @ids);
149 if ($line =~ /^bestmove/) {
151 return if (!$remoteglotconf::uci_assume_full_compliance);
152 if (defined($pos_waiting)) {
153 uciprint($engine, "position fen " . $pos_waiting->fen());
154 uciprint($engine, "go infinite");
156 $pos_calculating = $pos_waiting;
157 $pos_waiting = undef;
160 $engine2->{'info'} = {};
161 my $pos = $pos_waiting // $pos_calculating;
162 uciprint($engine2, "position fen " . $pos->fen());
163 uciprint($engine2, "go infinite");
164 $pos_calculating_second_engine = $pos;
170 my $getting_movelist = 0;
171 my $pos_for_movelist = undef;
172 my @uci_movelist = ();
173 my @pretty_movelist = ();
177 if ($line =~ /^<12> /) {
178 handle_position(Position->new($line));
181 if ($line =~ /^Movelist for game /) {
182 my $pos = $pos_waiting // $pos_calculating;
185 @pretty_movelist = ();
186 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
187 $getting_movelist = 1;
190 if ($getting_movelist &&
191 $line =~ /^\s* \d+\. \s+ # move number
192 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
193 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
197 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
198 push @uci_movelist, $uci_move;
199 push @pretty_movelist, $1;
202 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
203 push @uci_movelist, $uci_move;
204 push @pretty_movelist, $2;
208 warn "Error when getting FICS move history: $@";
209 $getting_movelist = 0;
212 if ($getting_movelist &&
213 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
215 for my $pos ($pos_waiting, $pos_calculating) {
216 next if (!defined($pos));
217 if ($pos->fen() eq $pos_for_movelist->fen()) {
218 $pos->{'pretty_history'} = \@pretty_movelist;
221 $getting_movelist = 0;
223 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
224 my ($who, $msg) = ($1, $2);
226 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
228 if ($msg =~ /^fics (.*?)$/) {
229 $t->cmd("tell $who Executing '$1' on FICS.");
231 } elsif ($msg =~ /^uci (.*?)$/) {
232 $t->cmd("tell $who Sending '$1' to the engine.");
233 print { $engine->{'write'} } "$1\n";
234 } elsif ($msg =~ /^pgn (.*?)$/) {
236 $t->cmd("tell $who Starting to poll '$url'.");
238 } elsif ($msg =~ /^stoppgn$/) {
239 $t->cmd("tell $who Stopping poll.");
242 } elsif ($msg =~ /^quit$/) {
243 $t->cmd("tell $who Bye bye.");
246 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
249 #print "FICS: [$line]\n";
252 # Starts periodic fetching of PGNs from the given URL.
255 AnyEvent::HTTP::http_get($url, sub {
256 handle_pgn(@_, $url);
260 my ($last_pgn_white, $last_pgn_black);
261 my @last_pgn_uci_moves = ();
262 my $pgn_hysteresis_counter = 0;
265 my ($body, $header, $url) = @_;
267 if ($stop_pgn_fetch) {
273 my $pgn = Chess::PGN::Parse->new(undef, $body);
274 if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
275 warn "Error in parsing PGN from $url\n";
278 # Skip to the right game.
279 while (defined($remoteglotconf::pgn_filter) &&
280 !&$remoteglotconf::pgn_filter($pgn)) {
281 $pgn->read_game() or die "Out of games during filtering";
284 $pgn->parse_game({ save_comments => 'yes' });
285 my $pos = Position->start_pos($pgn->white, $pgn->black);
286 my $moves = $pgn->moves;
288 for my $move (@$moves) {
290 ($pos, $uci_move) = $pos->make_pretty_move($move);
291 push @uci_moves, $uci_move;
293 $pos->{'result'} = $pgn->result;
294 $pos->{'pretty_history'} = $moves;
296 extract_clock($pgn, $pos);
298 # Sometimes, PGNs lose a move or two for a short while,
299 # or people push out new ones non-atomically.
300 # Thus, if we PGN doesn't change names but becomes
301 # shorter, we mistrust it for a few seconds.
303 if (defined($last_pgn_white) && defined($last_pgn_black) &&
304 $last_pgn_white eq $pgn->white &&
305 $last_pgn_black eq $pgn->black &&
306 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
307 if (++$pgn_hysteresis_counter < 3) {
312 $last_pgn_white = $pgn->white;
313 $last_pgn_black = $pgn->black;
314 @last_pgn_uci_moves = @uci_moves;
315 $pgn_hysteresis_counter = 0;
316 handle_position($pos);
320 warn "Error in parsing moves from $url: $@\n";
324 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
329 sub handle_position {
331 find_clock_start($pos, $pos_calculating);
333 # if this is already in the queue, ignore it (just update the result)
334 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
335 $pos_waiting->{'result'} = $pos->{'result'};
339 # if we're already chewing on this and there's nothing else in the queue,
341 if (!defined($pos_waiting) && defined($pos_calculating) &&
342 $pos->fen() eq $pos_calculating->fen()) {
343 $pos_calculating->{'result'} = $pos->{'result'};
347 # if we're already thinking on something, stop and wait for the engine
349 if (defined($pos_calculating)) {
350 # Store the final data we have for this position in the history,
351 # with the precise clock information we just got from the new
352 # position. (Historic positions store the clock at the end of
355 # Do not output anything new to the main analysis; that's
356 # going to be obsolete really soon.
357 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
358 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
359 delete $pos_calculating->{'white_clock_target'};
360 delete $pos_calculating->{'black_clock_target'};
363 if (!defined($pos_waiting)) {
364 uciprint($engine, "stop");
366 if ($remoteglotconf::uci_assume_full_compliance) {
369 uciprint($engine, "position fen " . $pos->fen());
370 uciprint($engine, "go infinite");
371 $pos_calculating = $pos;
374 # it's wrong just to give the FEN (the move history is useful,
375 # and per the UCI spec, we should really have sent "ucinewgame"),
377 uciprint($engine, "position fen " . $pos->fen());
378 uciprint($engine, "go infinite");
379 $pos_calculating = $pos;
382 if (defined($engine2)) {
383 if (defined($pos_calculating_second_engine)) {
384 uciprint($engine2, "stop");
386 uciprint($engine2, "position fen " . $pos->fen());
387 uciprint($engine2, "go infinite");
388 $pos_calculating_second_engine = $pos;
390 $engine2->{'info'} = {};
393 $engine->{'info'} = {};
396 schedule_tb_lookup();
399 # Output a command every move to note that we're
400 # still paying attention -- this is a good tradeoff,
401 # since if no move has happened in the last half
402 # hour, the analysis/relay has most likely stopped
403 # and we should stop hogging server resources.
409 my ($engine, @x) = @_;
412 my $info = $engine->{'info'};
414 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
415 for my $i (0..$#x - 1) {
416 if ($x[$i] eq 'multipv') {
422 while (scalar @x > 0) {
423 if ($x[0] eq 'multipv') {
429 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
431 my $value = shift @x;
432 $info->{$key} = $value;
435 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
436 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
439 my $value = shift @x;
440 $info->{$key . $mpv} = $value;
443 if ($x[0] eq 'score') {
446 delete $info->{'score_cp' . $mpv};
447 delete $info->{'score_mate' . $mpv};
449 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
452 $info->{'score_cp' . $mpv} = shift @x;
453 } elsif ($x[0] eq 'mate') {
455 $info->{'score_mate' . $mpv} = shift @x;
463 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
466 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
470 #print "unknown info '$x[0]', trying to recover...\n";
472 die "Unknown info '" . join(',', @x) . "'";
478 my ($engine, @x) = @_;
480 while (scalar @x > 0) {
481 if ($x[0] =~ /^(name|author)$/) {
483 my $value = join(' ', @x);
484 $engine->{'id'}{$key} = $value;
493 sub prettyprint_pv_no_cache {
494 my ($board, @pvs) = @_;
496 if (scalar @pvs == 0 || !defined($pvs[0])) {
501 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
502 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
503 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
507 my ($pos, @pvs) = @_;
509 my $cachekey = join('', @pvs);
510 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
511 return @{$pos->{'prettyprint_cache'}{$cachekey}};
513 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
514 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
522 return if (!defined($pos_calculating));
524 # Don't update too often.
525 my $age = Time::HiRes::tv_interval($latest_update);
526 if ($age < $remoteglotconf::update_max_interval) {
527 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
528 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
532 my $info = $engine->{'info'};
535 # If we have tablebase data from a previous lookup, replace the
536 # engine data with the data from the tablebase.
538 my $fen = $pos_calculating->fen();
539 if (exists($tb_cache{$fen})) {
540 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
541 delete $info->{$key . '1'};
542 delete $info->{$key};
544 $info->{'nodes'} = 0;
546 $info->{'depth'} = 0;
547 $info->{'seldepth'} = 0;
548 $info->{'tbhits'} = 0;
550 my $t = $tb_cache{$fen};
552 my $matelen = int((1 + $t->{'score'}) / 2);
553 if ($t->{'result'} eq '1/2-1/2') {
554 $info->{'score_cp'} = 0;
555 } elsif ($t->{'result'} eq '1-0') {
556 if ($pos_calculating->{'toplay'} eq 'B') {
557 $info->{'score_mate'} = -$matelen;
559 $info->{'score_mate'} = $matelen;
562 if ($pos_calculating->{'toplay'} eq 'B') {
563 $info->{'score_mate'} = $matelen;
565 $info->{'score_mate'} = -$matelen;
569 $info->{'tablebase'} = 1;
571 $info->{'tablebase'} = 0;
575 # Some programs _always_ report MultiPV, even with only one PV.
576 # In this case, we simply use that data as if MultiPV was never
579 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
580 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
581 if (exists($info->{$key . '1'})) {
582 $info->{$key} = $info->{$key . '1'};
588 # Check the PVs first. if they're invalid, just wait, as our data
589 # is most likely out of sync. This isn't a very good solution, as
590 # it can frequently miss stuff, but it's good enough for most users.
594 if (exists($info->{'pv'})) {
595 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
599 while (exists($info->{'pv' . $mpv})) {
600 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
605 $engine->{'info'} = {};
611 $latest_update = [Time::HiRes::gettimeofday];
615 my $info = $engine->{'info'};
616 my $id = $engine->{'id'};
618 my $text = 'Analysis';
619 if ($pos_calculating->{'last_move'} ne 'none') {
620 if ($pos_calculating->{'toplay'} eq 'W') {
621 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
623 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
625 if (exists($id->{'name'})) {
630 if (exists($id->{'name'})) {
631 $text .= " by $id->{'name'}:\n\n";
636 return unless (exists($pos_calculating->{'board'}));
638 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
641 while (exists($info->{'pv' . $mpv})) {
642 $text .= sprintf " PV%2u", $mpv;
643 my $score = short_score($info, $pos_calculating, $mpv);
644 $text .= " ($score)" if (defined($score));
647 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
648 if ($info->{'tbhits' . $mpv} == 1) {
649 $tbhits = ", 1 tbhit";
651 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
655 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
656 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
657 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
661 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
667 my $score = long_score($info, $pos_calculating, '');
668 $text .= " $score\n" if defined($score);
669 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
672 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
673 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
674 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
676 if (exists($info->{'seldepth'})) {
677 $text .= sprintf " (%u selective)", $info->{'seldepth'};
679 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
680 if ($info->{'tbhits'} == 1) {
681 $text .= ", one Syzygy hit";
683 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
689 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
691 my @refutation_lines = ();
692 if (defined($engine2)) {
693 for (my $mpv = 1; $mpv < 500; ++$mpv) {
694 my $info = $engine2->{'info'};
695 last if (!exists($info->{'pv' . $mpv}));
697 my $pv = $info->{'pv' . $mpv};
699 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
700 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
701 if (scalar @pretty_pv > 5) {
702 @pretty_pv = @pretty_pv[0..4];
703 push @pretty_pv, "...";
705 my $key = $pretty_move;
706 my $line = sprintf(" %-6s %6s %3s %s",
708 short_score($info, $pos_calculating_second_engine, $mpv),
709 "d" . $info->{'depth' . $mpv},
710 join(', ', @pretty_pv));
711 push @refutation_lines, [ $key, $line ];
716 if ($#refutation_lines >= 0) {
717 $text .= "Shallow search of all legal moves:\n\n";
718 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
719 $text .= $line->[1] . "\n";
724 if ($last_text ne $text) {
725 print "
\e[H
\e[2J"; # clear the screen
732 my $historic_json_only = shift;
733 my $info = $engine->{'info'};
736 $json->{'position'} = $pos_calculating->to_json_hash();
737 $json->{'id'} = $engine->{'id'};
738 $json->{'score'} = long_score($info, $pos_calculating, '');
739 $json->{'short_score'} = short_score($info, $pos_calculating, '');
741 $json->{'nodes'} = $info->{'nodes'};
742 $json->{'nps'} = $info->{'nps'};
743 $json->{'depth'} = $info->{'depth'};
744 $json->{'tbhits'} = $info->{'tbhits'};
745 $json->{'seldepth'} = $info->{'seldepth'};
746 $json->{'tablebase'} = $info->{'tablebase'};
748 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
749 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
751 my %refutation_lines = ();
752 my @refutation_lines = ();
753 if (defined($engine2)) {
754 for (my $mpv = 1; $mpv < 500; ++$mpv) {
755 my $info = $engine2->{'info'};
756 my $pretty_move = "";
758 last if (!exists($info->{'pv' . $mpv}));
761 my $pv = $info->{'pv' . $mpv};
762 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
763 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
764 $refutation_lines{$pv->[0]} = {
765 sort_key => $pretty_move,
766 depth => $info->{'depth' . $mpv},
767 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
768 pretty_score => short_score($info, $pos_calculating, $mpv),
769 pretty_move => $pretty_move,
770 pv_pretty => \@pretty_pv,
775 $json->{'refutation_lines'} = \%refutation_lines;
777 my $json_enc = JSON::XS->new;
778 $json_enc->canonical(1);
779 my $encoded = $json_enc->encode($json);
780 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
781 (defined($last_written_json) && $last_written_json eq $encoded)) {
782 atomic_set_contents($remoteglotconf::json_output, $encoded);
783 $last_written_json = $encoded;
786 if (exists($pos_calculating->{'pretty_history'}) &&
787 defined($remoteglotconf::json_history_dir)) {
788 my $filename = $remoteglotconf::json_history_dir . "/" . id_for_pos($pos_calculating) . ".json";
790 # Overwrite old analysis (assuming it exists at all) if we're
791 # using a different engine, or if we've calculated deeper.
792 # nodes is used as a tiebreaker. Don't bother about Multi-PV
793 # data; it's not that important.
794 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
795 my $new_depth = $json->{'depth'} // 0;
796 my $new_nodes = $json->{'nodes'} // 0;
797 if (!defined($old_engine) ||
798 $old_engine ne $json->{'id'}{'name'} ||
799 $new_depth > $old_depth ||
800 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
801 atomic_set_contents($filename, $encoded);
806 sub atomic_set_contents {
807 my ($filename, $contents) = @_;
809 open my $fh, ">", $filename . ".tmp"
813 rename($filename . ".tmp", $filename);
819 my $halfmove_num = scalar @{$pos->{'pretty_history'}};
820 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
821 return "move$halfmove_num-$fen";
824 sub get_json_analysis_stats {
825 my $filename = shift;
827 my ($engine, $depth, $nodes);
829 open my $fh, "<", $filename
833 my $json = JSON::XS::decode_json(<$fh>);
834 $engine = $json->{'id'}{'name'} // die;
835 $depth = $json->{'depth'} // 0;
836 $nodes = $json->{'nodes'} // 0;
840 warn "Error in decoding $filename: $@";
843 return ($engine, $depth, $nodes);
847 my ($engine, $msg) = @_;
848 $engine->print($msg);
849 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
853 my ($info, $pos, $mpv) = @_;
855 my $invert = ($pos->{'toplay'} eq 'B');
856 if (defined($info->{'score_mate' . $mpv})) {
858 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
860 return sprintf "M%3d", $info->{'score_mate' . $mpv};
863 if (exists($info->{'score_cp' . $mpv})) {
864 my $score = $info->{'score_cp' . $mpv} * 0.01;
866 if ($info->{'tablebase'}) {
875 return sprintf "%+5.2f", $score;
883 my ($info, $pos, $mpv, $invert) = @_;
885 if (defined($info->{'score_mate' . $mpv})) {
886 my $mate = $info->{'score_mate' . $mpv};
890 $score = 99999 - $mate;
892 # Side to move is getting mated (note the double negative for $mate)
893 $score = -99999 - $mate;
900 if (exists($info->{'score_cp' . $mpv})) {
901 my $score = $info->{'score_cp' . $mpv};
913 my ($info, $pos, $mpv) = @_;
915 if (defined($info->{'score_mate' . $mpv})) {
916 my $mate = $info->{'score_mate' . $mpv};
917 if ($pos->{'toplay'} eq 'B') {
921 return sprintf "White mates in %u", $mate;
923 return sprintf "Black mates in %u", -$mate;
926 if (exists($info->{'score_cp' . $mpv})) {
927 my $score = $info->{'score_cp' . $mpv} * 0.01;
929 if ($info->{'tablebase'}) {
930 return "Theoretical draw";
932 return "Score: 0.00";
935 if ($pos->{'toplay'} eq 'B') {
938 return sprintf "Score: %+5.2f", $score;
947 my ($fen, $board, $toplay) = @_;
949 if (exists($book_cache{$fen})) {
950 return $book_cache{$fen};
953 my $ret = `./booklook $fen`;
954 return "" if ($ret =~ /Not found/ || $ret eq '');
958 for my $m (split /\n/, $ret) {
959 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
963 $pmove = '(current)';
965 ($pmove) = prettyprint_pv_no_cache($board, $move);
966 $pmove .= $annotation;
970 if ($toplay eq 'W') {
971 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
973 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
975 my $n = $win + $draw + $lose;
981 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
984 push @moves, [ $pmove, $n, $percent, $rating ];
987 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
989 my $text = "Book moves:\n\n Perf. N Rating\n\n";
991 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
998 my ($pgn, $pos) = @_;
1000 # Look for extended PGN clock tags.
1001 my $tags = $pgn->tags;
1002 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1003 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1004 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1008 # Look for TCEC-style time comments.
1009 my $moves = $pgn->moves;
1010 my $comments = $pgn->comments;
1011 my $last_black_move = int((scalar @$moves) / 2);
1012 my $last_white_move = int((1 + scalar @$moves) / 2);
1014 my $black_key = $last_black_move . "b";
1015 my $white_key = $last_white_move . "w";
1017 if (exists($comments->{$white_key}) &&
1018 exists($comments->{$black_key}) &&
1019 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1020 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1021 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1022 $pos->{'white_clock'} = hms_to_sec($1);
1023 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1024 $pos->{'black_clock'} = hms_to_sec($1);
1028 delete $pos->{'white_clock'};
1029 delete $pos->{'black_clock'};
1034 return undef if (!defined($hms));
1035 $hms =~ /(\d+):(\d+):(\d+)/;
1036 return $1 * 3600 + $2 * 60 + $3;
1039 sub find_clock_start {
1040 my ($pos, $prev_pos) = @_;
1042 # If the game is over, the clock is stopped.
1043 if (exists($pos->{'result'}) &&
1044 ($pos->{'result'} eq '1-0' ||
1045 $pos->{'result'} eq '1/2-1/2' ||
1046 $pos->{'result'} eq '0-1')) {
1050 # When we don't have any moves, we assume the clock hasn't started yet.
1051 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1052 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1053 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1058 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1059 # The history is needed for id_for_pos.
1060 if (!exists($pos->{'pretty_history'})) {
1064 my $id = id_for_pos($pos);
1065 if (exists($clock_info_for_pos{$id})) {
1066 $pos->{'white_clock'} //= $clock_info_for_pos{$id}{'white_clock'};
1067 $pos->{'black_clock'} //= $clock_info_for_pos{$id}{'black_clock'};
1068 if ($pos->{'toplay'} eq 'W') {
1069 $pos->{'white_clock_target'} = $clock_info_for_pos{$id}->{'white_clock_target'};
1071 $pos->{'black_clock_target'} = $clock_info_for_pos{$id}->{'black_clock_target'};
1076 # OK, we haven't seen this position before, so we assume the move
1077 # happened right now.
1079 # See if we should do our own clock management (ie., clock information
1080 # is spurious or non-existent).
1081 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1082 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1083 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1084 if (defined($prev_pos->{'white_clock_target'})) {
1085 $wc = $prev_pos->{'white_clock_target'} - time;
1087 if (defined($prev_pos->{'black_clock_target'})) {
1088 $bc = $prev_pos->{'black_clock_target'} - time;
1090 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1091 $pos->{'white_clock'} = $wc;
1092 $pos->{'black_clock'} = $bc;
1095 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1096 if (!exists($pos->{$key})) {
1097 # No clock information.
1100 my $time_left = $pos->{$key};
1102 white_clock => $pos->{'white_clock'},
1103 black_clock => $pos->{'black_clock'}
1105 if ($pos->{'toplay'} eq 'W') {
1106 $clock_info->{'white_clock_target'} = $pos->{'white_clock_target'} = time + $time_left;
1108 $clock_info->{'black_clock_target'} = $pos->{'black_clock_target'} = time + $time_left;
1110 $clock_info_for_pos{$id} = $clock_info;
1113 sub schedule_tb_lookup {
1114 return if (!defined($remoteglotconf::tb_serial_key));
1115 my $pos = $pos_waiting // $pos_calculating;
1116 return if (exists($tb_cache{$pos->fen()}));
1118 # If there's more than seven pieces, there's not going to be an answer,
1120 return if ($pos->num_pieces() > 7);
1122 # Max one at a time. If it's still relevant when it returns,
1123 # schedule_tb_lookup() will be called again.
1124 return if ($tb_lookup_running);
1126 $tb_lookup_running = 1;
1127 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1128 $remoteglotconf::tb_serial_key .
1129 '&auth.password=aquarium&type=0&fen=' .
1130 URI::Escape::uri_escape($pos->fen());
1131 print TBLOG "Downloading $url...\n";
1132 AnyEvent::HTTP::http_get($url, sub {
1133 handle_tb_lookup_return(@_, $pos, $pos->fen());
1137 sub handle_tb_lookup_return {
1138 my ($body, $header, $pos, $fen) = @_;
1139 print TBLOG "Response for [$fen]:\n";
1140 print TBLOG $header . "\n\n";
1141 print TBLOG $body . "\n\n";
1143 my $response = JSON::XS::decode_json($body);
1144 if ($response->{'ErrorCode'} != 0) {
1145 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1147 my $state = $response->{'Response'}{'StateString'};
1148 if ($state eq 'COMPLETE') {
1149 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1150 if (!defined($pgn) || !$pgn->read_game()) {
1151 warn "Error in parsing PGN\n";
1153 $pgn->quick_parse_game;
1155 my $moves = $pgn->moves;
1157 for my $move (@$moves) {
1159 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1160 push @uci_moves, $uci_move;
1163 result => $pgn->result,
1165 score => $response->{'Response'}{'Score'},
1169 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1170 # Try again in a second. Note that if we have changed
1171 # position in the meantime, we might query a completely
1172 # different position! But that's fine.
1174 die "Unknown response state " . $state;
1177 # Wait a second before we schedule another one.
1178 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1179 $tb_lookup_running = 0;
1180 schedule_tb_lookup();
1184 warn "Error in tablebase lookup: $@";
1186 # Don't try this one again, but don't block new lookups either.
1187 $tb_lookup_running = 0;
1192 my ($cmdline, $tag, $cb) = @_;
1193 return undef if (!defined($cmdline));
1194 return Engine->open($cmdline, $tag, $cb);
1197 sub col_letter_to_num {
1198 return ord(shift) - ord('a');
1201 sub row_letter_to_num {
1202 return 7 - (ord(shift) - ord('1'));
1205 sub parse_uci_move {
1207 my $from_col = col_letter_to_num(substr($move, 0, 1));
1208 my $from_row = row_letter_to_num(substr($move, 1, 1));
1209 my $to_col = col_letter_to_num(substr($move, 2, 1));
1210 my $to_row = row_letter_to_num(substr($move, 3, 1));
1211 my $promo = substr($move, 4, 1);
1212 return ($from_col, $from_row, $to_col, $to_row, $promo);