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 <steinar+remoteglot@gunderson.no>
9 # Licensed under the GNU General Public License, version 2.
15 use Chess::PGN::Parse;
25 require 'Position.pm';
33 my $latest_update = undef;
34 my $output_timer = undef;
35 my $http_timer = undef;
36 my $stop_pgn_fetch = 0;
37 my $tb_retry_timer = undef;
39 my $tb_lookup_running = 0;
40 my $last_written_json = undef;
42 # Persisted so we can restart.
43 # TODO: Figure out an appropriate way to deal with database restarts
44 # and/or Postgres going away entirely.
45 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
47 $dbh->{RaiseError} = 1;
51 open(FICSLOG, ">ficslog.txt")
52 or die "ficslog.txt: $!";
53 print FICSLOG "Log starting.\n";
57 open(UCILOG, ">ucilog.txt")
58 or die "ucilog.txt: $!";
59 print UCILOG "Log starting.\n";
63 open(TBLOG, ">tblog.txt")
64 or die "tblog.txt: $!";
65 print TBLOG "Log starting.\n";
70 umask 0022; # analysis.json should not be served to users.
72 # open the chess engine
73 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
74 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
77 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
79 uciprint($engine, "setoption name UCI_AnalyseMode value true");
80 while (my ($key, $value) = each %remoteglotconf::engine_config) {
81 uciprint($engine, "setoption name $key value $value");
83 uciprint($engine, "ucinewgame");
85 if (defined($engine2)) {
86 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
87 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
88 uciprint($engine2, "setoption name $key value $value");
90 uciprint($engine2, "setoption name MultiPV value 500");
91 uciprint($engine2, "ucinewgame");
94 print "Chess engine ready.\n";
98 if (defined($remoteglotconf::server)) {
99 $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
100 $t->input_log(\*FICSLOG);
101 $t->open($remoteglotconf::server);
102 $t->print($remoteglotconf::nick);
103 $t->waitfor('/Press return to enter the server/');
107 $t->cmd("set shout 0");
108 $t->cmd("set seek 0");
109 $t->cmd("set style 12");
114 cb => sub { # what callback to execute
116 my $line = $t->getline(Timeout => 0, errmode => 'return');
117 return if (!defined($line));
126 if (defined($remoteglotconf::target)) {
127 if ($remoteglotconf::target =~ /^https?:/) {
128 fetch_pgn($remoteglotconf::target);
129 } elsif (defined($t)) {
130 $t->cmd("observe $remoteglotconf::target");
134 print "FICS ready.\n";
137 # Engine events have already been set up by Engine.pm.
141 my ($engine, $line, $primary) = @_;
143 return if $line =~ /(upper|lower)bound/;
145 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
146 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
147 if ($line =~ /^info/) {
148 my (@infos) = split / /, $line;
151 parse_infos($engine, @infos);
153 if ($line =~ /^id/) {
154 my (@ids) = split / /, $line;
157 parse_ids($engine, @ids);
159 if ($line =~ /^bestmove/) {
161 return if (!$remoteglotconf::uci_assume_full_compliance);
162 if (defined($pos_waiting)) {
163 uciprint($engine, "position fen " . $pos_waiting->fen());
164 uciprint($engine, "go infinite");
166 $pos_calculating = $pos_waiting;
167 $pos_waiting = undef;
170 $engine2->{'info'} = {};
171 my $pos = $pos_waiting // $pos_calculating;
172 uciprint($engine2, "position fen " . $pos->fen());
173 uciprint($engine2, "go infinite");
174 $pos_calculating_second_engine = $pos;
180 my $getting_movelist = 0;
181 my $pos_for_movelist = undef;
182 my @uci_movelist = ();
183 my @pretty_movelist = ();
187 if ($line =~ /^<12> /) {
188 handle_position(Position->new($line));
191 if ($line =~ /^Movelist for game /) {
192 my $pos = $pos_waiting // $pos_calculating;
195 @pretty_movelist = ();
196 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
197 $getting_movelist = 1;
200 if ($getting_movelist &&
201 $line =~ /^\s* \d+\. \s+ # move number
202 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
203 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
207 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
208 push @uci_movelist, $uci_move;
209 push @pretty_movelist, $1;
212 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
213 push @uci_movelist, $uci_move;
214 push @pretty_movelist, $2;
218 warn "Error when getting FICS move history: $@";
219 $getting_movelist = 0;
222 if ($getting_movelist &&
223 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
225 for my $pos ($pos_waiting, $pos_calculating) {
226 next if (!defined($pos));
227 if ($pos->fen() eq $pos_for_movelist->fen()) {
228 $pos->{'history'} = \@pretty_movelist;
231 $getting_movelist = 0;
233 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
234 my ($who, $msg) = ($1, $2);
236 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
238 if ($msg =~ /^fics (.*?)$/) {
239 $t->cmd("tell $who Executing '$1' on FICS.");
241 } elsif ($msg =~ /^uci (.*?)$/) {
242 $t->cmd("tell $who Sending '$1' to the engine.");
243 print { $engine->{'write'} } "$1\n";
244 } elsif ($msg =~ /^pgn (.*?)$/) {
246 $t->cmd("tell $who Starting to poll '$url'.");
248 } elsif ($msg =~ /^stoppgn$/) {
249 $t->cmd("tell $who Stopping poll.");
252 } elsif ($msg =~ /^quit$/) {
253 $t->cmd("tell $who Bye bye.");
256 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
259 #print "FICS: [$line]\n";
262 # Starts periodic fetching of PGNs from the given URL.
265 AnyEvent::HTTP::http_get($url, sub {
266 handle_pgn(@_, $url);
270 my ($last_pgn_white, $last_pgn_black);
271 my @last_pgn_uci_moves = ();
272 my $pgn_hysteresis_counter = 0;
275 my ($body, $header, $url) = @_;
277 if ($stop_pgn_fetch) {
283 my $pgn = Chess::PGN::Parse->new(undef, $body);
284 if (!defined($pgn)) {
285 warn "Error in parsing PGN from $url [body='$body']\n";
286 } elsif (!$pgn->read_game()) {
287 warn "Error in reading PGN game from $url [body='$body']\n";
288 } elsif ($body !~ /^\[/) {
289 warn "Malformed PGN from $url [body='$body']\n";
292 # Skip to the right game.
293 while (defined($remoteglotconf::pgn_filter) &&
294 !&$remoteglotconf::pgn_filter($pgn)) {
295 $pgn->read_game() or die "Out of games during filtering";
298 $pgn->parse_game({ save_comments => 'yes' });
299 my $white = $pgn->white;
300 my $black = $pgn->black;
301 $white =~ s/,.*//; # Remove first name.
302 $black =~ s/,.*//; # Remove first name.
303 my $pos = Position->start_pos($white, $black);
304 my $moves = $pgn->moves;
306 my @repretty_moves = ();
307 for my $move (@$moves) {
308 my ($npos, $uci_move) = $pos->make_pretty_move($move);
309 push @uci_moves, $uci_move;
311 # Re-prettyprint the move.
312 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
313 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
314 push @repretty_moves, $pretty;
317 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
318 $pos->{'result'} = $pgn->result;
320 $pos->{'history'} = \@repretty_moves;
322 extract_clock($pgn, $pos);
324 # Sometimes, PGNs lose a move or two for a short while,
325 # or people push out new ones non-atomically.
326 # Thus, if we PGN doesn't change names but becomes
327 # shorter, we mistrust it for a few seconds.
329 if (defined($last_pgn_white) && defined($last_pgn_black) &&
330 $last_pgn_white eq $pgn->white &&
331 $last_pgn_black eq $pgn->black &&
332 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
333 if (++$pgn_hysteresis_counter < 3) {
338 $last_pgn_white = $pgn->white;
339 $last_pgn_black = $pgn->black;
340 @last_pgn_uci_moves = @uci_moves;
341 $pgn_hysteresis_counter = 0;
342 handle_position($pos);
346 warn "Error in parsing moves from $url: $@\n";
350 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
355 sub handle_position {
357 find_clock_start($pos, $pos_calculating);
359 # if this is already in the queue, ignore it (just update the result)
360 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
361 $pos_waiting->{'result'} = $pos->{'result'};
365 # if we're already chewing on this and there's nothing else in the queue,
367 if (!defined($pos_waiting) && defined($pos_calculating) &&
368 $pos->fen() eq $pos_calculating->fen()) {
369 $pos_calculating->{'result'} = $pos->{'result'};
373 # if we're already thinking on something, stop and wait for the engine
375 if (defined($pos_calculating)) {
376 # Store the final data we have for this position in the history,
377 # with the precise clock information we just got from the new
378 # position. (Historic positions store the clock at the end of
381 # Do not output anything new to the main analysis; that's
382 # going to be obsolete really soon.
383 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
384 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
385 delete $pos_calculating->{'white_clock_target'};
386 delete $pos_calculating->{'black_clock_target'};
389 if (!defined($pos_waiting)) {
390 uciprint($engine, "stop");
392 if ($remoteglotconf::uci_assume_full_compliance) {
395 uciprint($engine, "position fen " . $pos->fen());
396 uciprint($engine, "go infinite");
397 $pos_calculating = $pos;
400 # it's wrong just to give the FEN (the move history is useful,
401 # and per the UCI spec, we should really have sent "ucinewgame"),
403 uciprint($engine, "position fen " . $pos->fen());
404 uciprint($engine, "go infinite");
405 $pos_calculating = $pos;
408 if (defined($engine2)) {
409 if (defined($pos_calculating_second_engine)) {
410 uciprint($engine2, "stop");
412 uciprint($engine2, "position fen " . $pos->fen());
413 uciprint($engine2, "go infinite");
414 $pos_calculating_second_engine = $pos;
416 $engine2->{'info'} = {};
419 $engine->{'info'} = {};
422 schedule_tb_lookup();
425 # Output a command every move to note that we're
426 # still paying attention -- this is a good tradeoff,
427 # since if no move has happened in the last half
428 # hour, the analysis/relay has most likely stopped
429 # and we should stop hogging server resources.
437 my ($engine, @x) = @_;
440 my $info = $engine->{'info'};
442 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
443 for my $i (0..$#x - 1) {
444 if ($x[$i] eq 'multipv') {
450 while (scalar @x > 0) {
451 if ($x[0] eq 'multipv') {
457 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
459 my $value = shift @x;
460 $info->{$key} = $value;
463 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
464 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
467 my $value = shift @x;
468 $info->{$key . $mpv} = $value;
471 if ($x[0] eq 'score') {
474 delete $info->{'score_cp' . $mpv};
475 delete $info->{'score_mate' . $mpv};
477 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
480 $info->{'score_cp' . $mpv} = shift @x;
481 } elsif ($x[0] eq 'mate') {
483 $info->{'score_mate' . $mpv} = shift @x;
491 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
494 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
498 #print "unknown info '$x[0]', trying to recover...\n";
500 die "Unknown info '" . join(',', @x) . "'";
506 my ($engine, @x) = @_;
508 while (scalar @x > 0) {
509 if ($x[0] eq 'name') {
510 my $value = join(' ', @x);
511 $engine->{'id'}{'author'} = $value;
520 sub prettyprint_pv_no_cache {
521 my ($board, @pvs) = @_;
523 if (scalar @pvs == 0 || !defined($pvs[0])) {
528 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
529 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
530 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
534 my ($pos, @pvs) = @_;
536 my $cachekey = $pos->fen() . join('', @pvs);
537 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
538 return @{$pos->{'prettyprint_cache'}{$cachekey}};
540 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
541 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
546 my %tbprobe_cache = ();
548 sub complete_using_tbprobe {
549 my ($pos, $info, $mpv) = @_;
551 # We need Fathom installed to do standalone TB probes.
552 return if (!defined($remoteglotconf::fathom_cmdline));
554 # If we already have a mate, don't bother; in some cases, it would even be
555 # better than a tablebase score.
556 return if defined($info->{'score_mate' . $mpv});
558 # If we have a draw or near-draw score, there's also not much interesting
559 # we could add from a tablebase. We only really want mates.
560 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
562 # Run through the PV until we are at a 6-man position.
563 # TODO: We could in theory only have 5-man data.
564 my @pv = @{$info->{'pv' . $mpv}};
565 my $key = $pos->fen() . " " . join('', @pv);
567 if (exists($tbprobe_cache{$key})) {
568 @moves = @{$tbprobe_cache{$key}};
571 # Force doing at least one move of the PV.
572 my $move = shift @pv;
574 $pos = $pos->make_move(parse_uci_move($move));
577 while ($pos->num_pieces() > 6 && $#pv > -1) {
578 my $move = shift @pv;
580 $pos = $pos->make_move(parse_uci_move($move));
583 return if ($pos->num_pieces() > 6);
585 my $fen = $pos->fen();
586 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
587 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
588 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
589 $pgn->quick_parse_game;
590 $info->{'pv' . $mpv} = \@moves;
592 # Splice the PV from the tablebase onto what we have so far.
593 for my $move (@{$pgn->moves}) {
595 ($pos, $uci_move) = $pos->make_pretty_move($move);
596 push @moves, $uci_move;
599 $tbprobe_cache{$key} = \@moves;
602 $info->{'pv' . $mpv} = \@moves;
604 my $matelen = int((1 + scalar @moves) / 2);
605 if ((scalar @moves) % 2 == 0) {
606 $info->{'score_mate' . $mpv} = -$matelen;
608 $info->{'score_mate' . $mpv} = $matelen;
615 return if (!defined($pos_calculating));
617 # Don't update too often.
618 my $age = Time::HiRes::tv_interval($latest_update);
619 if ($age < $remoteglotconf::update_max_interval) {
620 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
621 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
625 my $info = $engine->{'info'};
628 # If we have tablebase data from a previous lookup, replace the
629 # engine data with the data from the tablebase.
631 my $fen = $pos_calculating->fen();
632 if (exists($tb_cache{$fen})) {
633 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
634 delete $info->{$key . '1'};
635 delete $info->{$key};
637 $info->{'nodes'} = 0;
639 $info->{'depth'} = 0;
640 $info->{'seldepth'} = 0;
641 $info->{'tbhits'} = 0;
643 my $t = $tb_cache{$fen};
645 my $matelen = int((1 + $t->{'score'}) / 2);
646 if ($t->{'result'} eq '1/2-1/2') {
647 $info->{'score_cp'} = 0;
648 } elsif ($t->{'result'} eq '1-0') {
649 if ($pos_calculating->{'toplay'} eq 'B') {
650 $info->{'score_mate'} = -$matelen;
652 $info->{'score_mate'} = $matelen;
655 if ($pos_calculating->{'toplay'} eq 'B') {
656 $info->{'score_mate'} = $matelen;
658 $info->{'score_mate'} = -$matelen;
662 $info->{'tablebase'} = 1;
664 $info->{'tablebase'} = 0;
668 # Some programs _always_ report MultiPV, even with only one PV.
669 # In this case, we simply use that data as if MultiPV was never
672 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
673 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
674 if (exists($info->{$key . '1'})) {
675 $info->{$key} = $info->{$key . '1'};
677 delete $info->{$key};
683 # Check the PVs first. if they're invalid, just wait, as our data
684 # is most likely out of sync. This isn't a very good solution, as
685 # it can frequently miss stuff, but it's good enough for most users.
689 if (exists($info->{'pv'})) {
690 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
694 while (exists($info->{'pv' . $mpv})) {
695 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
700 $engine->{'info'} = {};
704 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
705 if (exists($info->{'pv'})) {
706 complete_using_tbprobe($pos_calculating, $info, '');
710 while (exists($info->{'pv' . $mpv})) {
711 complete_using_tbprobe($pos_calculating, $info, $mpv);
717 $latest_update = [Time::HiRes::gettimeofday];
721 my $info = $engine->{'info'};
722 my $id = $engine->{'id'};
724 my $text = 'Analysis';
725 if ($pos_calculating->{'last_move'} ne 'none') {
726 if ($pos_calculating->{'toplay'} eq 'W') {
727 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
729 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
731 if (exists($id->{'name'})) {
736 if (exists($id->{'name'})) {
737 $text .= " by $id->{'name'}:\n\n";
742 return unless (exists($pos_calculating->{'board'}));
744 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
747 while (exists($info->{'pv' . $mpv})) {
748 $text .= sprintf " PV%2u", $mpv;
749 my $score = short_score($info, $pos_calculating, $mpv);
750 $text .= " ($score)" if (defined($score));
753 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
754 if ($info->{'tbhits' . $mpv} == 1) {
755 $tbhits = ", 1 tbhit";
757 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
761 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
762 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
763 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
767 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
773 my $score = long_score($info, $pos_calculating, '');
774 $text .= " $score\n" if defined($score);
775 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
778 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
779 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
780 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
782 if (exists($info->{'seldepth'})) {
783 $text .= sprintf " (%u selective)", $info->{'seldepth'};
785 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
786 if ($info->{'tbhits'} == 1) {
787 $text .= ", one Syzygy hit";
789 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
795 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
797 my @refutation_lines = ();
798 if (defined($engine2)) {
799 for (my $mpv = 1; $mpv < 500; ++$mpv) {
800 my $info = $engine2->{'info'};
801 last if (!exists($info->{'pv' . $mpv}));
803 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
804 my $pv = $info->{'pv' . $mpv};
805 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
806 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
807 if (scalar @pretty_pv > 5) {
808 @pretty_pv = @pretty_pv[0..4];
809 push @pretty_pv, "...";
811 my $key = $pretty_move;
812 my $line = sprintf(" %-6s %6s %3s %s",
814 short_score($info, $pos_calculating_second_engine, $mpv),
815 "d" . $info->{'depth' . $mpv},
816 join(', ', @pretty_pv));
817 push @refutation_lines, [ $key, $line ];
822 if ($#refutation_lines >= 0) {
823 $text .= "Shallow search of all legal moves:\n\n";
824 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
825 $text .= $line->[1] . "\n";
830 if ($last_text ne $text) {
831 print "
\e[H
\e[2J"; # clear the screen
838 my $historic_json_only = shift;
839 my $info = $engine->{'info'};
842 $json->{'position'} = $pos_calculating->to_json_hash();
843 $json->{'engine'} = $engine->{'id'};
844 if (defined($remoteglotconf::engine_url)) {
845 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
847 if (defined($remoteglotconf::engine_details)) {
848 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
850 my @grpc_backends = ();
851 if (defined($remoteglotconf::engine_grpc_backend)) {
852 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
854 if (defined($remoteglotconf::engine2_grpc_backend)) {
855 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
857 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
858 if (defined($remoteglotconf::move_source)) {
859 $json->{'move_source'} = $remoteglotconf::move_source;
861 if (defined($remoteglotconf::move_source_url)) {
862 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
864 $json->{'score'} = score_digest($info, $pos_calculating, '');
865 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
867 $json->{'nodes'} = $info->{'nodes'};
868 $json->{'nps'} = $info->{'nps'};
869 $json->{'depth'} = $info->{'depth'};
870 $json->{'tbhits'} = $info->{'tbhits'};
871 $json->{'seldepth'} = $info->{'seldepth'};
872 $json->{'tablebase'} = $info->{'tablebase'};
873 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
875 my %refutation_lines = ();
876 my @refutation_lines = ();
877 if (defined($engine2)) {
878 for (my $mpv = 1; $mpv < 500; ++$mpv) {
879 my $info = $engine2->{'info'};
880 my $pretty_move = "";
882 last if (!exists($info->{'pv' . $mpv}));
885 complete_using_tbprobe($pos_calculating, $info, $mpv);
886 my $pv = $info->{'pv' . $mpv};
887 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
888 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
889 $refutation_lines{$pretty_move} = {
890 depth => $info->{'depth' . $mpv},
891 score => score_digest($info, $pos_calculating, $mpv),
892 move => $pretty_move,
898 $json->{'refutation_lines'} = \%refutation_lines;
900 # Piece together historic score information, to the degree we have it.
901 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
902 my %score_history = ();
904 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
905 my $pos = Position->start_pos('white', 'black');
906 my $halfmove_num = 0;
907 for my $move (@{$pos_calculating->{'history'}}) {
908 my $id = id_for_pos($pos, $halfmove_num);
909 my $ref = $dbh->selectrow_hashref($q, undef, $id);
911 $score_history{$halfmove_num} = [
912 $ref->{'score_type'},
913 $ref->{'score_value'}
917 ($pos) = $pos->make_pretty_move($move);
921 # If at any point we are missing 10 consecutive moves,
922 # truncate the history there. This is so we don't get into
923 # a situation where we e.g. start analyzing at move 45,
924 # but we have analysis for 1. e4 from some completely different game
925 # and thus show a huge hole.
926 my $consecutive_missing = 0;
927 my $truncate_until = 0;
928 for (my $i = $halfmove_num; $i --> 0; ) {
929 if ($consecutive_missing >= 10) {
930 delete $score_history{$i};
933 if (exists($score_history{$i})) {
934 $consecutive_missing = 0;
936 ++$consecutive_missing;
940 $json->{'score_history'} = \%score_history;
943 # Give out a list of other games going on. (Empty is fine.)
944 # TODO: Don't bother reading our own file, the data will be stale anyway.
945 if (!$historic_json_only) {
948 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
950 while (my $ref = $q->fetchrow_hashref) {
952 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
953 my $other_game_json = JSON::XS::decode_json($other_game_contents);
955 die "Missing position" if (!exists($other_game_json->{'position'}));
956 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
957 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
961 name => "$white–$black",
962 url => $ref->{'url'},
963 hashurl => $ref->{'hash_url'},
965 if (defined($other_game_json->{'position'}{'result'})) {
966 $game->{'result'} = $other_game_json->{'position'}{'result'};
968 $game->{'score'} = $other_game_json->{'score'};
973 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
977 if (scalar @games > 0) {
978 $json->{'games'} = \@games;
982 my $json_enc = JSON::XS->new;
983 $json_enc->canonical(1);
984 my $encoded = $json_enc->encode($json);
985 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
986 (defined($last_written_json) && $last_written_json eq $encoded)) {
987 atomic_set_contents($remoteglotconf::json_output, $encoded);
988 $last_written_json = $encoded;
991 if (exists($pos_calculating->{'history'}) &&
992 defined($remoteglotconf::json_history_dir)) {
993 my $id = id_for_pos($pos_calculating);
994 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
996 # Overwrite old analysis (assuming it exists at all) if we're
997 # using a different engine, or if we've calculated deeper.
998 # nodes is used as a tiebreaker. Don't bother about Multi-PV
999 # data; it's not that important.
1000 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1001 my $new_depth = $json->{'depth'} // 0;
1002 my $new_nodes = $json->{'nodes'} // 0;
1003 if (!defined($old_engine) ||
1004 $old_engine ne $json->{'engine'}{'name'} ||
1005 $new_depth > $old_depth ||
1006 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1007 atomic_set_contents($filename, $encoded);
1008 if (defined($json->{'score'})) {
1009 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1010 ' ON CONFLICT (id) DO UPDATE SET ' .
1011 ' score_type=EXCLUDED.score_type, ' .
1012 ' score_value=EXCLUDED.score_value, ' .
1013 ' engine=EXCLUDED.engine, ' .
1014 ' depth=EXCLUDED.depth, ' .
1015 ' nodes=EXCLUDED.nodes',
1017 $id, $json->{'score'}[0], $json->{'score'}[1],
1018 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1024 sub atomic_set_contents {
1025 my ($filename, $contents) = @_;
1027 open my $fh, ">", $filename . ".tmp"
1029 print $fh $contents;
1031 rename($filename . ".tmp", $filename);
1035 my ($pos, $halfmove_num) = @_;
1037 $halfmove_num //= scalar @{$pos->{'history'}};
1038 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1039 return "move$halfmove_num-$fen";
1042 sub get_json_analysis_stats {
1044 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1045 if (defined($ref)) {
1046 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1053 my ($engine, $msg) = @_;
1054 $engine->print($msg);
1055 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1059 my ($info, $pos, $mpv) = @_;
1061 my $invert = ($pos->{'toplay'} eq 'B');
1062 if (defined($info->{'score_mate' . $mpv})) {
1064 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1066 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1069 if (exists($info->{'score_cp' . $mpv})) {
1070 my $score = $info->{'score_cp' . $mpv} * 0.01;
1072 if ($info->{'tablebase'}) {
1081 return sprintf "%+5.2f", $score;
1088 # Sufficient for computing long_score, short_score, plot_score and
1089 # (with side-to-play information) score_sort_key.
1091 my ($info, $pos, $mpv) = @_;
1093 if (defined($info->{'score_mate' . $mpv})) {
1094 my $mate = $info->{'score_mate' . $mpv};
1095 if ($pos->{'toplay'} eq 'B') {
1098 return ['m', $mate];
1100 if (exists($info->{'score_cp' . $mpv})) {
1101 my $score = $info->{'score_cp' . $mpv};
1102 if ($pos->{'toplay'} eq 'B') {
1105 if ($score == 0 && $info->{'tablebase'}) {
1106 return ['d', undef];
1108 return ['cp', int($score)];
1117 my ($info, $pos, $mpv) = @_;
1119 if (defined($info->{'score_mate' . $mpv})) {
1120 my $mate = $info->{'score_mate' . $mpv};
1121 if ($pos->{'toplay'} eq 'B') {
1125 return sprintf "White mates in %u", $mate;
1127 return sprintf "Black mates in %u", -$mate;
1130 if (exists($info->{'score_cp' . $mpv})) {
1131 my $score = $info->{'score_cp' . $mpv} * 0.01;
1133 if ($info->{'tablebase'}) {
1134 return "Theoretical draw";
1136 return "Score: 0.00";
1139 if ($pos->{'toplay'} eq 'B') {
1142 return sprintf "Score: %+5.2f", $score;
1149 # For graphs; a single number in centipawns, capped at +/- 500.
1151 my ($info, $pos, $mpv) = @_;
1153 my $invert = ($pos->{'toplay'} eq 'B');
1154 if (defined($info->{'score_mate' . $mpv})) {
1155 my $mate = $info->{'score_mate' . $mpv};
1165 if (exists($info->{'score_cp' . $mpv})) {
1166 my $score = $info->{'score_cp' . $mpv};
1170 $score = 500 if ($score > 500);
1171 $score = -500 if ($score < -500);
1179 my %book_cache = ();
1181 my ($fen, $board, $toplay) = @_;
1183 if (exists($book_cache{$fen})) {
1184 return $book_cache{$fen};
1187 my $ret = `./booklook $fen`;
1188 return "" if ($ret =~ /Not found/ || $ret eq '');
1192 for my $m (split /\n/, $ret) {
1193 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1197 $pmove = '(current)';
1199 ($pmove) = prettyprint_pv_no_cache($board, $move);
1200 $pmove .= $annotation;
1204 if ($toplay eq 'W') {
1205 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1207 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1209 my $n = $win + $draw + $lose;
1215 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1218 push @moves, [ $pmove, $n, $percent, $rating ];
1221 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1223 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1224 for my $m (@moves) {
1225 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1232 my ($pgn, $pos) = @_;
1234 # Look for extended PGN clock tags.
1235 my $tags = $pgn->tags;
1236 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1237 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1238 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1242 # Look for TCEC-style time comments.
1243 my $moves = $pgn->moves;
1244 my $comments = $pgn->comments;
1245 my $last_black_move = int((scalar @$moves) / 2);
1246 my $last_white_move = int((1 + scalar @$moves) / 2);
1248 my $black_key = $last_black_move . "b";
1249 my $white_key = $last_white_move . "w";
1251 if (exists($comments->{$white_key}) &&
1252 exists($comments->{$black_key}) &&
1253 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1254 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1255 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1256 $pos->{'white_clock'} = hms_to_sec($1);
1257 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1258 $pos->{'black_clock'} = hms_to_sec($1);
1262 delete $pos->{'white_clock'};
1263 delete $pos->{'black_clock'};
1268 return undef if (!defined($hms));
1269 $hms =~ /(\d+):(\d+):(\d+)/;
1270 return $1 * 3600 + $2 * 60 + $3;
1273 sub find_clock_start {
1274 my ($pos, $prev_pos) = @_;
1276 # If the game is over, the clock is stopped.
1277 if (exists($pos->{'result'}) &&
1278 ($pos->{'result'} eq '1-0' ||
1279 $pos->{'result'} eq '1/2-1/2' ||
1280 $pos->{'result'} eq '0-1')) {
1284 # When we don't have any moves, we assume the clock hasn't started yet.
1285 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1286 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1287 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1292 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1293 # The history is needed for id_for_pos.
1294 if (!exists($pos->{'history'})) {
1298 my $id = id_for_pos($pos);
1299 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1300 if (defined($clock_info)) {
1301 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1302 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1303 if ($pos->{'toplay'} eq 'W') {
1304 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1306 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1311 # OK, we haven't seen this position before, so we assume the move
1312 # happened right now.
1314 # See if we should do our own clock management (ie., clock information
1315 # is spurious or non-existent).
1316 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1317 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1318 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1319 if (defined($prev_pos->{'white_clock_target'})) {
1320 $wc = $prev_pos->{'white_clock_target'} - time;
1322 if (defined($prev_pos->{'black_clock_target'})) {
1323 $bc = $prev_pos->{'black_clock_target'} - time;
1325 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1326 $pos->{'white_clock'} = $wc;
1327 $pos->{'black_clock'} = $bc;
1330 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1331 if (!exists($pos->{$key})) {
1332 # No clock information.
1335 my $time_left = $pos->{$key};
1336 my ($white_clock_target, $black_clock_target);
1337 if ($pos->{'toplay'} eq 'W') {
1338 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1340 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1342 local $dbh->{AutoCommit} = 0;
1343 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1344 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1345 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1349 sub schedule_tb_lookup {
1350 return if (!defined($remoteglotconf::tb_serial_key));
1351 my $pos = $pos_waiting // $pos_calculating;
1352 return if (exists($tb_cache{$pos->fen()}));
1354 # If there's more than seven pieces, there's not going to be an answer,
1356 return if ($pos->num_pieces() > 7);
1358 # Max one at a time. If it's still relevant when it returns,
1359 # schedule_tb_lookup() will be called again.
1360 return if ($tb_lookup_running);
1362 $tb_lookup_running = 1;
1363 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1364 $remoteglotconf::tb_serial_key .
1365 '&auth.password=aquarium&type=0&fen=' .
1366 URI::Escape::uri_escape($pos->fen());
1367 print TBLOG "Downloading $url...\n";
1368 AnyEvent::HTTP::http_get($url, sub {
1369 handle_tb_lookup_return(@_, $pos, $pos->fen());
1373 sub handle_tb_lookup_return {
1374 my ($body, $header, $pos, $fen) = @_;
1375 print TBLOG "Response for [$fen]:\n";
1376 print TBLOG $header . "\n\n";
1377 print TBLOG $body . "\n\n";
1379 my $response = JSON::XS::decode_json($body);
1380 if ($response->{'ErrorCode'} != 0) {
1381 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1383 my $state = $response->{'Response'}{'StateString'};
1384 if ($state eq 'COMPLETE') {
1385 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1386 if (!defined($pgn) || !$pgn->read_game()) {
1387 warn "Error in parsing PGN\n";
1389 $pgn->quick_parse_game;
1391 my $moves = $pgn->moves;
1393 for my $move (@$moves) {
1395 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1396 push @uci_moves, $uci_move;
1399 result => $pgn->result,
1401 score => $response->{'Response'}{'Score'},
1405 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1406 # Try again in a second. Note that if we have changed
1407 # position in the meantime, we might query a completely
1408 # different position! But that's fine.
1410 die "Unknown response state " . $state;
1413 # Wait a second before we schedule another one.
1414 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1415 $tb_lookup_running = 0;
1416 schedule_tb_lookup();
1420 warn "Error in tablebase lookup: $@";
1422 # Don't try this one again, but don't block new lookups either.
1423 $tb_lookup_running = 0;
1428 my ($cmdline, $tag, $cb) = @_;
1429 return undef if (!defined($cmdline));
1430 return Engine->open($cmdline, $tag, $cb);
1433 sub col_letter_to_num {
1434 return ord(shift) - ord('a');
1437 sub row_letter_to_num {
1438 return 7 - (ord(shift) - ord('1'));
1441 sub parse_uci_move {
1443 my $from_col = col_letter_to_num(substr($move, 0, 1));
1444 my $from_row = row_letter_to_num(substr($move, 1, 1));
1445 my $to_col = col_letter_to_num(substr($move, 2, 1));
1446 my $to_row = row_letter_to_num(substr($move, 3, 1));
1447 my $promo = substr($move, 4, 1);
1448 return ($from_row, $from_col, $to_row, $to_col, $promo);