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;
38 my $tb_lookup_running = 0;
39 my $last_written_json = undef;
41 # Persisted so we can restart.
42 # TODO: Figure out an appropriate way to deal with database restarts
43 # and/or Postgres going away entirely.
44 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
46 $dbh->{RaiseError} = 1;
50 open(FICSLOG, ">ficslog.txt")
51 or die "ficslog.txt: $!";
52 print FICSLOG "Log starting.\n";
56 open(UCILOG, ">ucilog.txt")
57 or die "ucilog.txt: $!";
58 print UCILOG "Log starting.\n";
62 open(TBLOG, ">tblog.txt")
63 or die "tblog.txt: $!";
64 print TBLOG "Log starting.\n";
69 umask 0022; # analysis.json should not be served to users.
71 # open the chess engine
72 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
73 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
76 my ($pos_calculating, $pos_calculating_second_engine);
78 # If not undef, we've started calculating this position but haven't ever given out
79 # any analysis for it, so we're on a forced timer to do so.
80 my $pos_calculating_started = undef;
82 # If not undef, we've output this position, but without a main PV, so we're on
83 # _another_ forced timer to do so.
84 my $pos_pv_started = undef;
85 my $last_output_had_pv = 0;
87 setoptions($engine, \%remoteglotconf::engine_config);
88 uciprint($engine, "ucinewgame");
90 if (defined($engine2)) {
91 setoptions($engine2, \%remoteglotconf::engine2_config);
92 uciprint($engine2, "setoption name MultiPV value 500");
93 uciprint($engine2, "ucinewgame");
96 print "Chess engine ready.\n";
100 if (defined($remoteglotconf::server)) {
101 $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
102 $t->input_log(\*FICSLOG);
103 $t->open($remoteglotconf::server);
104 $t->print($remoteglotconf::nick);
105 $t->waitfor('/Press return to enter the server/');
109 $t->cmd("set shout 0");
110 $t->cmd("set seek 0");
111 $t->cmd("set style 12");
116 cb => sub { # what callback to execute
118 my $line = $t->getline(Timeout => 0, errmode => 'return');
119 return if (!defined($line));
128 if (defined($remoteglotconf::target)) {
129 if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
130 fetch_pgn($remoteglotconf::target);
131 } elsif (defined($t)) {
132 $t->cmd("observe $remoteglotconf::target");
136 print "FICS ready.\n";
139 # Engine events have already been set up by Engine.pm.
143 my ($engine, $line, $primary) = @_;
145 return if $line =~ /(upper|lower)bound/;
147 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
148 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
150 # If we've sent a stop command, gobble up lines until we see bestmove.
151 return if ($engine->{'stopping'} && $line !~ /^bestmove/);
152 $engine->{'stopping'} = 0;
154 if ($line =~ /^info/ && $line !~ / cluster /) {
155 my (@infos) = split / /, $line;
158 parse_infos($engine, @infos);
160 if ($line =~ /^id/) {
161 my (@ids) = split / /, $line;
164 parse_ids($engine, @ids);
169 my $getting_movelist = 0;
170 my $pos_for_movelist = undef;
171 my @uci_movelist = ();
172 my @pretty_movelist = ();
176 if ($line =~ /^<12> /) {
177 handle_position(Position->new($line));
180 if ($line =~ /^Movelist for game /) {
181 my $pos = $pos_calculating;
184 @pretty_movelist = ();
185 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
186 $getting_movelist = 1;
189 if ($getting_movelist &&
190 $line =~ /^\s* \d+\. \s+ # move number
191 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
192 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
196 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
197 push @uci_movelist, $uci_move;
198 push @pretty_movelist, $1;
201 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
202 push @uci_movelist, $uci_move;
203 push @pretty_movelist, $2;
207 warn "Error when getting FICS move history: $@";
208 $getting_movelist = 0;
211 if ($getting_movelist &&
212 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
214 if (defined($pos_calculating)) {
215 if ($pos_calculating->fen() eq $pos_for_movelist->fen()) {
216 $pos_calculating->{'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 if ($url =~ m#^/#) { # Local file.
256 open my $fh, "<", $url
260 handle_pgn($pgn, '', $url);
264 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
269 AnyEvent::HTTP::http_get($url, sub {
270 handle_pgn(@_, $url);
275 my ($last_pgn_white, $last_pgn_black);
276 my @last_pgn_uci_moves = ();
277 my $pgn_hysteresis_counter = 0;
280 my ($body, $header, $url) = @_;
282 if ($stop_pgn_fetch) {
288 my $pgn = Chess::PGN::Parse->new(undef, $body);
289 if (!defined($pgn)) {
290 warn "Error in parsing PGN from $url [body='$body']\n";
291 } elsif (!$pgn->read_game()) {
292 warn "Error in reading PGN game from $url [body='$body']\n";
293 } elsif ($body !~ /^\[/) {
294 warn "Malformed PGN from $url [body='$body']\n";
297 # Skip to the right game.
298 while (defined($remoteglotconf::pgn_filter) &&
299 !&$remoteglotconf::pgn_filter($pgn)) {
300 $pgn->read_game() or die "Out of games during filtering";
303 $pgn->parse_game({ save_comments => 'yes' });
304 my $white = $pgn->white;
305 my $black = $pgn->black;
306 $white =~ s/,.*//; # Remove first name.
307 $black =~ s/,.*//; # Remove first name.
308 my $tags = $pgn->tags();
310 if (exists($tags->{'FEN'})) {
311 $pos = Position->from_fen($tags->{'FEN'});
312 $pos->{'last_move'} = 'none';
313 $pos->{'player_w'} = $white;
314 $pos->{'player_b'} = $black;
315 $pos->{'start_fen'} = $tags->{'FEN'};
317 $pos = Position->start_pos($white, $black);
319 if (exists($tags->{'Variant'}) &&
320 $tags->{'Variant'} =~ /960|fischer/i) {
321 $pos->{'chess960'} = 1;
323 $pos->{'chess960'} = 0;
325 my $moves = $pgn->moves;
327 my @repretty_moves = ();
328 for my $move (@$moves) {
329 my ($npos, $uci_move) = $pos->make_pretty_move($move);
330 push @uci_moves, $uci_move;
332 # Re-prettyprint the move.
333 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
334 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
335 push @repretty_moves, $pretty;
338 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
339 $pos->{'result'} = $pgn->result;
341 $pos->{'history'} = \@repretty_moves;
343 extract_clock($pgn, $pos);
345 # Sometimes, PGNs lose a move or two for a short while,
346 # or people push out new ones non-atomically.
347 # Thus, if we PGN doesn't change names but becomes
348 # shorter, we mistrust it for a few seconds.
350 if (defined($last_pgn_white) && defined($last_pgn_black) &&
351 $last_pgn_white eq $pgn->white &&
352 $last_pgn_black eq $pgn->black &&
353 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
354 if (++$pgn_hysteresis_counter < 3) {
359 $last_pgn_white = $pgn->white;
360 $last_pgn_black = $pgn->black;
361 @last_pgn_uci_moves = @uci_moves;
362 $pgn_hysteresis_counter = 0;
363 handle_position($pos);
367 warn "Error in parsing moves from $url: $@\n";
371 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
376 sub handle_position {
378 find_clock_start($pos, $pos_calculating);
380 # If we're already chewing on this and there's nothing else in the queue,
382 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
383 $pos_calculating->{'result'} = $pos->{'result'};
384 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
385 $pos_calculating->{$key} //= $pos->{$key};
390 # If we're already thinking on something, stop and wait for the engine
392 if (defined($pos_calculating)) {
393 # Store the final data we have for this position in the history,
394 # with the precise clock information we just got from the new
395 # position. (Historic positions store the clock at the end of
398 # Do not output anything new to the main analysis; that's
399 # going to be obsolete really soon. (Exception: If we've never
400 # output anything for this move, ie., it didn't hit the 200ms
401 # limit, spit it out to the user anyway. It's probably a really
402 # fast blitz game or something, and it's good to show the moves
403 # as they come in even without great analysis.)
404 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
405 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
406 delete $pos_calculating->{'white_clock_target'};
407 delete $pos_calculating->{'black_clock_target'};
409 if (defined($pos_calculating_started)) {
414 $pos_calculating_started = [Time::HiRes::gettimeofday];
415 $pos_pv_started = undef;
417 # Ask the engine to stop; we will throw away its data until it
418 # sends us "bestmove", signaling the end of it.
419 $engine->{'stopping'} = 1;
420 uciprint($engine, "stop");
423 # It's wrong to just give the FEN (the move history is useful,
424 # and per the UCI spec, we should really have sent "ucinewgame"),
425 # but it's easier, and it works around a Stockfish repetition issue.
426 if ($engine->{'chess960'} != $pos->{'chess960'}) {
427 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
428 $engine->{'chess960'} = $pos->{'chess960'};
430 uciprint($engine, "position fen " . $pos->fen());
431 uciprint($engine, "go infinite");
432 $pos_calculating = $pos;
433 $pos_calculating_started = [Time::HiRes::gettimeofday];
434 $pos_pv_started = undef;
436 if (defined($engine2)) {
437 if (defined($pos_calculating_second_engine)) {
438 $engine2->{'stopping'} = 1;
439 uciprint($engine2, "stop");
441 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
442 uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
443 $engine2->{'chess960'} = $pos->{'chess960'};
445 uciprint($engine2, "position fen " . $pos->fen());
446 uciprint($engine2, "go infinite");
447 $pos_calculating_second_engine = $pos;
448 $engine2->{'info'} = {};
451 $engine->{'info'} = {};
455 # Output a command every move to note that we're
456 # still paying attention -- this is a good tradeoff,
457 # since if no move has happened in the last half
458 # hour, the analysis/relay has most likely stopped
459 # and we should stop hogging server resources.
467 my ($engine, @x) = @_;
470 my $info = $engine->{'info'};
472 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
473 for my $i (0..$#x - 1) {
474 if ($x[$i] eq 'multipv') {
480 while (scalar @x > 0) {
481 if ($x[0] eq 'multipv') {
487 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
489 my $value = shift @x;
490 $info->{$key} = $value;
493 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
494 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
497 my $value = shift @x;
498 $info->{$key . $mpv} = $value;
501 if ($x[0] eq 'score') {
504 delete $info->{'score_cp' . $mpv};
505 delete $info->{'score_mate' . $mpv};
506 delete $info->{'splicepos' . $mpv};
508 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
511 $info->{'score_cp' . $mpv} = shift @x;
512 } elsif ($x[0] eq 'mate') {
514 $info->{'score_mate' . $mpv} = shift @x;
522 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
525 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
529 #print "unknown info '$x[0]', trying to recover...\n";
531 die "Unknown info '" . join(',', @x) . "'";
537 my ($engine, @x) = @_;
539 while (scalar @x > 0) {
540 if ($x[0] eq 'name') {
541 my $value = join(' ', @x);
542 $engine->{'id'}{'author'} = $value;
551 sub prettyprint_pv_no_cache {
552 my ($board, @pvs) = @_;
554 if (scalar @pvs == 0 || !defined($pvs[0])) {
560 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
561 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
569 my ($pos, @pvs) = @_;
571 my $cachekey = join('', @pvs);
572 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
573 return @{$pos->{'prettyprint_cache'}{$cachekey}};
575 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
576 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
581 my %tbprobe_cache = ();
583 sub complete_using_tbprobe {
584 my ($pos, $info, $mpv) = @_;
586 # We need Fathom installed to do standalone TB probes.
587 return if (!defined($remoteglotconf::fathom_cmdline));
589 # If we already have a mate, don't bother; in some cases, it would even be
590 # better than a tablebase score.
591 return if defined($info->{'score_mate' . $mpv});
593 # If we have a draw or near-draw score, there's also not much interesting
594 # we could add from a tablebase. We only really want mates.
595 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
597 # Run through the PV until we are at a 6-man position.
598 # TODO: We could in theory only have 5-man data.
599 my @pv = @{$info->{'pv' . $mpv}};
600 my $key = $pos->fen() . " " . join('', @pv);
603 if (exists($tbprobe_cache{$key})) {
604 my $c = $tbprobe_cache{$key};
605 @moves = @{$c->{'moves'}};
606 $splicepos = $c->{'splicepos'};
609 # Force doing at least one move of the PV.
610 my $move = shift @pv;
612 $pos = $pos->make_move(parse_uci_move($move));
615 while ($pos->num_pieces() > 7 && $#pv > -1) {
616 my $move = shift @pv;
618 $pos = $pos->make_move(parse_uci_move($move));
621 return if ($pos->num_pieces() > 7);
623 my $fen = $pos->fen();
624 my $pgn_text = `$remoteglotconf::fathom_cmdline "$fen"`;
625 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
626 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
627 $pgn->quick_parse_game;
629 # Splice the PV from the tablebase onto what we have so far.
630 $splicepos = scalar @moves;
631 for my $move (@{$pgn->moves}) {
632 last if $move eq '#';
633 last if $move eq '1-0';
634 last if $move eq '0-1';
635 last if $move eq '1/2-1/2';
637 ($pos, $uci_move) = $pos->make_pretty_move($move);
638 push @moves, $uci_move;
641 $tbprobe_cache{$key} = {
643 splicepos => $splicepos
647 $info->{'pv' . $mpv} = \@moves;
649 my $matelen = int((1 + scalar @moves) / 2);
650 if ((scalar @moves) % 2 == 0) {
651 $info->{'score_mate' . $mpv} = -$matelen;
653 $info->{'score_mate' . $mpv} = $matelen;
655 $info->{'splicepos' . $mpv} = $splicepos;
661 return if (!defined($pos_calculating));
663 my $info = $engine->{'info'};
665 # Don't update too often.
666 my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
667 if (defined($pos_calculating_started)) {
668 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started);
669 $wait = $new_pos_wait if ($new_pos_wait < $wait);
671 if (!$last_output_had_pv && has_pv($info)) {
672 if (!defined($pos_pv_started)) {
673 $pos_pv_started = [Time::HiRes::gettimeofday];
675 # We just got initial PV, and we're in a hurry since we gave out a blank one earlier,
676 # so give us just 200ms more to increase the quality and then force a display.
677 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_pv_started);
678 $wait = $new_pos_wait if ($new_pos_wait < $wait);
681 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
684 $pos_pv_started = undef;
686 # We're outputting something for this position now, so the special handling
687 # for new positions is off.
688 undef $pos_calculating_started;
691 # Some programs _always_ report MultiPV, even with only one PV.
692 # In this case, we simply use that data as if MultiPV was never
695 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
696 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
697 if (exists($info->{$key . '1'})) {
698 $info->{$key} = $info->{$key . '1'};
700 delete $info->{$key};
706 # Check the PVs first. if they're invalid, just wait, as our data
707 # is most likely out of sync. This isn't a very good solution, as
708 # it can frequently miss stuff, but it's good enough for most users.
712 if (exists($info->{'pv'})) {
713 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
717 while (exists($info->{'pv' . $mpv})) {
718 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
723 $engine->{'info'} = {};
727 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
728 if (exists($info->{'pv'})) {
729 complete_using_tbprobe($pos_calculating, $info, '');
733 while (exists($info->{'pv' . $mpv})) {
734 complete_using_tbprobe($pos_calculating, $info, $mpv);
740 $latest_update = [Time::HiRes::gettimeofday];
741 $last_output_had_pv = has_pv($info);
746 return 1 if (exists($info->{'pv'}) && (scalar(@{$info->{'pv'}}) > 0));
747 return 1 if (exists($info->{'pv1'}) && (scalar(@{$info->{'pv1'}}) > 0));
752 my $info = $engine->{'info'};
753 my $id = $engine->{'id'};
755 my $text = 'Analysis';
756 if ($pos_calculating->{'last_move'} ne 'none') {
757 if ($pos_calculating->{'toplay'} eq 'W') {
758 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
760 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
762 if (exists($id->{'name'})) {
767 if (exists($id->{'name'})) {
768 $text .= " by $id->{'name'}:\n\n";
773 return unless (exists($pos_calculating->{'board'}));
775 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
778 while (exists($info->{'pv' . $mpv})) {
779 $text .= sprintf " PV%2u", $mpv;
780 my $score = short_score($info, $pos_calculating, $mpv);
781 $text .= " ($score)" if (defined($score));
784 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
785 if ($info->{'tbhits' . $mpv} == 1) {
786 $tbhits = ", 1 tbhit";
788 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
792 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
793 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
794 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
798 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
804 my $score = long_score($info, $pos_calculating, '');
805 $text .= " $score\n" if defined($score);
806 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
809 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
810 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
811 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
813 if (exists($info->{'seldepth'})) {
814 $text .= sprintf " (%u selective)", $info->{'seldepth'};
816 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
817 if ($info->{'tbhits'} == 1) {
818 $text .= ", one Syzygy hit";
820 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
826 my @refutation_lines = ();
827 if (defined($engine2)) {
828 for (my $mpv = 1; $mpv < 500; ++$mpv) {
829 my $info = $engine2->{'info'};
830 last if (!exists($info->{'pv' . $mpv}));
832 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
833 my $pv = $info->{'pv' . $mpv};
834 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
835 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
836 if (scalar @pretty_pv > 5) {
837 @pretty_pv = @pretty_pv[0..4];
838 push @pretty_pv, "...";
840 my $key = $pretty_move;
841 my $line = sprintf(" %-6s %6s %3s %s",
843 short_score($info, $pos_calculating_second_engine, $mpv),
844 "d" . $info->{'depth' . $mpv},
845 join(', ', @pretty_pv));
846 push @refutation_lines, [ $key, $line ];
851 if ($#refutation_lines >= 0) {
852 $text .= "Shallow search of all legal moves:\n\n";
853 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
854 $text .= $line->[1] . "\n";
859 if ($last_text ne $text) {
860 print "
\e[H
\e[2J"; # clear the screen
867 my $historic_json_only = shift;
868 my $info = $engine->{'info'};
871 $json->{'position'} = $pos_calculating->to_json_hash();
872 $json->{'engine'} = $engine->{'id'};
873 if (defined($remoteglotconf::engine_url)) {
874 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
876 if (defined($remoteglotconf::engine_details)) {
877 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
879 my @grpc_backends = ();
880 if (defined($remoteglotconf::engine_grpc_backend)) {
881 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
883 if (defined($remoteglotconf::engine2_grpc_backend)) {
884 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
886 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
887 if (defined($remoteglotconf::move_source)) {
888 $json->{'move_source'} = $remoteglotconf::move_source;
890 if (defined($remoteglotconf::move_source_url)) {
891 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
893 $json->{'score'} = score_digest($info, $pos_calculating, '');
895 $json->{'nodes'} = $info->{'nodes'};
896 $json->{'nps'} = $info->{'nps'};
897 $json->{'depth'} = $info->{'depth'};
898 $json->{'tbhits'} = $info->{'tbhits'};
899 $json->{'seldepth'} = $info->{'seldepth'};
900 $json->{'tablebase'} = $info->{'tablebase'};
901 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
903 my %refutation_lines = ();
904 my @refutation_lines = ();
905 if (defined($engine2)) {
906 for (my $mpv = 1; $mpv < 500; ++$mpv) {
907 my $info = $engine2->{'info'};
908 my $pretty_move = "";
910 last if (!exists($info->{'pv' . $mpv}));
913 complete_using_tbprobe($pos_calculating, $info, $mpv);
914 my $pv = $info->{'pv' . $mpv};
915 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
916 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
917 $refutation_lines{$pretty_move} = {
918 depth => $info->{'depth' . $mpv},
919 score => score_digest($info, $pos_calculating, $mpv),
920 move => $pretty_move,
923 if (exists($info->{'splicepos' . $mpv})) {
924 $refutation_lines{$pretty_move}->{'splicepos'} = $info->{'splicepos' . $mpv};
929 $json->{'refutation_lines'} = \%refutation_lines;
931 # Piece together historic score information, to the degree we have it.
932 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
933 my %score_history = ();
935 local $dbh->{AutoCommit} = 0;
936 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
938 if (exists($pos_calculating->{'start_fen'})) {
939 $pos = Position->from_fen($pos_calculating->{'start_fen'});
941 $pos = Position->start_pos('white', 'black');
943 $pos->{'chess960'} = $pos_calculating->{'chess960'};
944 my $halfmove_num = 0;
945 for my $move (@{$pos_calculating->{'history'}}) {
946 my $id = id_for_pos($pos, $halfmove_num);
947 my $ref = $dbh->selectrow_hashref($q, undef, $id);
949 $score_history{$halfmove_num} = [
950 $ref->{'score_type'},
951 $ref->{'score_value'}
955 ($pos) = $pos->make_pretty_move($move);
960 # If at any point we are missing 10 consecutive moves,
961 # truncate the history there. This is so we don't get into
962 # a situation where we e.g. start analyzing at move 45,
963 # but we have analysis for 1. e4 from some completely different game
964 # and thus show a huge hole.
965 my $consecutive_missing = 0;
966 my $truncate_until = 0;
967 for (my $i = $halfmove_num; $i --> 0; ) {
968 if ($consecutive_missing >= 10) {
969 delete $score_history{$i};
972 if (exists($score_history{$i})) {
973 $consecutive_missing = 0;
975 ++$consecutive_missing;
979 $json->{'score_history'} = \%score_history;
982 # Give out a list of other games going on. (Empty is fine.)
983 # TODO: Don't bother reading our own file, the data will be stale anyway.
984 if (!$historic_json_only) {
987 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
989 while (my $ref = $q->fetchrow_hashref) {
991 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
992 my $other_game_json = JSON::XS::decode_json($other_game_contents);
994 die "Missing position" if (!exists($other_game_json->{'position'}));
995 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
996 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
1000 name => "$white–$black",
1001 url => $ref->{'url'},
1002 hashurl => $ref->{'hash_url'},
1004 if (defined($other_game_json->{'position'}{'result'})) {
1005 $game->{'result'} = $other_game_json->{'position'}{'result'};
1007 $game->{'score'} = $other_game_json->{'score'};
1012 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
1016 if (scalar @games > 0) {
1017 $json->{'games'} = \@games;
1021 my $json_enc = JSON::XS->new;
1022 $json_enc->canonical(1);
1023 my $encoded = $json_enc->encode($json);
1024 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1025 (defined($last_written_json) && $last_written_json eq $encoded)) {
1026 atomic_set_contents($remoteglotconf::json_output, $encoded);
1027 $last_written_json = $encoded;
1030 if (exists($pos_calculating->{'history'}) &&
1031 defined($remoteglotconf::json_history_dir) && defined($json->{'engine'}{name})) {
1032 my $id = id_for_pos($pos_calculating);
1033 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1035 # Overwrite old analysis (assuming it exists at all) if we're
1036 # using a different engine, or if we've calculated deeper.
1037 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1038 # data; it's not that important.
1039 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1040 my $new_depth = $json->{'depth'} // 0;
1041 my $new_nodes = $json->{'nodes'} // 0;
1042 if (!defined($old_engine) ||
1043 $old_engine ne $json->{'engine'}{'name'} ||
1044 $new_depth > $old_depth ||
1045 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1046 atomic_set_contents($filename, $encoded);
1047 if (defined($json->{'score'})) {
1048 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1049 ' ON CONFLICT (id) DO UPDATE SET ' .
1050 ' score_type=EXCLUDED.score_type, ' .
1051 ' score_value=EXCLUDED.score_value, ' .
1052 ' engine=EXCLUDED.engine, ' .
1053 ' depth=EXCLUDED.depth, ' .
1054 ' nodes=EXCLUDED.nodes',
1056 $id, $json->{'score'}[0], $json->{'score'}[1],
1057 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1063 sub atomic_set_contents {
1064 my ($filename, $contents) = @_;
1066 open my $fh, ">", $filename . ".tmp"
1068 print $fh $contents;
1070 rename($filename . ".tmp", $filename);
1074 my ($pos, $halfmove_num) = @_;
1076 $halfmove_num //= scalar @{$pos->{'history'}};
1077 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1078 return "move$halfmove_num-$fen";
1081 sub get_json_analysis_stats {
1083 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1084 if (defined($ref)) {
1085 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1092 my ($engine, $msg) = @_;
1093 $engine->print($msg);
1094 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1098 my ($info, $pos, $mpv) = @_;
1100 my $invert = ($pos->{'toplay'} eq 'B');
1101 if (defined($info->{'score_mate' . $mpv})) {
1103 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1105 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1108 if (exists($info->{'score_cp' . $mpv})) {
1109 my $score = $info->{'score_cp' . $mpv} * 0.01;
1111 if ($info->{'tablebase'}) {
1120 return sprintf "%+5.2f", $score;
1127 # Sufficient for computing long_score, short_score, plot_score and
1128 # (with side-to-play information) score_sort_key.
1130 my ($info, $pos, $mpv) = @_;
1132 if (defined($info->{'score_mate' . $mpv})) {
1133 my $mate = $info->{'score_mate' . $mpv};
1134 if ($pos->{'toplay'} eq 'B') {
1137 if (exists($info->{'splicepos' . $mpv})) {
1138 my $sp = $info->{'splicepos' . $mpv};
1146 return ['M', $mate];
1147 } elsif ($mate < 0) {
1148 return ['m', -$mate];
1149 } elsif ($pos->{'toplay'} eq 'B') {
1156 if (exists($info->{'score_cp' . $mpv})) {
1157 my $score = $info->{'score_cp' . $mpv};
1158 if ($pos->{'toplay'} eq 'B') {
1161 if ($score == 0 && $info->{'tablebase'}) {
1162 return ['d', undef];
1164 return ['cp', int($score)];
1173 my ($info, $pos, $mpv) = @_;
1175 if (defined($info->{'score_mate' . $mpv})) {
1176 my $mate = $info->{'score_mate' . $mpv};
1177 if ($pos->{'toplay'} eq 'B') {
1180 if (exists($info->{'splicepos' . $mpv})) {
1181 my $sp = $info->{'splicepos' . $mpv};
1183 return sprintf "White wins in %u", int(($sp + 1) * 0.5);
1185 return sprintf "Black wins in %u", int(($sp + 1) * 0.5);
1189 return sprintf "White mates in %u", $mate;
1191 return sprintf "Black mates in %u", -$mate;
1195 if (exists($info->{'score_cp' . $mpv})) {
1196 my $score = $info->{'score_cp' . $mpv} * 0.01;
1198 if ($info->{'tablebase'}) {
1199 return "Theoretical draw";
1201 return "Score: 0.00";
1204 if ($pos->{'toplay'} eq 'B') {
1207 return sprintf "Score: %+5.2f", $score;
1214 # For graphs; a single number in centipawns, capped at +/- 500.
1216 my ($info, $pos, $mpv) = @_;
1218 my $invert = ($pos->{'toplay'} eq 'B');
1219 if (defined($info->{'score_mate' . $mpv})) {
1220 my $mate = $info->{'score_mate' . $mpv};
1230 if (exists($info->{'score_cp' . $mpv})) {
1231 my $score = $info->{'score_cp' . $mpv};
1235 $score = 500 if ($score > 500);
1236 $score = -500 if ($score < -500);
1245 my ($pgn, $pos) = @_;
1247 # Look for extended PGN clock tags.
1248 my $tags = $pgn->tags;
1249 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1250 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1251 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1255 # Look for TCEC-style time comments.
1256 my $moves = $pgn->moves;
1257 my $comments = $pgn->comments;
1258 my $last_black_move = int((scalar @$moves) / 2);
1259 my $last_white_move = int((1 + scalar @$moves) / 2);
1261 my $black_key = $last_black_move . "b";
1262 my $white_key = $last_white_move . "w";
1264 if (exists($comments->{$white_key}) &&
1265 exists($comments->{$black_key}) &&
1266 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1267 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1268 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1269 $pos->{'white_clock'} = hms_to_sec($1);
1270 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1271 $pos->{'black_clock'} = hms_to_sec($1);
1275 delete $pos->{'white_clock'};
1276 delete $pos->{'black_clock'};
1281 return undef if (!defined($hms));
1282 $hms =~ /(\d+):(\d+):(\d+)/;
1283 return $1 * 3600 + $2 * 60 + $3;
1286 sub find_clock_start {
1287 my ($pos, $prev_pos) = @_;
1289 # If the game is over, the clock is stopped.
1290 if (exists($pos->{'result'}) &&
1291 ($pos->{'result'} eq '1-0' ||
1292 $pos->{'result'} eq '1/2-1/2' ||
1293 $pos->{'result'} eq '0-1')) {
1297 # When we don't have any moves, we assume the clock hasn't started yet.
1298 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1299 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1300 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1305 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1306 # The history is needed for id_for_pos.
1307 if (!exists($pos->{'history'})) {
1311 my $id = id_for_pos($pos);
1312 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);
1313 if (defined($clock_info)) {
1314 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1315 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1316 if ($pos->{'toplay'} eq 'W') {
1317 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1319 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1324 # OK, we haven't seen this position before, so we assume the move
1325 # happened right now.
1327 # See if we should do our own clock management (ie., clock information
1328 # is spurious or non-existent).
1329 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1330 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1331 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1332 if (defined($prev_pos->{'white_clock_target'})) {
1333 $wc = $prev_pos->{'white_clock_target'} - time;
1335 if (defined($prev_pos->{'black_clock_target'})) {
1336 $bc = $prev_pos->{'black_clock_target'} - time;
1338 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1339 $pos->{'white_clock'} = $wc;
1340 $pos->{'black_clock'} = $bc;
1343 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1344 if (!exists($pos->{$key})) {
1345 # No clock information.
1348 my $time_left = $pos->{$key};
1349 my ($white_clock_target, $black_clock_target);
1350 if ($pos->{'toplay'} eq 'W') {
1351 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1353 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1355 local $dbh->{AutoCommit} = 0;
1356 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1357 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1358 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1363 my ($cmdline, $tag, $cb) = @_;
1364 return undef if (!defined($cmdline));
1365 return Engine->open($cmdline, $tag, $cb);
1368 sub col_letter_to_num {
1369 return ord(shift) - ord('a');
1372 sub row_letter_to_num {
1373 return 7 - (ord(shift) - ord('1'));
1376 sub parse_uci_move {
1378 my $from_col = col_letter_to_num(substr($move, 0, 1));
1379 my $from_row = row_letter_to_num(substr($move, 1, 1));
1380 my $to_col = col_letter_to_num(substr($move, 2, 1));
1381 my $to_row = row_letter_to_num(substr($move, 3, 1));
1382 my $promo = substr($move, 4, 1);
1383 return ($from_row, $from_col, $to_row, $to_col, $promo);
1387 my ($engine, $config) = @_;
1388 uciprint($engine, "setoption name UCI_AnalyseMode value true");
1389 uciprint($engine, "setoption name Analysis Contempt value Off");
1390 if (exists($config->{'Threads'})) { # Threads first, because clearing hash can be multithreaded then.
1391 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1393 while (my ($key, $value) = each %$config) {
1394 next if $key eq 'Threads';
1395 uciprint($engine, "setoption name $key value $value");