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 # If not undef, we've output this position, but without a main PV, so we're on
84 # _another_ forced timer to do so.
85 my $pos_pv_started = undef;
86 my $last_output_had_pv = 0;
88 setoptions($engine, \%remoteglotconf::engine_config);
89 uciprint($engine, "ucinewgame");
91 if (defined($engine2)) {
92 setoptions($engine2, \%remoteglotconf::engine2_config);
93 uciprint($engine2, "setoption name MultiPV value 500");
94 uciprint($engine2, "ucinewgame");
97 print "Chess engine ready.\n";
101 if (defined($remoteglotconf::server)) {
102 $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
103 $t->input_log(\*FICSLOG);
104 $t->open($remoteglotconf::server);
105 $t->print($remoteglotconf::nick);
106 $t->waitfor('/Press return to enter the server/');
110 $t->cmd("set shout 0");
111 $t->cmd("set seek 0");
112 $t->cmd("set style 12");
117 cb => sub { # what callback to execute
119 my $line = $t->getline(Timeout => 0, errmode => 'return');
120 return if (!defined($line));
129 if (defined($remoteglotconf::target)) {
130 if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
131 fetch_pgn($remoteglotconf::target);
132 } elsif (defined($t)) {
133 $t->cmd("observe $remoteglotconf::target");
137 print "FICS ready.\n";
140 # Engine events have already been set up by Engine.pm.
144 my ($engine, $line, $primary) = @_;
146 return if $line =~ /(upper|lower)bound/;
148 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
149 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
151 # If we've sent a stop command, gobble up lines until we see bestmove.
152 return if ($engine->{'stopping'} && $line !~ /^bestmove/);
153 $engine->{'stopping'} = 0;
155 if ($line =~ /^info/) {
156 my (@infos) = split / /, $line;
159 parse_infos($engine, @infos);
161 if ($line =~ /^id/) {
162 my (@ids) = split / /, $line;
165 parse_ids($engine, @ids);
170 my $getting_movelist = 0;
171 my $pos_for_movelist = undef;
172 my @uci_movelist = ();
173 my @pretty_movelist = ();
177 if ($line =~ /^<12> /) {
178 handle_position(Position->new($line));
181 if ($line =~ /^Movelist for game /) {
182 my $pos = $pos_calculating;
185 @pretty_movelist = ();
186 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
187 $getting_movelist = 1;
190 if ($getting_movelist &&
191 $line =~ /^\s* \d+\. \s+ # move number
192 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
193 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
197 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
198 push @uci_movelist, $uci_move;
199 push @pretty_movelist, $1;
202 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
203 push @uci_movelist, $uci_move;
204 push @pretty_movelist, $2;
208 warn "Error when getting FICS move history: $@";
209 $getting_movelist = 0;
212 if ($getting_movelist &&
213 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
215 if (defined($pos_calculating)) {
216 if ($pos_calculating->fen() eq $pos_for_movelist->fen()) {
217 $pos_calculating->{'history'} = \@pretty_movelist;
220 $getting_movelist = 0;
222 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
223 my ($who, $msg) = ($1, $2);
225 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
227 if ($msg =~ /^fics (.*?)$/) {
228 $t->cmd("tell $who Executing '$1' on FICS.");
230 } elsif ($msg =~ /^uci (.*?)$/) {
231 $t->cmd("tell $who Sending '$1' to the engine.");
232 print { $engine->{'write'} } "$1\n";
233 } elsif ($msg =~ /^pgn (.*?)$/) {
235 $t->cmd("tell $who Starting to poll '$url'.");
237 } elsif ($msg =~ /^stoppgn$/) {
238 $t->cmd("tell $who Stopping poll.");
241 } elsif ($msg =~ /^quit$/) {
242 $t->cmd("tell $who Bye bye.");
245 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
248 #print "FICS: [$line]\n";
251 # Starts periodic fetching of PGNs from the given URL.
254 if ($url =~ m#^/#) { # Local file.
257 open my $fh, "<", $url
261 handle_pgn($pgn, '', $url);
265 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
270 AnyEvent::HTTP::http_get($url, sub {
271 handle_pgn(@_, $url);
276 my ($last_pgn_white, $last_pgn_black);
277 my @last_pgn_uci_moves = ();
278 my $pgn_hysteresis_counter = 0;
281 my ($body, $header, $url) = @_;
283 if ($stop_pgn_fetch) {
289 my $pgn = Chess::PGN::Parse->new(undef, $body);
290 if (!defined($pgn)) {
291 warn "Error in parsing PGN from $url [body='$body']\n";
292 } elsif (!$pgn->read_game()) {
293 warn "Error in reading PGN game from $url [body='$body']\n";
294 } elsif ($body !~ /^\[/) {
295 warn "Malformed PGN from $url [body='$body']\n";
298 # Skip to the right game.
299 while (defined($remoteglotconf::pgn_filter) &&
300 !&$remoteglotconf::pgn_filter($pgn)) {
301 $pgn->read_game() or die "Out of games during filtering";
304 $pgn->parse_game({ save_comments => 'yes' });
305 my $white = $pgn->white;
306 my $black = $pgn->black;
307 $white =~ s/,.*//; # Remove first name.
308 $black =~ s/,.*//; # Remove first name.
309 my $tags = $pgn->tags();
311 if (exists($tags->{'FEN'})) {
312 $pos = Position->from_fen($tags->{'FEN'});
313 $pos->{'last_move'} = 'none';
314 $pos->{'player_w'} = $white;
315 $pos->{'player_b'} = $black;
316 $pos->{'start_fen'} = $tags->{'FEN'};
318 $pos = Position->start_pos($white, $black);
320 if (exists($tags->{'Variant'}) &&
321 $tags->{'Variant'} =~ /960|fischer/i) {
322 $pos->{'chess960'} = 1;
324 $pos->{'chess960'} = 0;
326 my $moves = $pgn->moves;
328 my @repretty_moves = ();
329 for my $move (@$moves) {
330 my ($npos, $uci_move) = $pos->make_pretty_move($move);
331 push @uci_moves, $uci_move;
333 # Re-prettyprint the move.
334 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
335 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
336 push @repretty_moves, $pretty;
339 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
340 $pos->{'result'} = $pgn->result;
342 $pos->{'history'} = \@repretty_moves;
344 extract_clock($pgn, $pos);
346 # Sometimes, PGNs lose a move or two for a short while,
347 # or people push out new ones non-atomically.
348 # Thus, if we PGN doesn't change names but becomes
349 # shorter, we mistrust it for a few seconds.
351 if (defined($last_pgn_white) && defined($last_pgn_black) &&
352 $last_pgn_white eq $pgn->white &&
353 $last_pgn_black eq $pgn->black &&
354 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
355 if (++$pgn_hysteresis_counter < 3) {
360 $last_pgn_white = $pgn->white;
361 $last_pgn_black = $pgn->black;
362 @last_pgn_uci_moves = @uci_moves;
363 $pgn_hysteresis_counter = 0;
364 handle_position($pos);
368 warn "Error in parsing moves from $url: $@\n";
372 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
377 sub handle_position {
379 find_clock_start($pos, $pos_calculating);
381 # If we're already chewing on this and there's nothing else in the queue,
383 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
384 $pos_calculating->{'result'} = $pos->{'result'};
385 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
386 $pos_calculating->{$key} //= $pos->{$key};
391 # If we're already thinking on something, stop and wait for the engine
393 if (defined($pos_calculating)) {
394 # Store the final data we have for this position in the history,
395 # with the precise clock information we just got from the new
396 # position. (Historic positions store the clock at the end of
399 # Do not output anything new to the main analysis; that's
400 # going to be obsolete really soon. (Exception: If we've never
401 # output anything for this move, ie., it didn't hit the 200ms
402 # limit, spit it out to the user anyway. It's probably a really
403 # fast blitz game or something, and it's good to show the moves
404 # as they come in even without great analysis.)
405 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
406 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
407 delete $pos_calculating->{'white_clock_target'};
408 delete $pos_calculating->{'black_clock_target'};
410 if (defined($pos_calculating_started)) {
415 $pos_calculating_started = [Time::HiRes::gettimeofday];
416 $pos_pv_started = undef;
418 # Ask the engine to stop; we will throw away its data until it
419 # sends us "bestmove", signaling the end of it.
420 $engine->{'stopping'} = 1;
421 uciprint($engine, "stop");
424 # It's wrong to just give the FEN (the move history is useful,
425 # and per the UCI spec, we should really have sent "ucinewgame"),
426 # but it's easier, and it works around a Stockfish repetition issue.
427 if ($engine->{'chess960'} != $pos->{'chess960'}) {
428 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
429 $engine->{'chess960'} = $pos->{'chess960'};
431 uciprint($engine, "position fen " . $pos->fen());
432 uciprint($engine, "go infinite");
433 $pos_calculating = $pos;
434 $pos_calculating_started = [Time::HiRes::gettimeofday];
435 $pos_pv_started = undef;
437 if (defined($engine2)) {
438 if (defined($pos_calculating_second_engine)) {
439 $engine2->{'stopping'} = 1;
440 uciprint($engine2, "stop");
442 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
443 uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
444 $engine2->{'chess960'} = $pos->{'chess960'};
446 uciprint($engine2, "position fen " . $pos->fen());
447 uciprint($engine2, "go infinite");
448 $pos_calculating_second_engine = $pos;
449 $engine2->{'info'} = {};
452 $engine->{'info'} = {};
455 schedule_tb_lookup();
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 my $prev_depth = $info->{'depth1'} // $info->{'depth'};
485 while (scalar @x > 0) {
486 if ($x[0] eq 'multipv') {
492 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
494 my $value = shift @x;
495 $info->{$key} = $value;
498 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
499 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
502 my $value = shift @x;
503 $info->{$key . $mpv} = $value;
506 if ($x[0] eq 'score') {
509 delete $info->{'score_cp' . $mpv};
510 delete $info->{'score_mate' . $mpv};
511 delete $info->{'splicepos' . $mpv};
513 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
516 $info->{'score_cp' . $mpv} = shift @x;
517 } elsif ($x[0] eq 'mate') {
519 $info->{'score_mate' . $mpv} = shift @x;
527 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
530 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
534 #print "unknown info '$x[0]', trying to recover...\n";
536 die "Unknown info '" . join(',', @x) . "'";
540 my $now_depth = $info->{'depth1'} // $info->{'depth'};
541 if (defined($prev_depth) && POSIX::floor($now_depth / 10) > POSIX::floor($prev_depth / 10)) {
542 my $d = POSIX::floor($now_depth / 10) * 10; # In case we skipped some.
543 complete_using_tbprobe($pos_calculating, $info, exists($info->{'depth1'}) ? '1' : '');
544 my $cp = $info->{'score_cp1'} // $info->{'score_cp'};
545 my $mate = $info->{'score_mate1'} // $info->{'score_mate'};
546 my $splicepos = $info->{'splicepos1'} // $info->{'splicepos'};
548 if (defined($info->{'pv1'})) { # Avoid autovivification.
549 $bestmove = $info->{'pv1'}[0];
551 $bestmove = $info->{'pv'}[0];
553 push @{$info->{'lowdepth'}}, [ $d, $cp, $mate, $splicepos, $bestmove ];
558 my ($engine, @x) = @_;
560 while (scalar @x > 0) {
561 if ($x[0] eq 'name') {
562 my $value = join(' ', @x);
563 $engine->{'id'}{'author'} = $value;
572 sub prettyprint_pv_no_cache {
573 my ($board, @pvs) = @_;
575 if (scalar @pvs == 0 || !defined($pvs[0])) {
581 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
582 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
590 my ($pos, @pvs) = @_;
592 my $cachekey = join('', @pvs);
593 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
594 return @{$pos->{'prettyprint_cache'}{$cachekey}};
596 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
597 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
602 my %tbprobe_cache = ();
604 sub complete_using_tbprobe {
605 my ($pos, $info, $mpv) = @_;
607 # We need Fathom installed to do standalone TB probes.
608 return if (!defined($remoteglotconf::fathom_cmdline));
610 # If we already have a mate, don't bother; in some cases, it would even be
611 # better than a tablebase score.
612 return if defined($info->{'score_mate' . $mpv});
614 # If we have a draw or near-draw score, there's also not much interesting
615 # we could add from a tablebase. We only really want mates.
616 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
618 # Run through the PV until we are at a 6-man position.
619 # TODO: We could in theory only have 5-man data.
620 my @pv = @{$info->{'pv' . $mpv}};
621 my $key = $pos->fen() . " " . join('', @pv);
624 if (exists($tbprobe_cache{$key})) {
625 my $c = $tbprobe_cache{$key};
626 @moves = @{$c->{'moves'}};
627 $splicepos = $c->{'splicepos'};
630 # Force doing at least one move of the PV.
631 my $move = shift @pv;
633 $pos = $pos->make_move(parse_uci_move($move));
636 while ($pos->num_pieces() > 7 && $#pv > -1) {
637 my $move = shift @pv;
639 $pos = $pos->make_move(parse_uci_move($move));
642 return if ($pos->num_pieces() > 7);
644 my $fen = $pos->fen();
645 my $pgn_text = `$remoteglotconf::fathom_cmdline "$fen"`;
646 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
647 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
648 $pgn->quick_parse_game;
650 # Splice the PV from the tablebase onto what we have so far.
651 $splicepos = scalar @moves;
652 for my $move (@{$pgn->moves}) {
653 last if $move eq '#';
654 last if $move eq '1-0';
655 last if $move eq '0-1';
656 last if $move eq '1/2-1/2';
658 ($pos, $uci_move) = $pos->make_pretty_move($move);
659 push @moves, $uci_move;
662 $tbprobe_cache{$key} = {
664 splicepos => $splicepos
668 $info->{'pv' . $mpv} = \@moves;
670 my $matelen = int((1 + scalar @moves) / 2);
671 if ((scalar @moves) % 2 == 0) {
672 $info->{'score_mate' . $mpv} = -$matelen;
674 $info->{'score_mate' . $mpv} = $matelen;
676 $info->{'splicepos' . $mpv} = $splicepos;
682 return if (!defined($pos_calculating));
684 my $info = $engine->{'info'};
686 # Don't update too often.
687 my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
688 if (defined($pos_calculating_started)) {
689 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started);
690 $wait = $new_pos_wait if ($new_pos_wait < $wait);
692 if (!$last_output_had_pv && has_pv($info)) {
693 if (!defined($pos_pv_started)) {
694 $pos_pv_started = [Time::HiRes::gettimeofday];
696 # We just got initial PV, and we're in a hurry since we gave out a blank one earlier,
697 # so give us just 200ms more to increase the quality and then force a display.
698 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_pv_started);
699 $wait = $new_pos_wait if ($new_pos_wait < $wait);
702 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
705 $pos_pv_started = undef;
707 # We're outputting something for this position now, so the special handling
708 # for new positions is off.
709 undef $pos_calculating_started;
712 # If we have tablebase data from a previous lookup, replace the
713 # engine data with the data from the tablebase.
715 my $fen = $pos_calculating->fen();
716 if (exists($tb_cache{$fen})) {
717 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
718 delete $info->{$key . '1'};
719 delete $info->{$key};
721 $info->{'nodes'} = 0;
723 $info->{'depth'} = 0;
724 $info->{'seldepth'} = 0;
725 $info->{'tbhits'} = 0;
727 my $t = $tb_cache{$fen};
729 my $matelen = int((1 + $t->{'score'}) / 2);
730 if ($t->{'result'} eq '1/2-1/2') {
731 $info->{'score_cp'} = 0;
732 } elsif ($t->{'result'} eq '1-0') {
733 if ($pos_calculating->{'toplay'} eq 'B') {
734 $info->{'score_mate'} = -$matelen;
736 $info->{'score_mate'} = $matelen;
739 if ($pos_calculating->{'toplay'} eq 'B') {
740 $info->{'score_mate'} = $matelen;
742 $info->{'score_mate'} = -$matelen;
746 $info->{'tablebase'} = 1;
748 $info->{'tablebase'} = 0;
752 # Some programs _always_ report MultiPV, even with only one PV.
753 # In this case, we simply use that data as if MultiPV was never
756 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
757 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
758 if (exists($info->{$key . '1'})) {
759 $info->{$key} = $info->{$key . '1'};
761 delete $info->{$key};
767 # Check the PVs first. if they're invalid, just wait, as our data
768 # is most likely out of sync. This isn't a very good solution, as
769 # it can frequently miss stuff, but it's good enough for most users.
773 if (exists($info->{'pv'})) {
774 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
778 while (exists($info->{'pv' . $mpv})) {
779 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
784 $engine->{'info'} = {};
788 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
789 if (exists($info->{'pv'})) {
790 complete_using_tbprobe($pos_calculating, $info, '');
794 while (exists($info->{'pv' . $mpv})) {
795 complete_using_tbprobe($pos_calculating, $info, $mpv);
801 $latest_update = [Time::HiRes::gettimeofday];
802 $last_output_had_pv = has_pv($info);
807 return 1 if (exists($info->{'pv'}) && (scalar(@{$info->{'pv'}}) > 0));
808 return 1 if (exists($info->{'pv1'}) && (scalar(@{$info->{'pv1'}}) > 0));
813 my $info = $engine->{'info'};
814 my $id = $engine->{'id'};
816 my $text = 'Analysis';
817 if ($pos_calculating->{'last_move'} ne 'none') {
818 if ($pos_calculating->{'toplay'} eq 'W') {
819 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
821 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
823 if (exists($id->{'name'})) {
828 if (exists($id->{'name'})) {
829 $text .= " by $id->{'name'}:\n\n";
834 return unless (exists($pos_calculating->{'board'}));
836 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
839 while (exists($info->{'pv' . $mpv})) {
840 $text .= sprintf " PV%2u", $mpv;
841 my $score = short_score($info, $pos_calculating, $mpv);
842 $text .= " ($score)" if (defined($score));
845 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
846 if ($info->{'tbhits' . $mpv} == 1) {
847 $tbhits = ", 1 tbhit";
849 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
853 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
854 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
855 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
859 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
865 my $score = long_score($info, $pos_calculating, '');
866 $text .= " $score\n" if defined($score);
867 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
870 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
871 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
872 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
874 if (exists($info->{'seldepth'})) {
875 $text .= sprintf " (%u selective)", $info->{'seldepth'};
877 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
878 if ($info->{'tbhits'} == 1) {
879 $text .= ", one Syzygy hit";
881 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
887 my @refutation_lines = ();
888 if (defined($engine2)) {
889 for (my $mpv = 1; $mpv < 500; ++$mpv) {
890 my $info = $engine2->{'info'};
891 last if (!exists($info->{'pv' . $mpv}));
893 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
894 my $pv = $info->{'pv' . $mpv};
895 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
896 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
897 if (scalar @pretty_pv > 5) {
898 @pretty_pv = @pretty_pv[0..4];
899 push @pretty_pv, "...";
901 my $key = $pretty_move;
902 my $line = sprintf(" %-6s %6s %3s %s",
904 short_score($info, $pos_calculating_second_engine, $mpv),
905 "d" . $info->{'depth' . $mpv},
906 join(', ', @pretty_pv));
907 push @refutation_lines, [ $key, $line ];
912 if ($#refutation_lines >= 0) {
913 $text .= "Shallow search of all legal moves:\n\n";
914 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
915 $text .= $line->[1] . "\n";
920 if ($last_text ne $text) {
921 print "
\e[H
\e[2J"; # clear the screen
928 my $historic_json_only = shift;
929 my $info = $engine->{'info'};
932 $json->{'position'} = $pos_calculating->to_json_hash();
933 $json->{'engine'} = $engine->{'id'};
934 if (defined($remoteglotconf::engine_url)) {
935 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
937 if (defined($remoteglotconf::engine_details)) {
938 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
940 my @grpc_backends = ();
941 if (defined($remoteglotconf::engine_grpc_backend)) {
942 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
944 if (defined($remoteglotconf::engine2_grpc_backend)) {
945 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
947 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
948 if (defined($remoteglotconf::move_source)) {
949 $json->{'move_source'} = $remoteglotconf::move_source;
951 if (defined($remoteglotconf::move_source_url)) {
952 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
954 $json->{'score'} = score_digest($info, $pos_calculating, '');
955 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
957 $json->{'nodes'} = $info->{'nodes'};
958 $json->{'nps'} = $info->{'nps'};
959 $json->{'depth'} = $info->{'depth'};
960 $json->{'tbhits'} = $info->{'tbhits'};
961 $json->{'seldepth'} = $info->{'seldepth'};
962 $json->{'tablebase'} = $info->{'tablebase'};
963 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
965 $json->{'lowdepth'} = {};
966 if (exists($info->{'lowdepth'})) {
967 for my $ld (@{$info->{'lowdepth'}}) {
968 my $score = score_digest_inner($ld->[1], $ld->[2], $ld->[3], 0, $pos_calculating);
969 push @$score, prettyprint_pv($pos_calculating, $ld->[4]);
970 $json->{'lowdepth'}{$ld->[0]} = $score;
974 my %refutation_lines = ();
975 my @refutation_lines = ();
976 if (defined($engine2)) {
977 for (my $mpv = 1; $mpv < 500; ++$mpv) {
978 my $info = $engine2->{'info'};
979 my $pretty_move = "";
981 last if (!exists($info->{'pv' . $mpv}));
984 complete_using_tbprobe($pos_calculating, $info, $mpv);
985 my $pv = $info->{'pv' . $mpv};
986 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
987 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
988 $refutation_lines{$pretty_move} = {
989 depth => $info->{'depth' . $mpv},
990 score => score_digest($info, $pos_calculating, $mpv),
991 move => $pretty_move,
994 if (exists($info->{'splicepos' . $mpv})) {
995 $refutation_lines{$pretty_move}->{'splicepos'} = $info->{'splicepos' . $mpv};
1000 $json->{'refutation_lines'} = \%refutation_lines;
1002 # Piece together historic score information, to the degree we have it.
1003 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
1004 my %score_history = ();
1006 local $dbh->{AutoCommit} = 0;
1007 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
1009 if (exists($pos_calculating->{'start_fen'})) {
1010 $pos = Position->from_fen($pos_calculating->{'start_fen'});
1012 $pos = Position->start_pos('white', 'black');
1014 $pos->{'chess960'} = $pos_calculating->{'chess960'};
1015 my $halfmove_num = 0;
1016 for my $move (@{$pos_calculating->{'history'}}) {
1017 my $id = id_for_pos($pos, $halfmove_num);
1018 my $ref = $dbh->selectrow_hashref($q, undef, $id);
1019 if (defined($ref)) {
1020 $score_history{$halfmove_num} = [
1021 $ref->{'score_type'},
1022 $ref->{'score_value'}
1026 ($pos) = $pos->make_pretty_move($move);
1031 # If at any point we are missing 10 consecutive moves,
1032 # truncate the history there. This is so we don't get into
1033 # a situation where we e.g. start analyzing at move 45,
1034 # but we have analysis for 1. e4 from some completely different game
1035 # and thus show a huge hole.
1036 my $consecutive_missing = 0;
1037 my $truncate_until = 0;
1038 for (my $i = $halfmove_num; $i --> 0; ) {
1039 if ($consecutive_missing >= 10) {
1040 delete $score_history{$i};
1043 if (exists($score_history{$i})) {
1044 $consecutive_missing = 0;
1046 ++$consecutive_missing;
1050 $json->{'score_history'} = \%score_history;
1053 # Give out a list of other games going on. (Empty is fine.)
1054 # TODO: Don't bother reading our own file, the data will be stale anyway.
1055 if (!$historic_json_only) {
1058 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
1060 while (my $ref = $q->fetchrow_hashref) {
1062 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
1063 my $other_game_json = JSON::XS::decode_json($other_game_contents);
1065 die "Missing position" if (!exists($other_game_json->{'position'}));
1066 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
1067 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
1071 name => "$white–$black",
1072 url => $ref->{'url'},
1073 hashurl => $ref->{'hash_url'},
1075 if (defined($other_game_json->{'position'}{'result'})) {
1076 $game->{'result'} = $other_game_json->{'position'}{'result'};
1078 $game->{'score'} = $other_game_json->{'score'};
1083 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
1087 if (scalar @games > 0) {
1088 $json->{'games'} = \@games;
1092 my $json_enc = JSON::XS->new;
1093 $json_enc->canonical(1);
1094 my $encoded = $json_enc->encode($json);
1095 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
1096 (defined($last_written_json) && $last_written_json eq $encoded)) {
1097 atomic_set_contents($remoteglotconf::json_output, $encoded);
1098 $last_written_json = $encoded;
1101 if (exists($pos_calculating->{'history'}) &&
1102 defined($remoteglotconf::json_history_dir)) {
1103 my $id = id_for_pos($pos_calculating);
1104 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1106 # Overwrite old analysis (assuming it exists at all) if we're
1107 # using a different engine, or if we've calculated deeper.
1108 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1109 # data; it's not that important.
1110 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1111 my $new_depth = $json->{'depth'} // 0;
1112 my $new_nodes = $json->{'nodes'} // 0;
1113 if (!defined($old_engine) ||
1114 $old_engine ne $json->{'engine'}{'name'} ||
1115 $new_depth > $old_depth ||
1116 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1117 atomic_set_contents($filename, $encoded);
1118 if (defined($json->{'score'})) {
1119 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1120 ' ON CONFLICT (id) DO UPDATE SET ' .
1121 ' score_type=EXCLUDED.score_type, ' .
1122 ' score_value=EXCLUDED.score_value, ' .
1123 ' engine=EXCLUDED.engine, ' .
1124 ' depth=EXCLUDED.depth, ' .
1125 ' nodes=EXCLUDED.nodes',
1127 $id, $json->{'score'}[0], $json->{'score'}[1],
1128 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1134 sub atomic_set_contents {
1135 my ($filename, $contents) = @_;
1137 open my $fh, ">", $filename . ".tmp"
1139 print $fh $contents;
1141 rename($filename . ".tmp", $filename);
1145 my ($pos, $halfmove_num) = @_;
1147 $halfmove_num //= scalar @{$pos->{'history'}};
1148 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1149 return "move$halfmove_num-$fen";
1152 sub get_json_analysis_stats {
1154 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1155 if (defined($ref)) {
1156 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1163 my ($engine, $msg) = @_;
1164 $engine->print($msg);
1165 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1169 my ($info, $pos, $mpv) = @_;
1171 my $invert = ($pos->{'toplay'} eq 'B');
1172 if (defined($info->{'score_mate' . $mpv})) {
1174 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1176 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1179 if (exists($info->{'score_cp' . $mpv})) {
1180 my $score = $info->{'score_cp' . $mpv} * 0.01;
1182 if ($info->{'tablebase'}) {
1191 return sprintf "%+5.2f", $score;
1198 # Sufficient for computing long_score, short_score, plot_score and
1199 # (with side-to-play information) score_sort_key.
1201 my ($info, $pos, $mpv) = @_;
1202 return score_digest_inner(
1203 $info->{'score_cp' . $mpv},
1204 $info->{'score_mate' . $mpv},
1205 $info->{'splicepos' . $mpv},
1206 $info->{'tablebase'},
1210 sub score_digest_inner {
1211 my ($score, $mate, $sp, $tablebase, $pos) = @_;
1212 if (defined($mate)) {
1213 if ($pos->{'toplay'} eq 'B') {
1224 return ['M', $mate];
1225 } elsif ($mate < 0) {
1226 return ['m', -$mate];
1227 } elsif ($pos->{'toplay'} eq 'B') {
1234 if (defined($score)) {
1235 if ($pos->{'toplay'} eq 'B') {
1238 if ($score == 0 && $tablebase) {
1239 return ['d', undef];
1241 return ['cp', int($score)];
1250 my ($info, $pos, $mpv) = @_;
1252 if (defined($info->{'score_mate' . $mpv})) {
1253 my $mate = $info->{'score_mate' . $mpv};
1254 if ($pos->{'toplay'} eq 'B') {
1257 if (exists($info->{'splicepos' . $mpv})) {
1258 my $sp = $info->{'splicepos' . $mpv};
1260 return sprintf "White wins in %u", int(($sp + 1) * 0.5);
1262 return sprintf "Black wins in %u", int(($sp + 1) * 0.5);
1266 return sprintf "White mates in %u", $mate;
1268 return sprintf "Black mates in %u", -$mate;
1272 if (exists($info->{'score_cp' . $mpv})) {
1273 my $score = $info->{'score_cp' . $mpv} * 0.01;
1275 if ($info->{'tablebase'}) {
1276 return "Theoretical draw";
1278 return "Score: 0.00";
1281 if ($pos->{'toplay'} eq 'B') {
1284 return sprintf "Score: %+5.2f", $score;
1291 # For graphs; a single number in centipawns, capped at +/- 500.
1293 my ($info, $pos, $mpv) = @_;
1295 my $invert = ($pos->{'toplay'} eq 'B');
1296 if (defined($info->{'score_mate' . $mpv})) {
1297 my $mate = $info->{'score_mate' . $mpv};
1307 if (exists($info->{'score_cp' . $mpv})) {
1308 my $score = $info->{'score_cp' . $mpv};
1312 $score = 500 if ($score > 500);
1313 $score = -500 if ($score < -500);
1322 my ($pgn, $pos) = @_;
1324 # Look for extended PGN clock tags.
1325 my $tags = $pgn->tags;
1326 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1327 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1328 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1332 # Look for TCEC-style time comments.
1333 my $moves = $pgn->moves;
1334 my $comments = $pgn->comments;
1335 my $last_black_move = int((scalar @$moves) / 2);
1336 my $last_white_move = int((1 + scalar @$moves) / 2);
1338 my $black_key = $last_black_move . "b";
1339 my $white_key = $last_white_move . "w";
1341 if (exists($comments->{$white_key}) &&
1342 exists($comments->{$black_key}) &&
1343 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1344 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1345 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1346 $pos->{'white_clock'} = hms_to_sec($1);
1347 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1348 $pos->{'black_clock'} = hms_to_sec($1);
1352 delete $pos->{'white_clock'};
1353 delete $pos->{'black_clock'};
1358 return undef if (!defined($hms));
1359 $hms =~ /(\d+):(\d+):(\d+)/;
1360 return $1 * 3600 + $2 * 60 + $3;
1363 sub find_clock_start {
1364 my ($pos, $prev_pos) = @_;
1366 # If the game is over, the clock is stopped.
1367 if (exists($pos->{'result'}) &&
1368 ($pos->{'result'} eq '1-0' ||
1369 $pos->{'result'} eq '1/2-1/2' ||
1370 $pos->{'result'} eq '0-1')) {
1374 # When we don't have any moves, we assume the clock hasn't started yet.
1375 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1376 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1377 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1382 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1383 # The history is needed for id_for_pos.
1384 if (!exists($pos->{'history'})) {
1388 my $id = id_for_pos($pos);
1389 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);
1390 if (defined($clock_info)) {
1391 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1392 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1393 if ($pos->{'toplay'} eq 'W') {
1394 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1396 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1401 # OK, we haven't seen this position before, so we assume the move
1402 # happened right now.
1404 # See if we should do our own clock management (ie., clock information
1405 # is spurious or non-existent).
1406 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1407 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1408 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1409 if (defined($prev_pos->{'white_clock_target'})) {
1410 $wc = $prev_pos->{'white_clock_target'} - time;
1412 if (defined($prev_pos->{'black_clock_target'})) {
1413 $bc = $prev_pos->{'black_clock_target'} - time;
1415 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1416 $pos->{'white_clock'} = $wc;
1417 $pos->{'black_clock'} = $bc;
1420 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1421 if (!exists($pos->{$key})) {
1422 # No clock information.
1425 my $time_left = $pos->{$key};
1426 my ($white_clock_target, $black_clock_target);
1427 if ($pos->{'toplay'} eq 'W') {
1428 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1430 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1432 local $dbh->{AutoCommit} = 0;
1433 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1434 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1435 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1439 sub schedule_tb_lookup {
1440 return if (!defined($remoteglotconf::tb_serial_key));
1441 my $pos = $pos_calculating;
1442 return if (exists($tb_cache{$pos->fen()}));
1444 # If there's more than seven pieces, there's not going to be an answer,
1446 return if ($pos->num_pieces() > 7);
1448 # Max one at a time. If it's still relevant when it returns,
1449 # schedule_tb_lookup() will be called again.
1450 return if ($tb_lookup_running);
1452 $tb_lookup_running = 1;
1453 my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1454 $remoteglotconf::tb_serial_key .
1455 '&auth.password=aquarium&type=0&fen=' .
1456 URI::Escape::uri_escape($pos->fen());
1457 print TBLOG "Downloading $url...\n";
1458 AnyEvent::HTTP::http_get($url, sub {
1459 handle_tb_lookup_return(@_, $pos, $pos->fen());
1463 sub handle_tb_lookup_return {
1464 my ($body, $header, $pos, $fen) = @_;
1465 print TBLOG "Response for [$fen]:\n";
1466 print TBLOG $header . "\n\n";
1467 print TBLOG $body . "\n\n";
1469 my $response = JSON::XS::decode_json($body);
1470 if ($response->{'ErrorCode'} != 0) {
1471 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1473 my $state = $response->{'Response'}{'StateString'};
1474 if ($state eq 'COMPLETE') {
1475 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1476 if (!defined($pgn) || !$pgn->read_game()) {
1477 warn "Error in parsing PGN\n";
1479 $pgn->quick_parse_game;
1481 my $moves = $pgn->moves;
1483 for my $move (@$moves) {
1485 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1486 push @uci_moves, $uci_move;
1489 result => $pgn->result,
1491 score => $response->{'Response'}{'Score'},
1495 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1496 # Try again in a second. Note that if we have changed
1497 # position in the meantime, we might query a completely
1498 # different position! But that's fine.
1500 die "Unknown response state " . $state;
1503 # Wait a second before we schedule another one.
1504 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1505 $tb_lookup_running = 0;
1506 schedule_tb_lookup();
1510 warn "Error in tablebase lookup: $@";
1512 # Don't try this one again, but don't block new lookups either.
1513 $tb_lookup_running = 0;
1518 my ($cmdline, $tag, $cb) = @_;
1519 return undef if (!defined($cmdline));
1520 return Engine->open($cmdline, $tag, $cb);
1523 sub col_letter_to_num {
1524 return ord(shift) - ord('a');
1527 sub row_letter_to_num {
1528 return 7 - (ord(shift) - ord('1'));
1531 sub parse_uci_move {
1533 my $from_col = col_letter_to_num(substr($move, 0, 1));
1534 my $from_row = row_letter_to_num(substr($move, 1, 1));
1535 my $to_col = col_letter_to_num(substr($move, 2, 1));
1536 my $to_row = row_letter_to_num(substr($move, 3, 1));
1537 my $promo = substr($move, 4, 1);
1538 return ($from_row, $from_col, $to_row, $to_col, $promo);
1542 my ($engine, $config) = @_;
1543 uciprint($engine, "setoption name UCI_AnalyseMode value true");
1544 uciprint($engine, "setoption name Analysis Contempt value Off");
1545 if (exists($config->{'Threads'})) { # Threads first, because clearing hash can be multithreaded then.
1546 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1548 while (my ($key, $value) = each %$config) {
1549 next if $key eq 'Threads';
1550 uciprint($engine, "setoption name $key value $value");