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 # Skip to the right game.
277 while (defined($remoteglotconf::pgn_filter) &&
278 !&$remoteglotconf::pgn_filter($pgn)) {
279 $pgn->read_game() or die "Out of games during filtering";
282 $pgn->parse_game({ save_comments => 'yes' });
283 my $pos = Position->start_pos($pgn->white, $pgn->black);
284 my $moves = $pgn->moves;
286 for my $move (@$moves) {
288 ($pos, $uci_move) = $pos->make_pretty_move($move);
289 push @uci_moves, $uci_move;
291 $pos->{'result'} = $pgn->result;
292 $pos->{'pretty_history'} = $moves;
294 extract_clock($pgn, $pos);
296 # Sometimes, PGNs lose a move or two for a short while,
297 # or people push out new ones non-atomically.
298 # Thus, if we PGN doesn't change names but becomes
299 # shorter, we mistrust it for a few seconds.
301 if (defined($last_pgn_white) && defined($last_pgn_black) &&
302 $last_pgn_white eq $pgn->white &&
303 $last_pgn_black eq $pgn->black &&
304 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
305 if (++$pgn_hysteresis_counter < 3) {
310 $last_pgn_white = $pgn->white;
311 $last_pgn_black = $pgn->black;
312 @last_pgn_uci_moves = @uci_moves;
313 $pgn_hysteresis_counter = 0;
314 handle_position($pos);
318 warn "Error in parsing moves from $url: $@\n";
322 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
327 sub handle_position {
329 find_clock_start($pos);
331 # if this is already in the queue, ignore it
332 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
334 # if we're already chewing on this and there's nothing else in the queue,
336 return if (!defined($pos_waiting) && defined($pos_calculating) &&
337 $pos->fen() eq $pos_calculating->fen());
339 # if we're already thinking on something, stop and wait for the engine
341 if (defined($pos_calculating)) {
342 # Store the final data we have for this position in the history,
343 # with the precise clock information we just got from the new
344 # position. (Historic positions store the clock at the end of
347 # Do not output anything new to the main analysis; that's
348 # going to be obsolete really soon.
349 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
350 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
351 delete $pos_calculating->{'white_clock_target'};
352 delete $pos_calculating->{'black_clock_target'};
355 if (!defined($pos_waiting)) {
356 uciprint($engine, "stop");
358 if ($remoteglotconf::uci_assume_full_compliance) {
361 uciprint($engine, "position fen " . $pos->fen());
362 uciprint($engine, "go infinite");
363 $pos_calculating = $pos;
366 # it's wrong just to give the FEN (the move history is useful,
367 # and per the UCI spec, we should really have sent "ucinewgame"),
369 uciprint($engine, "position fen " . $pos->fen());
370 uciprint($engine, "go infinite");
371 $pos_calculating = $pos;
374 if (defined($engine2)) {
375 if (defined($pos_calculating_second_engine)) {
376 uciprint($engine2, "stop");
378 uciprint($engine2, "position fen " . $pos->fen());
379 uciprint($engine2, "go infinite");
380 $pos_calculating_second_engine = $pos;
382 $engine2->{'info'} = {};
385 $engine->{'info'} = {};
388 schedule_tb_lookup();
391 # Output a command every move to note that we're
392 # still paying attention -- this is a good tradeoff,
393 # since if no move has happened in the last half
394 # hour, the analysis/relay has most likely stopped
395 # and we should stop hogging server resources.
401 my ($engine, @x) = @_;
404 my $info = $engine->{'info'};
406 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
407 for my $i (0..$#x - 1) {
408 if ($x[$i] eq 'multipv') {
414 while (scalar @x > 0) {
415 if ($x[0] eq 'multipv') {
421 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
423 my $value = shift @x;
424 $info->{$key} = $value;
427 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
428 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
431 my $value = shift @x;
432 $info->{$key . $mpv} = $value;
435 if ($x[0] eq 'score') {
438 delete $info->{'score_cp' . $mpv};
439 delete $info->{'score_mate' . $mpv};
441 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
444 $info->{'score_cp' . $mpv} = shift @x;
445 } elsif ($x[0] eq 'mate') {
447 $info->{'score_mate' . $mpv} = shift @x;
455 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
458 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
462 #print "unknown info '$x[0]', trying to recover...\n";
464 die "Unknown info '" . join(',', @x) . "'";
470 my ($engine, @x) = @_;
472 while (scalar @x > 0) {
473 if ($x[0] =~ /^(name|author)$/) {
475 my $value = join(' ', @x);
476 $engine->{'id'}{$key} = $value;
485 sub prettyprint_pv_no_cache {
486 my ($board, @pvs) = @_;
488 if (scalar @pvs == 0 || !defined($pvs[0])) {
493 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
494 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
495 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
499 my ($pos, @pvs) = @_;
501 my $cachekey = join('', @pvs);
502 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
503 return @{$pos->{'prettyprint_cache'}{$cachekey}};
505 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
506 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
514 return if (!defined($pos_calculating));
516 # Don't update too often.
517 my $age = Time::HiRes::tv_interval($latest_update);
518 if ($age < $remoteglotconf::update_max_interval) {
519 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
520 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
524 my $info = $engine->{'info'};
527 # If we have tablebase data from a previous lookup, replace the
528 # engine data with the data from the tablebase.
530 my $fen = $pos_calculating->fen();
531 if (exists($tb_cache{$fen})) {
532 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
533 delete $info->{$key . '1'};
534 delete $info->{$key};
536 $info->{'nodes'} = 0;
538 $info->{'depth'} = 0;
539 $info->{'seldepth'} = 0;
540 $info->{'tbhits'} = 0;
542 my $t = $tb_cache{$fen};
544 my $matelen = int((1 + $t->{'score'}) / 2);
545 if ($t->{'result'} eq '1/2-1/2') {
546 $info->{'score_cp'} = 0;
547 } elsif ($t->{'result'} eq '1-0') {
548 if ($pos_calculating->{'toplay'} eq 'B') {
549 $info->{'score_mate'} = -$matelen;
551 $info->{'score_mate'} = $matelen;
554 if ($pos_calculating->{'toplay'} eq 'B') {
555 $info->{'score_mate'} = $matelen;
557 $info->{'score_mate'} = -$matelen;
561 $info->{'tablebase'} = 1;
563 $info->{'tablebase'} = 0;
567 # Some programs _always_ report MultiPV, even with only one PV.
568 # In this case, we simply use that data as if MultiPV was never
571 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
572 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
573 if (exists($info->{$key . '1'})) {
574 $info->{$key} = $info->{$key . '1'};
580 # Check the PVs first. if they're invalid, just wait, as our data
581 # is most likely out of sync. This isn't a very good solution, as
582 # it can frequently miss stuff, but it's good enough for most users.
586 if (exists($info->{'pv'})) {
587 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
591 while (exists($info->{'pv' . $mpv})) {
592 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
597 $engine->{'info'} = {};
603 $latest_update = [Time::HiRes::gettimeofday];
607 my $info = $engine->{'info'};
608 my $id = $engine->{'id'};
610 my $text = 'Analysis';
611 if ($pos_calculating->{'last_move'} ne 'none') {
612 if ($pos_calculating->{'toplay'} eq 'W') {
613 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
615 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
617 if (exists($id->{'name'})) {
622 if (exists($id->{'name'})) {
623 $text .= " by $id->{'name'}:\n\n";
628 return unless (exists($pos_calculating->{'board'}));
630 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
633 while (exists($info->{'pv' . $mpv})) {
634 $text .= sprintf " PV%2u", $mpv;
635 my $score = short_score($info, $pos_calculating, $mpv);
636 $text .= " ($score)" if (defined($score));
639 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
640 if ($info->{'tbhits' . $mpv} == 1) {
641 $tbhits = ", 1 tbhit";
643 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
647 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
648 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
649 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
653 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
659 my $score = long_score($info, $pos_calculating, '');
660 $text .= " $score\n" if defined($score);
661 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
664 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
665 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
666 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
668 if (exists($info->{'seldepth'})) {
669 $text .= sprintf " (%u selective)", $info->{'seldepth'};
671 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
672 if ($info->{'tbhits'} == 1) {
673 $text .= ", one Syzygy hit";
675 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
681 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
683 my @refutation_lines = ();
684 if (defined($engine2)) {
685 for (my $mpv = 1; $mpv < 500; ++$mpv) {
686 my $info = $engine2->{'info'};
687 last if (!exists($info->{'pv' . $mpv}));
689 my $pv = $info->{'pv' . $mpv};
691 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
692 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
693 if (scalar @pretty_pv > 5) {
694 @pretty_pv = @pretty_pv[0..4];
695 push @pretty_pv, "...";
697 my $key = $pretty_move;
698 my $line = sprintf(" %-6s %6s %3s %s",
700 short_score($info, $pos_calculating_second_engine, $mpv),
701 "d" . $info->{'depth' . $mpv},
702 join(', ', @pretty_pv));
703 push @refutation_lines, [ $key, $line ];
708 if ($#refutation_lines >= 0) {
709 $text .= "Shallow search of all legal moves:\n\n";
710 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
711 $text .= $line->[1] . "\n";
716 if ($last_text ne $text) {
717 print "
\e[H
\e[2J"; # clear the screen
724 my $historic_json_only = shift;
725 my $info = $engine->{'info'};
728 $json->{'position'} = $pos_calculating->to_json_hash();
729 $json->{'id'} = $engine->{'id'};
730 $json->{'score'} = long_score($info, $pos_calculating, '');
731 $json->{'short_score'} = short_score($info, $pos_calculating, '');
733 $json->{'nodes'} = $info->{'nodes'};
734 $json->{'nps'} = $info->{'nps'};
735 $json->{'depth'} = $info->{'depth'};
736 $json->{'tbhits'} = $info->{'tbhits'};
737 $json->{'seldepth'} = $info->{'seldepth'};
738 $json->{'tablebase'} = $info->{'tablebase'};
740 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
741 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
743 my %refutation_lines = ();
744 my @refutation_lines = ();
745 if (defined($engine2)) {
746 for (my $mpv = 1; $mpv < 500; ++$mpv) {
747 my $info = $engine2->{'info'};
748 my $pretty_move = "";
750 last if (!exists($info->{'pv' . $mpv}));
753 my $pv = $info->{'pv' . $mpv};
754 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
755 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
756 $refutation_lines{$pv->[0]} = {
757 sort_key => $pretty_move,
758 depth => $info->{'depth' . $mpv},
759 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
760 pretty_score => short_score($info, $pos_calculating, $mpv),
761 pretty_move => $pretty_move,
762 pv_pretty => \@pretty_pv,
767 $json->{'refutation_lines'} = \%refutation_lines;
769 my $encoded = JSON::XS::encode_json($json);
770 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
771 (defined($last_written_json) && $last_written_json eq $encoded)) {
772 atomic_set_contents($remoteglotconf::json_output, $encoded);
773 $last_written_json = $encoded;
776 if (exists($pos_calculating->{'pretty_history'}) &&
777 defined($remoteglotconf::json_history_dir)) {
778 my $filename = $remoteglotconf::json_history_dir . "/" . id_for_pos($pos_calculating) . ".json";
780 # Overwrite old analysis (assuming it exists at all) if we're
781 # using a different engine, or if we've calculated deeper.
782 # nodes is used as a tiebreaker. Don't bother about Multi-PV
783 # data; it's not that important.
784 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
785 my $new_depth = $json->{'depth'} // 0;
786 my $new_nodes = $json->{'nodes'} // 0;
787 if (!defined($old_engine) ||
788 $old_engine ne $json->{'id'}{'name'} ||
789 $new_depth > $old_depth ||
790 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
791 atomic_set_contents($filename, $encoded);
796 sub atomic_set_contents {
797 my ($filename, $contents) = @_;
799 open my $fh, ">", $filename . ".tmp"
803 rename($filename . ".tmp", $filename);
809 my $halfmove_num = scalar @{$pos->{'pretty_history'}};
810 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
811 return "move$halfmove_num-$fen";
814 sub get_json_analysis_stats {
815 my $filename = shift;
817 my ($engine, $depth, $nodes);
819 open my $fh, "<", $filename
823 my $json = JSON::XS::decode_json(<$fh>);
824 $engine = $json->{'id'}{'name'} // die;
825 $depth = $json->{'depth'} // 0;
826 $nodes = $json->{'nodes'} // 0;
830 warn "Error in decoding $filename: $@";
833 return ($engine, $depth, $nodes);
837 my ($engine, $msg) = @_;
838 $engine->print($msg);
839 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
843 my ($info, $pos, $mpv) = @_;
845 my $invert = ($pos->{'toplay'} eq 'B');
846 if (defined($info->{'score_mate' . $mpv})) {
848 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
850 return sprintf "M%3d", $info->{'score_mate' . $mpv};
853 if (exists($info->{'score_cp' . $mpv})) {
854 my $score = $info->{'score_cp' . $mpv} * 0.01;
856 if ($info->{'tablebase'}) {
865 return sprintf "%+5.2f", $score;
873 my ($info, $pos, $mpv, $invert) = @_;
875 if (defined($info->{'score_mate' . $mpv})) {
876 my $mate = $info->{'score_mate' . $mpv};
880 $score = 99999 - $mate;
882 # Side to move is getting mated (note the double negative for $mate)
883 $score = -99999 - $mate;
890 if (exists($info->{'score_cp' . $mpv})) {
891 my $score = $info->{'score_cp' . $mpv};
903 my ($info, $pos, $mpv) = @_;
905 if (defined($info->{'score_mate' . $mpv})) {
906 my $mate = $info->{'score_mate' . $mpv};
907 if ($pos->{'toplay'} eq 'B') {
911 return sprintf "White mates in %u", $mate;
913 return sprintf "Black mates in %u", -$mate;
916 if (exists($info->{'score_cp' . $mpv})) {
917 my $score = $info->{'score_cp' . $mpv} * 0.01;
919 if ($info->{'tablebase'}) {
920 return "Theoretical draw";
922 return "Score: 0.00";
925 if ($pos->{'toplay'} eq 'B') {
928 return sprintf "Score: %+5.2f", $score;
937 my ($fen, $board, $toplay) = @_;
939 if (exists($book_cache{$fen})) {
940 return $book_cache{$fen};
943 my $ret = `./booklook $fen`;
944 return "" if ($ret =~ /Not found/ || $ret eq '');
948 for my $m (split /\n/, $ret) {
949 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
953 $pmove = '(current)';
955 ($pmove) = prettyprint_pv_no_cache($board, $move);
956 $pmove .= $annotation;
960 if ($toplay eq 'W') {
961 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
963 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
965 my $n = $win + $draw + $lose;
971 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
974 push @moves, [ $pmove, $n, $percent, $rating ];
977 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
979 my $text = "Book moves:\n\n Perf. N Rating\n\n";
981 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
988 my ($pgn, $pos) = @_;
990 # Look for extended PGN clock tags.
991 my $tags = $pgn->tags;
992 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
993 $pos->{'white_clock'} = $tags->{'WhiteClock'};
994 $pos->{'black_clock'} = $tags->{'BlackClock'};
996 $pos->{'white_clock'} =~ s/\b(\d)\b/0$1/g;
997 $pos->{'black_clock'} =~ s/\b(\d)\b/0$1/g;
1001 # Look for TCEC-style time comments.
1002 my $moves = $pgn->moves;
1003 my $comments = $pgn->comments;
1004 my $last_black_move = int((scalar @$moves) / 2);
1005 my $last_white_move = int((1 + scalar @$moves) / 2);
1007 my $black_key = $last_black_move . "b";
1008 my $white_key = $last_white_move . "w";
1010 if (exists($comments->{$white_key}) &&
1011 exists($comments->{$black_key}) &&
1012 $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/ &&
1013 $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/) {
1014 $comments->{$white_key} =~ /tl=(\d+:\d+:\d+)/;
1015 $pos->{'white_clock'} = $1;
1016 $comments->{$black_key} =~ /tl=(\d+:\d+:\d+)/;
1017 $pos->{'black_clock'} = $1;
1022 sub find_clock_start {
1025 # If the game is over, the clock is stopped.
1026 if (exists($pos->{'result'}) &&
1027 ($pos->{'result'} eq '1-0' ||
1028 $pos->{'result'} eq '1/2-1/2' ||
1029 $pos->{'result'} eq '0-1')) {
1033 # When we don't have any moves, we assume the clock hasn't started yet.
1034 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1038 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1039 if (!exists($pos->{'pretty_history'})) {
1043 my $id = id_for_pos($pos);
1044 if (exists($clock_target_for_pos{$id})) {
1045 if ($pos->{'toplay'} eq 'W') {
1046 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1048 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1053 # OK, we haven't seen this position before, so we assume the move
1054 # happened right now.
1055 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1056 if (!exists($pos->{$key})) {
1057 # No clock information.
1060 $pos->{$key} =~ /(\d+):(\d+):(\d+)/;
1061 my $time_left = $1 * 3600 + $2 * 60 + $3;
1062 $clock_target_for_pos{$id} = time + $time_left;
1063 if ($pos->{'toplay'} eq 'W') {
1064 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1066 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1070 sub schedule_tb_lookup {
1071 return if (!defined($remoteglotconf::tb_serial_key));
1072 my $pos = $pos_waiting // $pos_calculating;
1073 return if (exists($tb_cache{$pos->fen()}));
1075 # If there's more than seven pieces, there's not going to be an answer,
1077 return if ($pos->num_pieces() > 7);
1079 # Max one at a time. If it's still relevant when it returns,
1080 # schedule_tb_lookup() will be called again.
1081 return if ($tb_lookup_running);
1083 $tb_lookup_running = 1;
1084 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1085 $remoteglotconf::tb_serial_key .
1086 '&auth.password=aquarium&type=0&fen=' .
1087 URI::Escape::uri_escape($pos->fen());
1088 print TBLOG "Downloading $url...\n";
1089 AnyEvent::HTTP::http_get($url, sub {
1090 handle_tb_lookup_return(@_, $pos, $pos->fen());
1094 sub handle_tb_lookup_return {
1095 my ($body, $header, $pos, $fen) = @_;
1096 print TBLOG "Response for [$fen]:\n";
1097 print TBLOG $header . "\n\n";
1098 print TBLOG $body . "\n\n";
1100 my $response = JSON::XS::decode_json($body);
1101 if ($response->{'ErrorCode'} != 0) {
1102 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1104 my $state = $response->{'Response'}{'StateString'};
1105 if ($state eq 'COMPLETE') {
1106 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1107 if (!defined($pgn) || !$pgn->read_game()) {
1108 warn "Error in parsing PGN\n";
1110 $pgn->quick_parse_game;
1112 my $moves = $pgn->moves;
1114 for my $move (@$moves) {
1116 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1117 push @uci_moves, $uci_move;
1120 result => $pgn->result,
1122 score => $response->{'Response'}{'Score'},
1126 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1127 # Try again in a second. Note that if we have changed
1128 # position in the meantime, we might query a completely
1129 # different position! But that's fine.
1131 die "Unknown response state " . $state;
1134 # Wait a second before we schedule another one.
1135 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1136 $tb_lookup_running = 0;
1137 schedule_tb_lookup();
1141 warn "Error in tablebase lookup: $@";
1143 # Don't try this one again, but don't block new lookups either.
1144 $tb_lookup_running = 0;
1149 my ($cmdline, $tag, $cb) = @_;
1150 return undef if (!defined($cmdline));
1151 return Engine->open($cmdline, $tag, $cb);
1154 sub col_letter_to_num {
1155 return ord(shift) - ord('a');
1158 sub row_letter_to_num {
1159 return 7 - (ord(shift) - ord('1'));
1162 sub parse_uci_move {
1164 my $from_col = col_letter_to_num(substr($move, 0, 1));
1165 my $from_row = row_letter_to_num(substr($move, 1, 1));
1166 my $to_col = col_letter_to_num(substr($move, 2, 1));
1167 my $to_row = row_letter_to_num(substr($move, 3, 1));
1168 my $promo = substr($move, 4, 1);
1169 return ($from_col, $from_row, $to_col, $to_row, $promo);