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;
342 my @extra_moves = ();
343 $pos = extend_from_manual_override($pos, \@repretty_moves, \@extra_moves);
344 extract_clock($pgn, $pos);
345 $pos->{'history'} = \@repretty_moves;
346 $pos->{'extra_moves'} = \@extra_moves;
348 # Sometimes, PGNs lose a move or two for a short while,
349 # or people push out new ones non-atomically.
350 # Thus, if we PGN doesn't change names but becomes
351 # shorter, we mistrust it for a few seconds.
353 if (defined($last_pgn_white) && defined($last_pgn_black) &&
354 $last_pgn_white eq $pgn->white &&
355 $last_pgn_black eq $pgn->black &&
356 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
357 if (++$pgn_hysteresis_counter < 3) {
362 $last_pgn_white = $pgn->white;
363 $last_pgn_black = $pgn->black;
364 @last_pgn_uci_moves = @uci_moves;
365 $pgn_hysteresis_counter = 0;
366 handle_position($pos);
370 warn "Error in parsing moves from $url: $@\n";
374 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
379 sub handle_position {
381 find_clock_start($pos, $pos_calculating);
383 # If we're already chewing on this and there's nothing else in the queue,
385 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
386 $pos_calculating->{'result'} = $pos->{'result'};
387 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
388 $pos_calculating->{$key} //= $pos->{$key};
393 # If we're already thinking on something, stop and wait for the engine
395 if (defined($pos_calculating)) {
396 # Store the final data we have for this position in the history,
397 # with the precise clock information we just got from the new
398 # position. (Historic positions store the clock at the end of
401 # Do not output anything new to the main analysis; that's
402 # going to be obsolete really soon. (Exception: If we've never
403 # output anything for this move, ie., it didn't hit the 200ms
404 # limit, spit it out to the user anyway. It's probably a really
405 # fast blitz game or something, and it's good to show the moves
406 # as they come in even without great analysis.)
407 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
408 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
409 delete $pos_calculating->{'white_clock_target'};
410 delete $pos_calculating->{'black_clock_target'};
412 if (defined($pos_calculating_started)) {
417 $pos_calculating_started = [Time::HiRes::gettimeofday];
418 $pos_pv_started = undef;
420 # Ask the engine to stop; we will throw away its data until it
421 # sends us "bestmove", signaling the end of it.
422 $engine->{'stopping'} = 1;
423 uciprint($engine, "stop");
426 # It's wrong to just give the FEN (the move history is useful,
427 # and per the UCI spec, we should really have sent "ucinewgame"),
428 # but it's easier, and it works around a Stockfish repetition issue.
429 if ($engine->{'chess960'} != $pos->{'chess960'}) {
430 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
431 $engine->{'chess960'} = $pos->{'chess960'};
433 uciprint($engine, "position fen " . $pos->fen());
434 uciprint($engine, "go infinite");
435 $pos_calculating = $pos;
436 $pos_calculating_started = [Time::HiRes::gettimeofday];
437 $pos_pv_started = undef;
439 if (defined($engine2)) {
440 if (defined($pos_calculating_second_engine)) {
441 $engine2->{'stopping'} = 1;
442 uciprint($engine2, "stop");
444 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
445 uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
446 $engine2->{'chess960'} = $pos->{'chess960'};
448 uciprint($engine2, "position fen " . $pos->fen());
449 uciprint($engine2, "go infinite");
450 $pos_calculating_second_engine = $pos;
451 $engine2->{'info'} = {};
454 $engine->{'info'} = {};
458 # Output a command every move to note that we're
459 # still paying attention -- this is a good tradeoff,
460 # since if no move has happened in the last half
461 # hour, the analysis/relay has most likely stopped
462 # and we should stop hogging server resources.
470 my ($engine, @x) = @_;
473 my $info = $engine->{'info'};
475 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
476 for my $i (0..$#x - 1) {
477 if ($x[$i] eq 'multipv') {
483 while (scalar @x > 0) {
484 if ($x[0] eq 'multipv') {
490 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
492 my $value = shift @x;
493 $info->{$key} = $value;
496 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
497 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
500 my $value = shift @x;
501 $info->{$key . $mpv} = $value;
504 if ($x[0] eq 'score') {
507 delete $info->{'score_cp' . $mpv};
508 delete $info->{'score_mate' . $mpv};
509 delete $info->{'splicepos' . $mpv};
511 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
514 $info->{'score_cp' . $mpv} = shift @x;
515 } elsif ($x[0] eq 'mate') {
517 $info->{'score_mate' . $mpv} = shift @x;
525 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
528 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
532 #print "unknown info '$x[0]', trying to recover...\n";
534 die "Unknown info '" . join(',', @x) . "'";
540 my ($engine, @x) = @_;
542 while (scalar @x > 0) {
543 if ($x[0] eq 'name') {
544 my $value = join(' ', @x);
545 $engine->{'id'}{'author'} = $value;
554 sub prettyprint_pv_no_cache {
555 my ($board, @pvs) = @_;
557 if (scalar @pvs == 0 || !defined($pvs[0])) {
563 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
564 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
572 my ($pos, @pvs) = @_;
574 my $cachekey = join('', @pvs);
575 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
576 return @{$pos->{'prettyprint_cache'}{$cachekey}};
578 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
579 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
584 my %tbprobe_cache = ();
586 sub complete_using_tbprobe {
587 my ($pos, $info, $mpv) = @_;
589 # We need Fathom installed to do standalone TB probes.
590 return if (!defined($remoteglotconf::fathom_cmdline));
592 # If we already have a mate, don't bother; in some cases, it would even be
593 # better than a tablebase score.
594 return if defined($info->{'score_mate' . $mpv});
596 # If we have a draw or near-draw score, there's also not much interesting
597 # we could add from a tablebase. We only really want mates.
598 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
600 # Run through the PV until we are at a 6-man position.
601 # TODO: We could in theory only have 5-man data.
602 my @pv = @{$info->{'pv' . $mpv}};
603 my $key = $pos->fen() . " " . join('', @pv);
606 if (exists($tbprobe_cache{$key})) {
607 my $c = $tbprobe_cache{$key};
608 @moves = @{$c->{'moves'}};
609 $splicepos = $c->{'splicepos'};
612 # Force doing at least one move of the PV.
613 my $move = shift @pv;
615 $pos = $pos->make_move(parse_uci_move($move));
618 while ($pos->num_pieces() > 7 && $#pv > -1) {
619 my $move = shift @pv;
621 $pos = $pos->make_move(parse_uci_move($move));
624 return if ($pos->num_pieces() > 7);
626 my $fen = $pos->fen();
627 my $pgn_text = `$remoteglotconf::fathom_cmdline "$fen"`;
628 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
629 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
630 $pgn->quick_parse_game;
632 # Splice the PV from the tablebase onto what we have so far.
633 $splicepos = scalar @moves;
634 for my $move (@{$pgn->moves}) {
635 last if $move eq '#';
636 last if $move eq '1-0';
637 last if $move eq '0-1';
638 last if $move eq '1/2-1/2';
640 ($pos, $uci_move) = $pos->make_pretty_move($move);
641 push @moves, $uci_move;
644 $tbprobe_cache{$key} = {
646 splicepos => $splicepos
650 $info->{'pv' . $mpv} = \@moves;
652 my $matelen = int((1 + scalar @moves) / 2);
653 if ((scalar @moves) % 2 == 0) {
654 $info->{'score_mate' . $mpv} = -$matelen;
656 $info->{'score_mate' . $mpv} = $matelen;
658 $info->{'splicepos' . $mpv} = $splicepos;
664 return if (!defined($pos_calculating));
666 my $info = $engine->{'info'};
668 # Don't update too often.
669 my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
670 if (defined($pos_calculating_started)) {
671 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started);
672 $wait = $new_pos_wait if ($new_pos_wait < $wait);
674 if (!$last_output_had_pv && has_pv($info)) {
675 if (!defined($pos_pv_started)) {
676 $pos_pv_started = [Time::HiRes::gettimeofday];
678 # We just got initial PV, and we're in a hurry since we gave out a blank one earlier,
679 # so give us just 200ms more to increase the quality and then force a display.
680 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_pv_started);
681 $wait = $new_pos_wait if ($new_pos_wait < $wait);
684 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
687 $pos_pv_started = undef;
689 # We're outputting something for this position now, so the special handling
690 # for new positions is off.
691 undef $pos_calculating_started;
694 # Some programs _always_ report MultiPV, even with only one PV.
695 # In this case, we simply use that data as if MultiPV was never
698 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
699 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
700 if (exists($info->{$key . '1'})) {
701 $info->{$key} = $info->{$key . '1'};
703 delete $info->{$key};
709 # Check the PVs first. if they're invalid, just wait, as our data
710 # is most likely out of sync. This isn't a very good solution, as
711 # it can frequently miss stuff, but it's good enough for most users.
715 if (exists($info->{'pv'})) {
716 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
720 while (exists($info->{'pv' . $mpv})) {
721 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
726 $engine->{'info'} = {};
730 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
731 if (exists($info->{'pv'})) {
732 complete_using_tbprobe($pos_calculating, $info, '');
736 while (exists($info->{'pv' . $mpv})) {
737 complete_using_tbprobe($pos_calculating, $info, $mpv);
743 $latest_update = [Time::HiRes::gettimeofday];
744 $last_output_had_pv = has_pv($info);
749 return 1 if (exists($info->{'pv'}) && (scalar(@{$info->{'pv'}}) > 0));
750 return 1 if (exists($info->{'pv1'}) && (scalar(@{$info->{'pv1'}}) > 0));
755 my $info = $engine->{'info'};
756 my $id = $engine->{'id'};
758 my $text = 'Analysis';
759 if ($pos_calculating->{'last_move'} ne 'none') {
760 if ($pos_calculating->{'toplay'} eq 'W') {
761 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
763 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
765 if (exists($id->{'name'})) {
770 if (exists($id->{'name'})) {
771 $text .= " by $id->{'name'}:\n\n";
776 return unless (exists($pos_calculating->{'board'}));
778 my $extra_moves = $pos_calculating->{'extra_moves'};
779 if (defined($extra_moves) && scalar @$extra_moves > 0) {
780 $text .= " Manual move extensions: " . join(' ', @$extra_moves) . "\n";
783 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
786 while (exists($info->{'pv' . $mpv})) {
787 $text .= sprintf " PV%2u", $mpv;
788 my $score = short_score($info, $pos_calculating, $mpv);
789 $text .= " ($score)" if (defined($score));
792 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
793 if ($info->{'tbhits' . $mpv} == 1) {
794 $tbhits = ", 1 tbhit";
796 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
800 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
801 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
802 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
806 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
812 my $score = long_score($info, $pos_calculating, '');
813 $text .= " $score\n" if defined($score);
814 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
817 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
818 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
819 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
821 if (exists($info->{'seldepth'})) {
822 $text .= sprintf " (%u selective)", $info->{'seldepth'};
824 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
825 if ($info->{'tbhits'} == 1) {
826 $text .= ", one Syzygy hit";
828 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
834 my @refutation_lines = ();
835 if (defined($engine2)) {
836 for (my $mpv = 1; $mpv < 500; ++$mpv) {
837 my $info = $engine2->{'info'};
838 last if (!exists($info->{'pv' . $mpv}));
840 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
841 my $pv = $info->{'pv' . $mpv};
842 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
843 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
844 if (scalar @pretty_pv > 5) {
845 @pretty_pv = @pretty_pv[0..4];
846 push @pretty_pv, "...";
848 my $key = $pretty_move;
849 my $line = sprintf(" %-6s %6s %3s %s",
851 short_score($info, $pos_calculating_second_engine, $mpv),
852 "d" . $info->{'depth' . $mpv},
853 join(', ', @pretty_pv));
854 push @refutation_lines, [ $key, $line ];
859 if ($#refutation_lines >= 0) {
860 $text .= "Shallow search of all legal moves:\n\n";
861 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
862 $text .= $line->[1] . "\n";
867 if ($last_text ne $text) {
868 print "
\e[H
\e[2J"; # clear the screen
875 my $historic_json_only = shift;
876 my $info = $engine->{'info'};
879 $json->{'position'} = $pos_calculating->to_json_hash();
880 $json->{'engine'} = $engine->{'id'};
881 if (defined($remoteglotconf::engine_url)) {
882 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
884 if (defined($remoteglotconf::engine_details)) {
885 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
887 my @grpc_backends = ();
888 if (defined($remoteglotconf::engine_grpc_backend)) {
889 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
891 if (defined($remoteglotconf::engine2_grpc_backend)) {
892 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
894 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
895 if (defined($remoteglotconf::move_source)) {
896 $json->{'move_source'} = $remoteglotconf::move_source;
898 if (defined($remoteglotconf::move_source_url)) {
899 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
901 $json->{'score'} = score_digest($info, $pos_calculating, '');
903 $json->{'nodes'} = $info->{'nodes'};
904 $json->{'nps'} = $info->{'nps'};
905 $json->{'depth'} = $info->{'depth'};
906 $json->{'tbhits'} = $info->{'tbhits'};
907 $json->{'seldepth'} = $info->{'seldepth'};
908 $json->{'tablebase'} = $info->{'tablebase'};
909 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
911 my %refutation_lines = ();
912 my @refutation_lines = ();
913 if (defined($engine2)) {
914 for (my $mpv = 1; $mpv < 500; ++$mpv) {
915 my $info = $engine2->{'info'};
916 my $pretty_move = "";
918 last if (!exists($info->{'pv' . $mpv}));
921 complete_using_tbprobe($pos_calculating, $info, $mpv);
922 my $pv = $info->{'pv' . $mpv};
923 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
924 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
925 $refutation_lines{$pretty_move} = {
926 depth => $info->{'depth' . $mpv},
927 score => score_digest($info, $pos_calculating, $mpv),
928 move => $pretty_move,
931 if (exists($info->{'splicepos' . $mpv})) {
932 $refutation_lines{$pretty_move}->{'splicepos'} = $info->{'splicepos' . $mpv};
937 $json->{'refutation_lines'} = \%refutation_lines;
939 # Piece together historic score information, to the degree we have it.
940 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
941 my %score_history = ();
943 local $dbh->{AutoCommit} = 0;
944 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
946 if (exists($pos_calculating->{'start_fen'})) {
947 $pos = Position->from_fen($pos_calculating->{'start_fen'});
949 $pos = Position->start_pos('white', 'black');
951 $pos->{'chess960'} = $pos_calculating->{'chess960'};
952 my $halfmove_num = 0;
953 for my $move (@{$pos_calculating->{'history'}}) {
954 my $id = id_for_pos($pos, $halfmove_num);
955 my $ref = $dbh->selectrow_hashref($q, undef, $id);
957 $score_history{$halfmove_num} = [
958 $ref->{'score_type'},
959 $ref->{'score_value'}
963 ($pos) = $pos->make_pretty_move($move);
968 # If at any point we are missing 10 consecutive moves,
969 # truncate the history there. This is so we don't get into
970 # a situation where we e.g. start analyzing at move 45,
971 # but we have analysis for 1. e4 from some completely different game
972 # and thus show a huge hole.
973 my $consecutive_missing = 0;
974 my $truncate_until = 0;
975 for (my $i = $halfmove_num; $i --> 0; ) {
976 if ($consecutive_missing >= 10) {
977 delete $score_history{$i};
980 if (exists($score_history{$i})) {
981 $consecutive_missing = 0;
983 ++$consecutive_missing;
987 $json->{'score_history'} = \%score_history;
990 # Give out a list of other games going on. (Empty is fine.)
991 # TODO: Don't bother reading our own file, the data will be stale anyway.
992 if (!$historic_json_only) {
995 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
997 while (my $ref = $q->fetchrow_hashref) {
999 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
1000 my $other_game_json = JSON::XS::decode_json($other_game_contents);
1002 die "Missing position" if (!exists($other_game_json->{'position'}));
1003 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
1004 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
1008 name => "$white–$black",
1009 url => $ref->{'url'},
1010 hashurl => $ref->{'hash_url'},
1012 if (defined($other_game_json->{'position'}{'result'})) {
1013 $game->{'result'} = $other_game_json->{'position'}{'result'};
1015 $game->{'score'} = $other_game_json->{'score'};
1020 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
1024 if (scalar @games > 0) {
1025 $json->{'games'} = \@games;
1029 my $json_enc = JSON::XS->new;
1030 $json_enc->canonical(1);
1031 my $encoded = $json_enc->encode($json);
1032 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1033 (defined($last_written_json) && $last_written_json eq $encoded)) {
1034 atomic_set_contents($remoteglotconf::json_output, $encoded);
1035 $last_written_json = $encoded;
1038 if (exists($pos_calculating->{'history'}) &&
1039 defined($remoteglotconf::json_history_dir) && defined($json->{'engine'}{name})) {
1040 my $id = id_for_pos($pos_calculating);
1041 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1043 # Overwrite old analysis (assuming it exists at all) if we're
1044 # using a different engine, or if we've calculated deeper.
1045 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1046 # data; it's not that important.
1047 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1048 my $new_depth = $json->{'depth'} // 0;
1049 my $new_nodes = $json->{'nodes'} // 0;
1050 if (!defined($old_engine) ||
1051 $old_engine ne $json->{'engine'}{'name'} ||
1052 $new_depth > $old_depth ||
1053 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1054 atomic_set_contents($filename, $encoded);
1055 if (defined($json->{'score'})) {
1056 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1057 ' ON CONFLICT (id) DO UPDATE SET ' .
1058 ' score_type=EXCLUDED.score_type, ' .
1059 ' score_value=EXCLUDED.score_value, ' .
1060 ' engine=EXCLUDED.engine, ' .
1061 ' depth=EXCLUDED.depth, ' .
1062 ' nodes=EXCLUDED.nodes',
1064 $id, $json->{'score'}[0], $json->{'score'}[1],
1065 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1071 sub atomic_set_contents {
1072 my ($filename, $contents) = @_;
1074 open my $fh, ">", $filename . ".tmp"
1076 print $fh $contents;
1078 rename($filename . ".tmp", $filename);
1082 my ($pos, $halfmove_num) = @_;
1084 $halfmove_num //= scalar @{$pos->{'history'}};
1085 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1086 return "move$halfmove_num-$fen";
1089 sub get_json_analysis_stats {
1091 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1092 if (defined($ref)) {
1093 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1100 my ($engine, $msg) = @_;
1101 $engine->print($msg);
1102 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1106 my ($info, $pos, $mpv) = @_;
1108 my $invert = ($pos->{'toplay'} eq 'B');
1109 if (defined($info->{'score_mate' . $mpv})) {
1111 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1113 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1116 if (exists($info->{'score_cp' . $mpv})) {
1117 my $score = $info->{'score_cp' . $mpv} * 0.01;
1119 if ($info->{'tablebase'}) {
1128 return sprintf "%+5.2f", $score;
1135 # Sufficient for computing long_score, short_score, plot_score and
1136 # (with side-to-play information) score_sort_key.
1138 my ($info, $pos, $mpv) = @_;
1140 if (defined($info->{'score_mate' . $mpv})) {
1141 my $mate = $info->{'score_mate' . $mpv};
1142 if ($pos->{'toplay'} eq 'B') {
1145 if (exists($info->{'splicepos' . $mpv})) {
1146 my $sp = $info->{'splicepos' . $mpv};
1154 return ['M', $mate];
1155 } elsif ($mate < 0) {
1156 return ['m', -$mate];
1157 } elsif ($pos->{'toplay'} eq 'B') {
1164 if (exists($info->{'score_cp' . $mpv})) {
1165 my $score = $info->{'score_cp' . $mpv};
1166 if ($pos->{'toplay'} eq 'B') {
1169 if ($score == 0 && $info->{'tablebase'}) {
1170 return ['d', undef];
1172 return ['cp', int($score)];
1181 my ($info, $pos, $mpv) = @_;
1183 if (defined($info->{'score_mate' . $mpv})) {
1184 my $mate = $info->{'score_mate' . $mpv};
1185 if ($pos->{'toplay'} eq 'B') {
1188 if (exists($info->{'splicepos' . $mpv})) {
1189 my $sp = $info->{'splicepos' . $mpv};
1191 return sprintf "White wins in %u", int(($sp + 1) * 0.5);
1193 return sprintf "Black wins in %u", int(($sp + 1) * 0.5);
1197 return sprintf "White mates in %u", $mate;
1199 return sprintf "Black mates in %u", -$mate;
1203 if (exists($info->{'score_cp' . $mpv})) {
1204 my $score = $info->{'score_cp' . $mpv} * 0.01;
1206 if ($info->{'tablebase'}) {
1207 return "Theoretical draw";
1209 return "Score: 0.00";
1212 if ($pos->{'toplay'} eq 'B') {
1215 return sprintf "Score: %+5.2f", $score;
1222 # For graphs; a single number in centipawns, capped at +/- 500.
1224 my ($info, $pos, $mpv) = @_;
1226 my $invert = ($pos->{'toplay'} eq 'B');
1227 if (defined($info->{'score_mate' . $mpv})) {
1228 my $mate = $info->{'score_mate' . $mpv};
1238 if (exists($info->{'score_cp' . $mpv})) {
1239 my $score = $info->{'score_cp' . $mpv};
1243 $score = 500 if ($score > 500);
1244 $score = -500 if ($score < -500);
1252 sub extend_from_manual_override {
1253 my ($pos, $moves, $extra_moves) = @_;
1255 my $q = $dbh->prepare('SELECT next_move FROM game_extensions WHERE fen=? AND history=? AND player_w=? AND player_b=? AND (CURRENT_TIMESTAMP - ts) < INTERVAL \'1 hour\'');
1257 my $player_w = $pos->{'player_w'};
1258 my $player_b = $pos->{'player_b'};
1259 if ($player_w =~ /^base64:(.*)$/) {
1260 $player_w = MIME::Base64::decode_base64($1);
1262 if ($player_b =~ /^base64:(.*)$/) {
1263 $player_b = MIME::Base64::decode_base64($1);
1265 #use Data::Dumper; print Dumper([$pos->fen(), JSON::XS::encode_json($moves), $player_w, $player_b]);
1266 $q->execute($pos->fen(), JSON::XS::encode_json($moves), $player_w, $player_b);
1267 my $ref = $q->fetchrow_hashref;
1268 if (defined($ref)) {
1269 my $move = $ref->{'next_move'};
1270 ($pos) = $pos->make_pretty_move($move);
1271 push @$moves, $move;
1272 push @$extra_moves, $move;
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);
1399 my ($cmdline, $tag, $cb) = @_;
1400 return undef if (!defined($cmdline));
1401 return Engine->open($cmdline, $tag, $cb);
1404 sub col_letter_to_num {
1405 return ord(shift) - ord('a');
1408 sub row_letter_to_num {
1409 return 7 - (ord(shift) - ord('1'));
1412 sub parse_uci_move {
1414 my $from_col = col_letter_to_num(substr($move, 0, 1));
1415 my $from_row = row_letter_to_num(substr($move, 1, 1));
1416 my $to_col = col_letter_to_num(substr($move, 2, 1));
1417 my $to_row = row_letter_to_num(substr($move, 3, 1));
1418 my $promo = substr($move, 4, 1);
1419 return ($from_row, $from_col, $to_row, $to_col, $promo);
1423 my ($engine, $config) = @_;
1424 uciprint($engine, "setoption name UCI_AnalyseMode value true");
1425 uciprint($engine, "setoption name Analysis Contempt value Off");
1426 if (exists($config->{'Threads'})) { # Threads first, because clearing hash can be multithreaded then.
1427 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1429 while (my ($key, $value) = each %$config) {
1430 next if $key eq 'Threads';
1431 uciprint($engine, "setoption name $key value $value");