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_calculating, $pos_calculating_second_engine);
79 # If not undef, we've started calculating this position but haven't ever given out
80 # any analysis for it, so we're on a forced timer to do so.
81 my $pos_calculating_started = undef;
83 setoptions($engine, \%remoteglotconf::engine_config);
84 uciprint($engine, "ucinewgame");
86 if (defined($engine2)) {
87 setoptions($engine2, \%remoteglotconf::engine2_config);
88 uciprint($engine2, "setoption name MultiPV value 500");
89 uciprint($engine2, "ucinewgame");
92 print "Chess engine ready.\n";
96 if (defined($remoteglotconf::server)) {
97 $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
98 $t->input_log(\*FICSLOG);
99 $t->open($remoteglotconf::server);
100 $t->print($remoteglotconf::nick);
101 $t->waitfor('/Press return to enter the server/');
105 $t->cmd("set shout 0");
106 $t->cmd("set seek 0");
107 $t->cmd("set style 12");
112 cb => sub { # what callback to execute
114 my $line = $t->getline(Timeout => 0, errmode => 'return');
115 return if (!defined($line));
124 if (defined($remoteglotconf::target)) {
125 if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
126 fetch_pgn($remoteglotconf::target);
127 } elsif (defined($t)) {
128 $t->cmd("observe $remoteglotconf::target");
132 print "FICS ready.\n";
135 # Engine events have already been set up by Engine.pm.
139 my ($engine, $line, $primary) = @_;
141 return if $line =~ /(upper|lower)bound/;
143 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
144 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
146 # If we've sent a stop command, gobble up lines until we see bestmove.
147 return if ($engine->{'stopping'} && $line !~ /^bestmove/);
148 $engine->{'stopping'} = 0;
150 if ($line =~ /^info/) {
151 my (@infos) = split / /, $line;
154 parse_infos($engine, @infos);
156 if ($line =~ /^id/) {
157 my (@ids) = split / /, $line;
160 parse_ids($engine, @ids);
165 my $getting_movelist = 0;
166 my $pos_for_movelist = undef;
167 my @uci_movelist = ();
168 my @pretty_movelist = ();
172 if ($line =~ /^<12> /) {
173 handle_position(Position->new($line));
176 if ($line =~ /^Movelist for game /) {
177 my $pos = $pos_calculating;
180 @pretty_movelist = ();
181 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
182 $getting_movelist = 1;
185 if ($getting_movelist &&
186 $line =~ /^\s* \d+\. \s+ # move number
187 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
188 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
192 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
193 push @uci_movelist, $uci_move;
194 push @pretty_movelist, $1;
197 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
198 push @uci_movelist, $uci_move;
199 push @pretty_movelist, $2;
203 warn "Error when getting FICS move history: $@";
204 $getting_movelist = 0;
207 if ($getting_movelist &&
208 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
210 if (defined($pos_calculating)) {
211 if ($pos_calculating->fen() eq $pos_for_movelist->fen()) {
212 $pos_calculating->{'history'} = \@pretty_movelist;
215 $getting_movelist = 0;
217 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
218 my ($who, $msg) = ($1, $2);
220 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
222 if ($msg =~ /^fics (.*?)$/) {
223 $t->cmd("tell $who Executing '$1' on FICS.");
225 } elsif ($msg =~ /^uci (.*?)$/) {
226 $t->cmd("tell $who Sending '$1' to the engine.");
227 print { $engine->{'write'} } "$1\n";
228 } elsif ($msg =~ /^pgn (.*?)$/) {
230 $t->cmd("tell $who Starting to poll '$url'.");
232 } elsif ($msg =~ /^stoppgn$/) {
233 $t->cmd("tell $who Stopping poll.");
236 } elsif ($msg =~ /^quit$/) {
237 $t->cmd("tell $who Bye bye.");
240 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
243 #print "FICS: [$line]\n";
246 # Starts periodic fetching of PGNs from the given URL.
249 if ($url =~ m#^/#) { # Local file.
252 open my $fh, "<", $url
256 handle_pgn($pgn, '', $url);
260 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
265 AnyEvent::HTTP::http_get($url, sub {
266 handle_pgn(@_, $url);
271 my ($last_pgn_white, $last_pgn_black);
272 my @last_pgn_uci_moves = ();
273 my $pgn_hysteresis_counter = 0;
276 my ($body, $header, $url) = @_;
278 if ($stop_pgn_fetch) {
284 my $pgn = Chess::PGN::Parse->new(undef, $body);
285 if (!defined($pgn)) {
286 warn "Error in parsing PGN from $url [body='$body']\n";
287 } elsif (!$pgn->read_game()) {
288 warn "Error in reading PGN game from $url [body='$body']\n";
289 } elsif ($body !~ /^\[/) {
290 warn "Malformed PGN from $url [body='$body']\n";
293 # Skip to the right game.
294 while (defined($remoteglotconf::pgn_filter) &&
295 !&$remoteglotconf::pgn_filter($pgn)) {
296 $pgn->read_game() or die "Out of games during filtering";
299 $pgn->parse_game({ save_comments => 'yes' });
300 my $white = $pgn->white;
301 my $black = $pgn->black;
302 $white =~ s/,.*//; # Remove first name.
303 $black =~ s/,.*//; # Remove first name.
304 my $tags = $pgn->tags();
306 if (exists($tags->{'FEN'})) {
307 $pos = Position->from_fen($tags->{'FEN'});
308 $pos->{'last_move'} = 'none';
309 $pos->{'player_w'} = $white;
310 $pos->{'player_b'} = $black;
311 $pos->{'start_fen'} = $tags->{'FEN'};
313 $pos = Position->start_pos($white, $black);
315 if (exists($tags->{'Variant'}) &&
316 $tags->{'Variant'} =~ /960|fischer/i) {
317 $pos->{'chess960'} = 1;
319 $pos->{'chess960'} = 0;
321 my $moves = $pgn->moves;
323 my @repretty_moves = ();
324 for my $move (@$moves) {
325 my ($npos, $uci_move) = $pos->make_pretty_move($move);
326 push @uci_moves, $uci_move;
328 # Re-prettyprint the move.
329 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
330 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
331 push @repretty_moves, $pretty;
334 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
335 $pos->{'result'} = $pgn->result;
337 $pos->{'history'} = \@repretty_moves;
339 extract_clock($pgn, $pos);
341 # Sometimes, PGNs lose a move or two for a short while,
342 # or people push out new ones non-atomically.
343 # Thus, if we PGN doesn't change names but becomes
344 # shorter, we mistrust it for a few seconds.
346 if (defined($last_pgn_white) && defined($last_pgn_black) &&
347 $last_pgn_white eq $pgn->white &&
348 $last_pgn_black eq $pgn->black &&
349 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
350 if (++$pgn_hysteresis_counter < 3) {
355 $last_pgn_white = $pgn->white;
356 $last_pgn_black = $pgn->black;
357 @last_pgn_uci_moves = @uci_moves;
358 $pgn_hysteresis_counter = 0;
359 handle_position($pos);
363 warn "Error in parsing moves from $url: $@\n";
367 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
372 sub handle_position {
374 find_clock_start($pos, $pos_calculating);
376 # If we're already chewing on this and there's nothing else in the queue,
378 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
379 $pos_calculating->{'result'} = $pos->{'result'};
380 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
381 $pos_calculating->{$key} //= $pos->{$key};
386 # If we're already thinking on something, stop and wait for the engine
388 if (defined($pos_calculating)) {
389 # Store the final data we have for this position in the history,
390 # with the precise clock information we just got from the new
391 # position. (Historic positions store the clock at the end of
394 # Do not output anything new to the main analysis; that's
395 # going to be obsolete really soon. (Exception: If we've never
396 # output anything for this move, ie., it didn't hit the 200ms
397 # limit, spit it out to the user anyway. It's probably a really
398 # fast blitz game or something, and it's good to show the moves
399 # as they come in even without great analysis.)
400 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
401 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
402 delete $pos_calculating->{'white_clock_target'};
403 delete $pos_calculating->{'black_clock_target'};
405 if (defined($pos_calculating_started)) {
410 $pos_calculating_started = [Time::HiRes::gettimeofday];
412 # Ask the engine to stop; we will throw away its data until it
413 # sends us "bestmove", signaling the end of it.
414 $engine->{'stopping'} = 1;
415 uciprint($engine, "stop");
418 # It's wrong to just give the FEN (the move history is useful,
419 # and per the UCI spec, we should really have sent "ucinewgame"),
420 # but it's easier, and it works around a Stockfish repetition issue.
421 if ($engine->{'chess960'} != $pos->{'chess960'}) {
422 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
423 $engine->{'chess960'} = $pos->{'chess960'};
425 uciprint($engine, "position fen " . $pos->fen());
426 uciprint($engine, "go infinite");
427 $pos_calculating = $pos;
428 $pos_calculating_started = [Time::HiRes::gettimeofday];
430 if (defined($engine2)) {
431 if (defined($pos_calculating_second_engine)) {
432 $engine2->{'stopping'} = 1;
433 uciprint($engine2, "stop");
435 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
436 uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
437 $engine2->{'chess960'} = $pos->{'chess960'};
439 uciprint($engine2, "position fen " . $pos->fen());
440 uciprint($engine2, "go infinite");
441 $pos_calculating_second_engine = $pos;
442 $engine2->{'info'} = {};
445 $engine->{'info'} = {};
448 schedule_tb_lookup();
451 # Output a command every move to note that we're
452 # still paying attention -- this is a good tradeoff,
453 # since if no move has happened in the last half
454 # hour, the analysis/relay has most likely stopped
455 # and we should stop hogging server resources.
463 my ($engine, @x) = @_;
466 my $info = $engine->{'info'};
468 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
469 for my $i (0..$#x - 1) {
470 if ($x[$i] eq 'multipv') {
476 while (scalar @x > 0) {
477 if ($x[0] eq 'multipv') {
483 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
485 my $value = shift @x;
486 $info->{$key} = $value;
489 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
490 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
493 my $value = shift @x;
494 $info->{$key . $mpv} = $value;
497 if ($x[0] eq 'score') {
500 delete $info->{'score_cp' . $mpv};
501 delete $info->{'score_mate' . $mpv};
503 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
506 $info->{'score_cp' . $mpv} = shift @x;
507 } elsif ($x[0] eq 'mate') {
509 $info->{'score_mate' . $mpv} = shift @x;
517 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
520 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
524 #print "unknown info '$x[0]', trying to recover...\n";
526 die "Unknown info '" . join(',', @x) . "'";
532 my ($engine, @x) = @_;
534 while (scalar @x > 0) {
535 if ($x[0] eq 'name') {
536 my $value = join(' ', @x);
537 $engine->{'id'}{'author'} = $value;
546 sub prettyprint_pv_no_cache {
547 my ($board, @pvs) = @_;
549 if (scalar @pvs == 0 || !defined($pvs[0])) {
555 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
556 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
564 my ($pos, @pvs) = @_;
566 my $cachekey = join('', @pvs);
567 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
568 return @{$pos->{'prettyprint_cache'}{$cachekey}};
570 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
571 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
576 my %tbprobe_cache = ();
578 sub complete_using_tbprobe {
579 my ($pos, $info, $mpv) = @_;
581 # We need Fathom installed to do standalone TB probes.
582 return if (!defined($remoteglotconf::fathom_cmdline));
584 # If we already have a mate, don't bother; in some cases, it would even be
585 # better than a tablebase score.
586 return if defined($info->{'score_mate' . $mpv});
588 # If we have a draw or near-draw score, there's also not much interesting
589 # we could add from a tablebase. We only really want mates.
590 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
592 # Run through the PV until we are at a 6-man position.
593 # TODO: We could in theory only have 5-man data.
594 my @pv = @{$info->{'pv' . $mpv}};
595 my $key = $pos->fen() . " " . join('', @pv);
597 if (exists($tbprobe_cache{$key})) {
598 @moves = @{$tbprobe_cache{$key}};
601 # Force doing at least one move of the PV.
602 my $move = shift @pv;
604 $pos = $pos->make_move(parse_uci_move($move));
607 while ($pos->num_pieces() > 7 && $#pv > -1) {
608 my $move = shift @pv;
610 $pos = $pos->make_move(parse_uci_move($move));
613 return if ($pos->num_pieces() > 7);
615 my $fen = $pos->fen();
616 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
617 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
618 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
619 $pgn->quick_parse_game;
620 $info->{'pv' . $mpv} = \@moves;
622 # Splice the PV from the tablebase onto what we have so far.
623 for my $move (@{$pgn->moves}) {
624 last if $move eq '#';
625 last if $move eq '1-0';
626 last if $move eq '0-1';
627 last if $move eq '1/2-1/2';
629 ($pos, $uci_move) = $pos->make_pretty_move($move);
630 push @moves, $uci_move;
633 $tbprobe_cache{$key} = \@moves;
636 $info->{'pv' . $mpv} = \@moves;
638 my $matelen = int((1 + scalar @moves) / 2);
639 if ((scalar @moves) % 2 == 0) {
640 $info->{'score_mate' . $mpv} = -$matelen;
642 $info->{'score_mate' . $mpv} = $matelen;
649 return if (!defined($pos_calculating));
651 # Don't update too often.
652 my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
653 my $new_pos_wait = defined($pos_calculating_started) ?
654 $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started)
656 $wait = $new_pos_wait if ($new_pos_wait < $wait);
658 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
662 my $info = $engine->{'info'};
664 # We're outputting something for this position now, so the special handling
665 # for new positions is off.
666 undef $pos_calculating_started;
669 # If we have tablebase data from a previous lookup, replace the
670 # engine data with the data from the tablebase.
672 my $fen = $pos_calculating->fen();
673 if (exists($tb_cache{$fen})) {
674 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
675 delete $info->{$key . '1'};
676 delete $info->{$key};
678 $info->{'nodes'} = 0;
680 $info->{'depth'} = 0;
681 $info->{'seldepth'} = 0;
682 $info->{'tbhits'} = 0;
684 my $t = $tb_cache{$fen};
686 my $matelen = int((1 + $t->{'score'}) / 2);
687 if ($t->{'result'} eq '1/2-1/2') {
688 $info->{'score_cp'} = 0;
689 } elsif ($t->{'result'} eq '1-0') {
690 if ($pos_calculating->{'toplay'} eq 'B') {
691 $info->{'score_mate'} = -$matelen;
693 $info->{'score_mate'} = $matelen;
696 if ($pos_calculating->{'toplay'} eq 'B') {
697 $info->{'score_mate'} = $matelen;
699 $info->{'score_mate'} = -$matelen;
703 $info->{'tablebase'} = 1;
705 $info->{'tablebase'} = 0;
709 # Some programs _always_ report MultiPV, even with only one PV.
710 # In this case, we simply use that data as if MultiPV was never
713 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
714 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
715 if (exists($info->{$key . '1'})) {
716 $info->{$key} = $info->{$key . '1'};
718 delete $info->{$key};
724 # Check the PVs first. if they're invalid, just wait, as our data
725 # is most likely out of sync. This isn't a very good solution, as
726 # it can frequently miss stuff, but it's good enough for most users.
730 if (exists($info->{'pv'})) {
731 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
735 while (exists($info->{'pv' . $mpv})) {
736 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
741 $engine->{'info'} = {};
745 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
746 if (exists($info->{'pv'})) {
747 complete_using_tbprobe($pos_calculating, $info, '');
751 while (exists($info->{'pv' . $mpv})) {
752 complete_using_tbprobe($pos_calculating, $info, $mpv);
758 $latest_update = [Time::HiRes::gettimeofday];
762 my $info = $engine->{'info'};
763 my $id = $engine->{'id'};
765 my $text = 'Analysis';
766 if ($pos_calculating->{'last_move'} ne 'none') {
767 if ($pos_calculating->{'toplay'} eq 'W') {
768 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
770 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
772 if (exists($id->{'name'})) {
777 if (exists($id->{'name'})) {
778 $text .= " by $id->{'name'}:\n\n";
783 return unless (exists($pos_calculating->{'board'}));
785 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
788 while (exists($info->{'pv' . $mpv})) {
789 $text .= sprintf " PV%2u", $mpv;
790 my $score = short_score($info, $pos_calculating, $mpv);
791 $text .= " ($score)" if (defined($score));
794 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
795 if ($info->{'tbhits' . $mpv} == 1) {
796 $tbhits = ", 1 tbhit";
798 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
802 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
803 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
804 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
808 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
814 my $score = long_score($info, $pos_calculating, '');
815 $text .= " $score\n" if defined($score);
816 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
819 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
820 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
821 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
823 if (exists($info->{'seldepth'})) {
824 $text .= sprintf " (%u selective)", $info->{'seldepth'};
826 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
827 if ($info->{'tbhits'} == 1) {
828 $text .= ", one Syzygy hit";
830 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
836 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
838 my @refutation_lines = ();
839 if (defined($engine2)) {
840 for (my $mpv = 1; $mpv < 500; ++$mpv) {
841 my $info = $engine2->{'info'};
842 last if (!exists($info->{'pv' . $mpv}));
844 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
845 my $pv = $info->{'pv' . $mpv};
846 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
847 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
848 if (scalar @pretty_pv > 5) {
849 @pretty_pv = @pretty_pv[0..4];
850 push @pretty_pv, "...";
852 my $key = $pretty_move;
853 my $line = sprintf(" %-6s %6s %3s %s",
855 short_score($info, $pos_calculating_second_engine, $mpv),
856 "d" . $info->{'depth' . $mpv},
857 join(', ', @pretty_pv));
858 push @refutation_lines, [ $key, $line ];
863 if ($#refutation_lines >= 0) {
864 $text .= "Shallow search of all legal moves:\n\n";
865 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
866 $text .= $line->[1] . "\n";
871 if ($last_text ne $text) {
872 print "
\e[H
\e[2J"; # clear the screen
879 my $historic_json_only = shift;
880 my $info = $engine->{'info'};
883 $json->{'position'} = $pos_calculating->to_json_hash();
884 $json->{'engine'} = $engine->{'id'};
885 if (defined($remoteglotconf::engine_url)) {
886 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
888 if (defined($remoteglotconf::engine_details)) {
889 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
891 my @grpc_backends = ();
892 if (defined($remoteglotconf::engine_grpc_backend)) {
893 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
895 if (defined($remoteglotconf::engine2_grpc_backend)) {
896 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
898 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
899 if (defined($remoteglotconf::move_source)) {
900 $json->{'move_source'} = $remoteglotconf::move_source;
902 if (defined($remoteglotconf::move_source_url)) {
903 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
905 $json->{'score'} = score_digest($info, $pos_calculating, '');
906 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
908 $json->{'nodes'} = $info->{'nodes'};
909 $json->{'nps'} = $info->{'nps'};
910 $json->{'depth'} = $info->{'depth'};
911 $json->{'tbhits'} = $info->{'tbhits'};
912 $json->{'seldepth'} = $info->{'seldepth'};
913 $json->{'tablebase'} = $info->{'tablebase'};
914 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
916 my %refutation_lines = ();
917 my @refutation_lines = ();
918 if (defined($engine2)) {
919 for (my $mpv = 1; $mpv < 500; ++$mpv) {
920 my $info = $engine2->{'info'};
921 my $pretty_move = "";
923 last if (!exists($info->{'pv' . $mpv}));
926 complete_using_tbprobe($pos_calculating, $info, $mpv);
927 my $pv = $info->{'pv' . $mpv};
928 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
929 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
930 $refutation_lines{$pretty_move} = {
931 depth => $info->{'depth' . $mpv},
932 score => score_digest($info, $pos_calculating, $mpv),
933 move => $pretty_move,
939 $json->{'refutation_lines'} = \%refutation_lines;
941 # Piece together historic score information, to the degree we have it.
942 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
943 my %score_history = ();
945 local $dbh->{AutoCommit} = 0;
946 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
948 if (exists($pos_calculating->{'start_fen'})) {
949 $pos = Position->from_fen($pos_calculating->{'start_fen'});
951 $pos = Position->start_pos('white', 'black');
953 $pos->{'chess960'} = $pos_calculating->{'chess960'};
954 my $halfmove_num = 0;
955 for my $move (@{$pos_calculating->{'history'}}) {
956 my $id = id_for_pos($pos, $halfmove_num);
957 my $ref = $dbh->selectrow_hashref($q, undef, $id);
959 $score_history{$halfmove_num} = [
960 $ref->{'score_type'},
961 $ref->{'score_value'}
965 ($pos) = $pos->make_pretty_move($move);
970 # If at any point we are missing 10 consecutive moves,
971 # truncate the history there. This is so we don't get into
972 # a situation where we e.g. start analyzing at move 45,
973 # but we have analysis for 1. e4 from some completely different game
974 # and thus show a huge hole.
975 my $consecutive_missing = 0;
976 my $truncate_until = 0;
977 for (my $i = $halfmove_num; $i --> 0; ) {
978 if ($consecutive_missing >= 10) {
979 delete $score_history{$i};
982 if (exists($score_history{$i})) {
983 $consecutive_missing = 0;
985 ++$consecutive_missing;
989 $json->{'score_history'} = \%score_history;
992 # Give out a list of other games going on. (Empty is fine.)
993 # TODO: Don't bother reading our own file, the data will be stale anyway.
994 if (!$historic_json_only) {
997 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
999 while (my $ref = $q->fetchrow_hashref) {
1001 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
1002 my $other_game_json = JSON::XS::decode_json($other_game_contents);
1004 die "Missing position" if (!exists($other_game_json->{'position'}));
1005 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
1006 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
1010 name => "$white–$black",
1011 url => $ref->{'url'},
1012 hashurl => $ref->{'hash_url'},
1014 if (defined($other_game_json->{'position'}{'result'})) {
1015 $game->{'result'} = $other_game_json->{'position'}{'result'};
1017 $game->{'score'} = $other_game_json->{'score'};
1022 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
1026 if (scalar @games > 0) {
1027 $json->{'games'} = \@games;
1031 my $json_enc = JSON::XS->new;
1032 $json_enc->canonical(1);
1033 my $encoded = $json_enc->encode($json);
1034 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1035 (defined($last_written_json) && $last_written_json eq $encoded)) {
1036 atomic_set_contents($remoteglotconf::json_output, $encoded);
1037 $last_written_json = $encoded;
1040 if (exists($pos_calculating->{'history'}) &&
1041 defined($remoteglotconf::json_history_dir)) {
1042 my $id = id_for_pos($pos_calculating);
1043 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1045 # Overwrite old analysis (assuming it exists at all) if we're
1046 # using a different engine, or if we've calculated deeper.
1047 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1048 # data; it's not that important.
1049 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1050 my $new_depth = $json->{'depth'} // 0;
1051 my $new_nodes = $json->{'nodes'} // 0;
1052 if (!defined($old_engine) ||
1053 $old_engine ne $json->{'engine'}{'name'} ||
1054 $new_depth > $old_depth ||
1055 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1056 atomic_set_contents($filename, $encoded);
1057 if (defined($json->{'score'})) {
1058 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1059 ' ON CONFLICT (id) DO UPDATE SET ' .
1060 ' score_type=EXCLUDED.score_type, ' .
1061 ' score_value=EXCLUDED.score_value, ' .
1062 ' engine=EXCLUDED.engine, ' .
1063 ' depth=EXCLUDED.depth, ' .
1064 ' nodes=EXCLUDED.nodes',
1066 $id, $json->{'score'}[0], $json->{'score'}[1],
1067 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1073 sub atomic_set_contents {
1074 my ($filename, $contents) = @_;
1076 open my $fh, ">", $filename . ".tmp"
1078 print $fh $contents;
1080 rename($filename . ".tmp", $filename);
1084 my ($pos, $halfmove_num) = @_;
1086 $halfmove_num //= scalar @{$pos->{'history'}};
1087 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1088 return "move$halfmove_num-$fen";
1091 sub get_json_analysis_stats {
1093 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1094 if (defined($ref)) {
1095 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1102 my ($engine, $msg) = @_;
1103 $engine->print($msg);
1104 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1108 my ($info, $pos, $mpv) = @_;
1110 my $invert = ($pos->{'toplay'} eq 'B');
1111 if (defined($info->{'score_mate' . $mpv})) {
1113 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1115 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1118 if (exists($info->{'score_cp' . $mpv})) {
1119 my $score = $info->{'score_cp' . $mpv} * 0.01;
1121 if ($info->{'tablebase'}) {
1130 return sprintf "%+5.2f", $score;
1137 # Sufficient for computing long_score, short_score, plot_score and
1138 # (with side-to-play information) score_sort_key.
1140 my ($info, $pos, $mpv) = @_;
1142 if (defined($info->{'score_mate' . $mpv})) {
1143 my $mate = $info->{'score_mate' . $mpv};
1144 if ($pos->{'toplay'} eq 'B') {
1147 return ['m', $mate];
1149 if (exists($info->{'score_cp' . $mpv})) {
1150 my $score = $info->{'score_cp' . $mpv};
1151 if ($pos->{'toplay'} eq 'B') {
1154 if ($score == 0 && $info->{'tablebase'}) {
1155 return ['d', undef];
1157 return ['cp', int($score)];
1166 my ($info, $pos, $mpv) = @_;
1168 if (defined($info->{'score_mate' . $mpv})) {
1169 my $mate = $info->{'score_mate' . $mpv};
1170 if ($pos->{'toplay'} eq 'B') {
1174 return sprintf "White mates in %u", $mate;
1176 return sprintf "Black mates in %u", -$mate;
1179 if (exists($info->{'score_cp' . $mpv})) {
1180 my $score = $info->{'score_cp' . $mpv} * 0.01;
1182 if ($info->{'tablebase'}) {
1183 return "Theoretical draw";
1185 return "Score: 0.00";
1188 if ($pos->{'toplay'} eq 'B') {
1191 return sprintf "Score: %+5.2f", $score;
1198 # For graphs; a single number in centipawns, capped at +/- 500.
1200 my ($info, $pos, $mpv) = @_;
1202 my $invert = ($pos->{'toplay'} eq 'B');
1203 if (defined($info->{'score_mate' . $mpv})) {
1204 my $mate = $info->{'score_mate' . $mpv};
1214 if (exists($info->{'score_cp' . $mpv})) {
1215 my $score = $info->{'score_cp' . $mpv};
1219 $score = 500 if ($score > 500);
1220 $score = -500 if ($score < -500);
1228 my %book_cache = ();
1230 my ($fen, $board, $toplay) = @_;
1232 if (exists($book_cache{$fen})) {
1233 return $book_cache{$fen};
1236 my $ret = `./booklook $fen`;
1237 return "" if ($ret =~ /Not found/ || $ret eq '');
1241 for my $m (split /\n/, $ret) {
1242 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1246 $pmove = '(current)';
1248 ($pmove) = prettyprint_pv_no_cache($board, $move);
1249 $pmove .= $annotation;
1253 if ($toplay eq 'W') {
1254 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1256 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1258 my $n = $win + $draw + $lose;
1264 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1267 push @moves, [ $pmove, $n, $percent, $rating ];
1270 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1272 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1273 for my $m (@moves) {
1274 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1281 my ($pgn, $pos) = @_;
1283 # Look for extended PGN clock tags.
1284 my $tags = $pgn->tags;
1285 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1286 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1287 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1291 # Look for TCEC-style time comments.
1292 my $moves = $pgn->moves;
1293 my $comments = $pgn->comments;
1294 my $last_black_move = int((scalar @$moves) / 2);
1295 my $last_white_move = int((1 + scalar @$moves) / 2);
1297 my $black_key = $last_black_move . "b";
1298 my $white_key = $last_white_move . "w";
1300 if (exists($comments->{$white_key}) &&
1301 exists($comments->{$black_key}) &&
1302 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1303 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1304 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1305 $pos->{'white_clock'} = hms_to_sec($1);
1306 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1307 $pos->{'black_clock'} = hms_to_sec($1);
1311 delete $pos->{'white_clock'};
1312 delete $pos->{'black_clock'};
1317 return undef if (!defined($hms));
1318 $hms =~ /(\d+):(\d+):(\d+)/;
1319 return $1 * 3600 + $2 * 60 + $3;
1322 sub find_clock_start {
1323 my ($pos, $prev_pos) = @_;
1325 # If the game is over, the clock is stopped.
1326 if (exists($pos->{'result'}) &&
1327 ($pos->{'result'} eq '1-0' ||
1328 $pos->{'result'} eq '1/2-1/2' ||
1329 $pos->{'result'} eq '0-1')) {
1333 # When we don't have any moves, we assume the clock hasn't started yet.
1334 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1335 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1336 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1341 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1342 # The history is needed for id_for_pos.
1343 if (!exists($pos->{'history'})) {
1347 my $id = id_for_pos($pos);
1348 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=? AND COALESCE(white_clock_target, black_clock_target) >= EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - INTERVAL \'1 day\'));', undef, $id);
1349 if (defined($clock_info)) {
1350 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1351 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1352 if ($pos->{'toplay'} eq 'W') {
1353 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1355 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1360 # OK, we haven't seen this position before, so we assume the move
1361 # happened right now.
1363 # See if we should do our own clock management (ie., clock information
1364 # is spurious or non-existent).
1365 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1366 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1367 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1368 if (defined($prev_pos->{'white_clock_target'})) {
1369 $wc = $prev_pos->{'white_clock_target'} - time;
1371 if (defined($prev_pos->{'black_clock_target'})) {
1372 $bc = $prev_pos->{'black_clock_target'} - time;
1374 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1375 $pos->{'white_clock'} = $wc;
1376 $pos->{'black_clock'} = $bc;
1379 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1380 if (!exists($pos->{$key})) {
1381 # No clock information.
1384 my $time_left = $pos->{$key};
1385 my ($white_clock_target, $black_clock_target);
1386 if ($pos->{'toplay'} eq 'W') {
1387 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1389 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1391 local $dbh->{AutoCommit} = 0;
1392 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1393 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1394 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1398 sub schedule_tb_lookup {
1399 return if (!defined($remoteglotconf::tb_serial_key));
1400 my $pos = $pos_calculating;
1401 return if (exists($tb_cache{$pos->fen()}));
1403 # If there's more than seven pieces, there's not going to be an answer,
1405 return if ($pos->num_pieces() > 7);
1407 # Max one at a time. If it's still relevant when it returns,
1408 # schedule_tb_lookup() will be called again.
1409 return if ($tb_lookup_running);
1411 $tb_lookup_running = 1;
1412 my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1413 $remoteglotconf::tb_serial_key .
1414 '&auth.password=aquarium&type=0&fen=' .
1415 URI::Escape::uri_escape($pos->fen());
1416 print TBLOG "Downloading $url...\n";
1417 AnyEvent::HTTP::http_get($url, sub {
1418 handle_tb_lookup_return(@_, $pos, $pos->fen());
1422 sub handle_tb_lookup_return {
1423 my ($body, $header, $pos, $fen) = @_;
1424 print TBLOG "Response for [$fen]:\n";
1425 print TBLOG $header . "\n\n";
1426 print TBLOG $body . "\n\n";
1428 my $response = JSON::XS::decode_json($body);
1429 if ($response->{'ErrorCode'} != 0) {
1430 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1432 my $state = $response->{'Response'}{'StateString'};
1433 if ($state eq 'COMPLETE') {
1434 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1435 if (!defined($pgn) || !$pgn->read_game()) {
1436 warn "Error in parsing PGN\n";
1438 $pgn->quick_parse_game;
1440 my $moves = $pgn->moves;
1442 for my $move (@$moves) {
1444 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1445 push @uci_moves, $uci_move;
1448 result => $pgn->result,
1450 score => $response->{'Response'}{'Score'},
1454 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1455 # Try again in a second. Note that if we have changed
1456 # position in the meantime, we might query a completely
1457 # different position! But that's fine.
1459 die "Unknown response state " . $state;
1462 # Wait a second before we schedule another one.
1463 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1464 $tb_lookup_running = 0;
1465 schedule_tb_lookup();
1469 warn "Error in tablebase lookup: $@";
1471 # Don't try this one again, but don't block new lookups either.
1472 $tb_lookup_running = 0;
1477 my ($cmdline, $tag, $cb) = @_;
1478 return undef if (!defined($cmdline));
1479 return Engine->open($cmdline, $tag, $cb);
1482 sub col_letter_to_num {
1483 return ord(shift) - ord('a');
1486 sub row_letter_to_num {
1487 return 7 - (ord(shift) - ord('1'));
1490 sub parse_uci_move {
1492 my $from_col = col_letter_to_num(substr($move, 0, 1));
1493 my $from_row = row_letter_to_num(substr($move, 1, 1));
1494 my $to_col = col_letter_to_num(substr($move, 2, 1));
1495 my $to_row = row_letter_to_num(substr($move, 3, 1));
1496 my $promo = substr($move, 4, 1);
1497 return ($from_row, $from_col, $to_row, $to_col, $promo);
1501 my ($engine, $config) = @_;
1502 uciprint($engine, "setoption name UCI_AnalyseMode value true");
1503 uciprint($engine, "setoption name Analysis Contempt value Off");
1504 if (exists($config->{'Threads'})) { # Threads first, because clearing hash can be multithreaded then.
1505 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1507 while (my ($key, $value) = each %$config) {
1508 next if $key eq 'Threads';
1509 uciprint($engine, "setoption name $key value $value");