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 (just update the result)
332 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
333 $pos_waiting->{'result'} = $pos->{'result'};
337 # if we're already chewing on this and there's nothing else in the queue,
339 if (!defined($pos_waiting) && defined($pos_calculating) &&
340 $pos->fen() eq $pos_calculating->fen()) {
341 $pos_calculating->{'result'} = $pos->{'result'};
345 # if we're already thinking on something, stop and wait for the engine
347 if (defined($pos_calculating)) {
348 # Store the final data we have for this position in the history,
349 # with the precise clock information we just got from the new
350 # position. (Historic positions store the clock at the end of
353 # Do not output anything new to the main analysis; that's
354 # going to be obsolete really soon.
355 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
356 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
357 delete $pos_calculating->{'white_clock_target'};
358 delete $pos_calculating->{'black_clock_target'};
361 if (!defined($pos_waiting)) {
362 uciprint($engine, "stop");
364 if ($remoteglotconf::uci_assume_full_compliance) {
367 uciprint($engine, "position fen " . $pos->fen());
368 uciprint($engine, "go infinite");
369 $pos_calculating = $pos;
372 # it's wrong just to give the FEN (the move history is useful,
373 # and per the UCI spec, we should really have sent "ucinewgame"),
375 uciprint($engine, "position fen " . $pos->fen());
376 uciprint($engine, "go infinite");
377 $pos_calculating = $pos;
380 if (defined($engine2)) {
381 if (defined($pos_calculating_second_engine)) {
382 uciprint($engine2, "stop");
384 uciprint($engine2, "position fen " . $pos->fen());
385 uciprint($engine2, "go infinite");
386 $pos_calculating_second_engine = $pos;
388 $engine2->{'info'} = {};
391 $engine->{'info'} = {};
394 schedule_tb_lookup();
397 # Output a command every move to note that we're
398 # still paying attention -- this is a good tradeoff,
399 # since if no move has happened in the last half
400 # hour, the analysis/relay has most likely stopped
401 # and we should stop hogging server resources.
407 my ($engine, @x) = @_;
410 my $info = $engine->{'info'};
412 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
413 for my $i (0..$#x - 1) {
414 if ($x[$i] eq 'multipv') {
420 while (scalar @x > 0) {
421 if ($x[0] eq 'multipv') {
427 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
429 my $value = shift @x;
430 $info->{$key} = $value;
433 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
434 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
437 my $value = shift @x;
438 $info->{$key . $mpv} = $value;
441 if ($x[0] eq 'score') {
444 delete $info->{'score_cp' . $mpv};
445 delete $info->{'score_mate' . $mpv};
447 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
450 $info->{'score_cp' . $mpv} = shift @x;
451 } elsif ($x[0] eq 'mate') {
453 $info->{'score_mate' . $mpv} = shift @x;
461 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
464 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
468 #print "unknown info '$x[0]', trying to recover...\n";
470 die "Unknown info '" . join(',', @x) . "'";
476 my ($engine, @x) = @_;
478 while (scalar @x > 0) {
479 if ($x[0] =~ /^(name|author)$/) {
481 my $value = join(' ', @x);
482 $engine->{'id'}{$key} = $value;
491 sub prettyprint_pv_no_cache {
492 my ($board, @pvs) = @_;
494 if (scalar @pvs == 0 || !defined($pvs[0])) {
499 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
500 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
501 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
505 my ($pos, @pvs) = @_;
507 my $cachekey = join('', @pvs);
508 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
509 return @{$pos->{'prettyprint_cache'}{$cachekey}};
511 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
512 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
520 return if (!defined($pos_calculating));
522 # Don't update too often.
523 my $age = Time::HiRes::tv_interval($latest_update);
524 if ($age < $remoteglotconf::update_max_interval) {
525 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
526 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
530 my $info = $engine->{'info'};
533 # If we have tablebase data from a previous lookup, replace the
534 # engine data with the data from the tablebase.
536 my $fen = $pos_calculating->fen();
537 if (exists($tb_cache{$fen})) {
538 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
539 delete $info->{$key . '1'};
540 delete $info->{$key};
542 $info->{'nodes'} = 0;
544 $info->{'depth'} = 0;
545 $info->{'seldepth'} = 0;
546 $info->{'tbhits'} = 0;
548 my $t = $tb_cache{$fen};
550 my $matelen = int((1 + $t->{'score'}) / 2);
551 if ($t->{'result'} eq '1/2-1/2') {
552 $info->{'score_cp'} = 0;
553 } elsif ($t->{'result'} eq '1-0') {
554 if ($pos_calculating->{'toplay'} eq 'B') {
555 $info->{'score_mate'} = -$matelen;
557 $info->{'score_mate'} = $matelen;
560 if ($pos_calculating->{'toplay'} eq 'B') {
561 $info->{'score_mate'} = $matelen;
563 $info->{'score_mate'} = -$matelen;
567 $info->{'tablebase'} = 1;
569 $info->{'tablebase'} = 0;
573 # Some programs _always_ report MultiPV, even with only one PV.
574 # In this case, we simply use that data as if MultiPV was never
577 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
578 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
579 if (exists($info->{$key . '1'})) {
580 $info->{$key} = $info->{$key . '1'};
586 # Check the PVs first. if they're invalid, just wait, as our data
587 # is most likely out of sync. This isn't a very good solution, as
588 # it can frequently miss stuff, but it's good enough for most users.
592 if (exists($info->{'pv'})) {
593 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
597 while (exists($info->{'pv' . $mpv})) {
598 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
603 $engine->{'info'} = {};
609 $latest_update = [Time::HiRes::gettimeofday];
613 my $info = $engine->{'info'};
614 my $id = $engine->{'id'};
616 my $text = 'Analysis';
617 if ($pos_calculating->{'last_move'} ne 'none') {
618 if ($pos_calculating->{'toplay'} eq 'W') {
619 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
621 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
623 if (exists($id->{'name'})) {
628 if (exists($id->{'name'})) {
629 $text .= " by $id->{'name'}:\n\n";
634 return unless (exists($pos_calculating->{'board'}));
636 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
639 while (exists($info->{'pv' . $mpv})) {
640 $text .= sprintf " PV%2u", $mpv;
641 my $score = short_score($info, $pos_calculating, $mpv);
642 $text .= " ($score)" if (defined($score));
645 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
646 if ($info->{'tbhits' . $mpv} == 1) {
647 $tbhits = ", 1 tbhit";
649 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
653 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
654 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
655 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
659 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
665 my $score = long_score($info, $pos_calculating, '');
666 $text .= " $score\n" if defined($score);
667 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
670 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
671 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
672 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
674 if (exists($info->{'seldepth'})) {
675 $text .= sprintf " (%u selective)", $info->{'seldepth'};
677 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
678 if ($info->{'tbhits'} == 1) {
679 $text .= ", one Syzygy hit";
681 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
687 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
689 my @refutation_lines = ();
690 if (defined($engine2)) {
691 for (my $mpv = 1; $mpv < 500; ++$mpv) {
692 my $info = $engine2->{'info'};
693 last if (!exists($info->{'pv' . $mpv}));
695 my $pv = $info->{'pv' . $mpv};
697 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
698 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
699 if (scalar @pretty_pv > 5) {
700 @pretty_pv = @pretty_pv[0..4];
701 push @pretty_pv, "...";
703 my $key = $pretty_move;
704 my $line = sprintf(" %-6s %6s %3s %s",
706 short_score($info, $pos_calculating_second_engine, $mpv),
707 "d" . $info->{'depth' . $mpv},
708 join(', ', @pretty_pv));
709 push @refutation_lines, [ $key, $line ];
714 if ($#refutation_lines >= 0) {
715 $text .= "Shallow search of all legal moves:\n\n";
716 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
717 $text .= $line->[1] . "\n";
722 if ($last_text ne $text) {
723 print "
\e[H
\e[2J"; # clear the screen
730 my $historic_json_only = shift;
731 my $info = $engine->{'info'};
734 $json->{'position'} = $pos_calculating->to_json_hash();
735 $json->{'id'} = $engine->{'id'};
736 $json->{'score'} = long_score($info, $pos_calculating, '');
737 $json->{'short_score'} = short_score($info, $pos_calculating, '');
739 $json->{'nodes'} = $info->{'nodes'};
740 $json->{'nps'} = $info->{'nps'};
741 $json->{'depth'} = $info->{'depth'};
742 $json->{'tbhits'} = $info->{'tbhits'};
743 $json->{'seldepth'} = $info->{'seldepth'};
744 $json->{'tablebase'} = $info->{'tablebase'};
746 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
747 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
749 my %refutation_lines = ();
750 my @refutation_lines = ();
751 if (defined($engine2)) {
752 for (my $mpv = 1; $mpv < 500; ++$mpv) {
753 my $info = $engine2->{'info'};
754 my $pretty_move = "";
756 last if (!exists($info->{'pv' . $mpv}));
759 my $pv = $info->{'pv' . $mpv};
760 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
761 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
762 $refutation_lines{$pv->[0]} = {
763 sort_key => $pretty_move,
764 depth => $info->{'depth' . $mpv},
765 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
766 pretty_score => short_score($info, $pos_calculating, $mpv),
767 pretty_move => $pretty_move,
768 pv_pretty => \@pretty_pv,
773 $json->{'refutation_lines'} = \%refutation_lines;
775 my $encoded = JSON::XS::encode_json($json);
776 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
777 (defined($last_written_json) && $last_written_json eq $encoded)) {
778 atomic_set_contents($remoteglotconf::json_output, $encoded);
779 $last_written_json = $encoded;
782 if (exists($pos_calculating->{'pretty_history'}) &&
783 defined($remoteglotconf::json_history_dir)) {
784 my $filename = $remoteglotconf::json_history_dir . "/" . id_for_pos($pos_calculating) . ".json";
786 # Overwrite old analysis (assuming it exists at all) if we're
787 # using a different engine, or if we've calculated deeper.
788 # nodes is used as a tiebreaker. Don't bother about Multi-PV
789 # data; it's not that important.
790 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($filename);
791 my $new_depth = $json->{'depth'} // 0;
792 my $new_nodes = $json->{'nodes'} // 0;
793 if (!defined($old_engine) ||
794 $old_engine ne $json->{'id'}{'name'} ||
795 $new_depth > $old_depth ||
796 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
797 atomic_set_contents($filename, $encoded);
802 sub atomic_set_contents {
803 my ($filename, $contents) = @_;
805 open my $fh, ">", $filename . ".tmp"
809 rename($filename . ".tmp", $filename);
815 my $halfmove_num = scalar @{$pos->{'pretty_history'}};
816 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
817 return "move$halfmove_num-$fen";
820 sub get_json_analysis_stats {
821 my $filename = shift;
823 my ($engine, $depth, $nodes);
825 open my $fh, "<", $filename
829 my $json = JSON::XS::decode_json(<$fh>);
830 $engine = $json->{'id'}{'name'} // die;
831 $depth = $json->{'depth'} // 0;
832 $nodes = $json->{'nodes'} // 0;
836 warn "Error in decoding $filename: $@";
839 return ($engine, $depth, $nodes);
843 my ($engine, $msg) = @_;
844 $engine->print($msg);
845 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
849 my ($info, $pos, $mpv) = @_;
851 my $invert = ($pos->{'toplay'} eq 'B');
852 if (defined($info->{'score_mate' . $mpv})) {
854 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
856 return sprintf "M%3d", $info->{'score_mate' . $mpv};
859 if (exists($info->{'score_cp' . $mpv})) {
860 my $score = $info->{'score_cp' . $mpv} * 0.01;
862 if ($info->{'tablebase'}) {
871 return sprintf "%+5.2f", $score;
879 my ($info, $pos, $mpv, $invert) = @_;
881 if (defined($info->{'score_mate' . $mpv})) {
882 my $mate = $info->{'score_mate' . $mpv};
886 $score = 99999 - $mate;
888 # Side to move is getting mated (note the double negative for $mate)
889 $score = -99999 - $mate;
896 if (exists($info->{'score_cp' . $mpv})) {
897 my $score = $info->{'score_cp' . $mpv};
909 my ($info, $pos, $mpv) = @_;
911 if (defined($info->{'score_mate' . $mpv})) {
912 my $mate = $info->{'score_mate' . $mpv};
913 if ($pos->{'toplay'} eq 'B') {
917 return sprintf "White mates in %u", $mate;
919 return sprintf "Black mates in %u", -$mate;
922 if (exists($info->{'score_cp' . $mpv})) {
923 my $score = $info->{'score_cp' . $mpv} * 0.01;
925 if ($info->{'tablebase'}) {
926 return "Theoretical draw";
928 return "Score: 0.00";
931 if ($pos->{'toplay'} eq 'B') {
934 return sprintf "Score: %+5.2f", $score;
943 my ($fen, $board, $toplay) = @_;
945 if (exists($book_cache{$fen})) {
946 return $book_cache{$fen};
949 my $ret = `./booklook $fen`;
950 return "" if ($ret =~ /Not found/ || $ret eq '');
954 for my $m (split /\n/, $ret) {
955 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
959 $pmove = '(current)';
961 ($pmove) = prettyprint_pv_no_cache($board, $move);
962 $pmove .= $annotation;
966 if ($toplay eq 'W') {
967 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
969 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
971 my $n = $win + $draw + $lose;
977 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
980 push @moves, [ $pmove, $n, $percent, $rating ];
983 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
985 my $text = "Book moves:\n\n Perf. N Rating\n\n";
987 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
994 my ($pgn, $pos) = @_;
996 # Look for extended PGN clock tags.
997 my $tags = $pgn->tags;
998 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
999 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1000 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1004 # Look for TCEC-style time comments.
1005 my $moves = $pgn->moves;
1006 my $comments = $pgn->comments;
1007 my $last_black_move = int((scalar @$moves) / 2);
1008 my $last_white_move = int((1 + scalar @$moves) / 2);
1010 my $black_key = $last_black_move . "b";
1011 my $white_key = $last_white_move . "w";
1013 if (exists($comments->{$white_key}) &&
1014 exists($comments->{$black_key}) &&
1015 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1016 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1017 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1018 $pos->{'white_clock'} = hms_to_sec($1);
1019 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1020 $pos->{'black_clock'} = hms_to_sec($1);
1024 delete $pos->{'white_clock'};
1025 delete $pos->{'black_clock'};
1030 return undef if (!defined($hms));
1031 $hms =~ /(\d+):(\d+):(\d+)/;
1032 return $1 * 3600 + $2 * 60 + $3;
1035 sub find_clock_start {
1038 # If the game is over, the clock is stopped.
1039 if (exists($pos->{'result'}) &&
1040 ($pos->{'result'} eq '1-0' ||
1041 $pos->{'result'} eq '1/2-1/2' ||
1042 $pos->{'result'} eq '0-1')) {
1046 # When we don't have any moves, we assume the clock hasn't started yet.
1047 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1051 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1052 # The history is needed for id_for_pos.
1053 if (!exists($pos->{'pretty_history'})) {
1057 my $id = id_for_pos($pos);
1058 if (exists($clock_target_for_pos{$id})) {
1059 if ($pos->{'toplay'} eq 'W') {
1060 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1062 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1067 # OK, we haven't seen this position before, so we assume the move
1068 # happened right now.
1069 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1070 if (!exists($pos->{$key})) {
1071 # No clock information.
1074 my $time_left = $pos->{$key};
1075 $clock_target_for_pos{$id} = time + $time_left;
1076 if ($pos->{'toplay'} eq 'W') {
1077 $pos->{'white_clock_target'} = $clock_target_for_pos{$id};
1079 $pos->{'black_clock_target'} = $clock_target_for_pos{$id};
1083 sub schedule_tb_lookup {
1084 return if (!defined($remoteglotconf::tb_serial_key));
1085 my $pos = $pos_waiting // $pos_calculating;
1086 return if (exists($tb_cache{$pos->fen()}));
1088 # If there's more than seven pieces, there's not going to be an answer,
1090 return if ($pos->num_pieces() > 7);
1092 # Max one at a time. If it's still relevant when it returns,
1093 # schedule_tb_lookup() will be called again.
1094 return if ($tb_lookup_running);
1096 $tb_lookup_running = 1;
1097 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1098 $remoteglotconf::tb_serial_key .
1099 '&auth.password=aquarium&type=0&fen=' .
1100 URI::Escape::uri_escape($pos->fen());
1101 print TBLOG "Downloading $url...\n";
1102 AnyEvent::HTTP::http_get($url, sub {
1103 handle_tb_lookup_return(@_, $pos, $pos->fen());
1107 sub handle_tb_lookup_return {
1108 my ($body, $header, $pos, $fen) = @_;
1109 print TBLOG "Response for [$fen]:\n";
1110 print TBLOG $header . "\n\n";
1111 print TBLOG $body . "\n\n";
1113 my $response = JSON::XS::decode_json($body);
1114 if ($response->{'ErrorCode'} != 0) {
1115 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1117 my $state = $response->{'Response'}{'StateString'};
1118 if ($state eq 'COMPLETE') {
1119 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1120 if (!defined($pgn) || !$pgn->read_game()) {
1121 warn "Error in parsing PGN\n";
1123 $pgn->quick_parse_game;
1125 my $moves = $pgn->moves;
1127 for my $move (@$moves) {
1129 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1130 push @uci_moves, $uci_move;
1133 result => $pgn->result,
1135 score => $response->{'Response'}{'Score'},
1139 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1140 # Try again in a second. Note that if we have changed
1141 # position in the meantime, we might query a completely
1142 # different position! But that's fine.
1144 die "Unknown response state " . $state;
1147 # Wait a second before we schedule another one.
1148 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1149 $tb_lookup_running = 0;
1150 schedule_tb_lookup();
1154 warn "Error in tablebase lookup: $@";
1156 # Don't try this one again, but don't block new lookups either.
1157 $tb_lookup_running = 0;
1162 my ($cmdline, $tag, $cb) = @_;
1163 return undef if (!defined($cmdline));
1164 return Engine->open($cmdline, $tag, $cb);
1167 sub col_letter_to_num {
1168 return ord(shift) - ord('a');
1171 sub row_letter_to_num {
1172 return 7 - (ord(shift) - ord('1'));
1175 sub parse_uci_move {
1177 my $from_col = col_letter_to_num(substr($move, 0, 1));
1178 my $from_row = row_letter_to_num(substr($move, 1, 1));
1179 my $to_col = col_letter_to_num(substr($move, 2, 1));
1180 my $to_row = row_letter_to_num(substr($move, 3, 1));
1181 my $promo = substr($move, 4, 1);
1182 return ($from_col, $from_row, $to_col, $to_row, $promo);