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 uciprint($engine, "setoption name UCI_AnalyseMode value true");
80 while (my ($key, $value) = each %remoteglotconf::engine_config) {
81 uciprint($engine, "setoption name $key value $value");
83 uciprint($engine, "ucinewgame");
85 if (defined($engine2)) {
86 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
87 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
88 uciprint($engine2, "setoption name $key value $value");
90 uciprint($engine2, "setoption name MultiPV value 500");
91 uciprint($engine2, "ucinewgame");
94 print "Chess engine ready.\n";
98 if (defined($remoteglotconf::server)) {
99 $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
100 $t->input_log(\*FICSLOG);
101 $t->open($remoteglotconf::server);
102 $t->print($remoteglotconf::nick);
103 $t->waitfor('/Press return to enter the server/');
107 $t->cmd("set shout 0");
108 $t->cmd("set seek 0");
109 $t->cmd("set style 12");
114 cb => sub { # what callback to execute
116 my $line = $t->getline(Timeout => 0, errmode => 'return');
117 return if (!defined($line));
126 if (defined($remoteglotconf::target)) {
127 if ($remoteglotconf::target =~ /^https?:/) {
128 fetch_pgn($remoteglotconf::target);
129 } elsif (defined($t)) {
130 $t->cmd("observe $remoteglotconf::target");
134 print "FICS ready.\n";
137 # Engine events have already been set up by Engine.pm.
141 my ($engine, $line, $primary) = @_;
143 return if $line =~ /(upper|lower)bound/;
145 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
146 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
148 # If we've sent a stop command, gobble up lines until we see bestmove.
149 return if ($engine->{'stopping'} && $line !~ /^bestmove/);
150 $engine->{'stopping'} = 0;
152 if ($line =~ /^info/) {
153 my (@infos) = split / /, $line;
156 parse_infos($engine, @infos);
158 if ($line =~ /^id/) {
159 my (@ids) = split / /, $line;
162 parse_ids($engine, @ids);
167 my $getting_movelist = 0;
168 my $pos_for_movelist = undef;
169 my @uci_movelist = ();
170 my @pretty_movelist = ();
174 if ($line =~ /^<12> /) {
175 handle_position(Position->new($line));
178 if ($line =~ /^Movelist for game /) {
179 my $pos = $pos_calculating;
182 @pretty_movelist = ();
183 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
184 $getting_movelist = 1;
187 if ($getting_movelist &&
188 $line =~ /^\s* \d+\. \s+ # move number
189 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
190 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
194 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
195 push @uci_movelist, $uci_move;
196 push @pretty_movelist, $1;
199 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
200 push @uci_movelist, $uci_move;
201 push @pretty_movelist, $2;
205 warn "Error when getting FICS move history: $@";
206 $getting_movelist = 0;
209 if ($getting_movelist &&
210 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
212 if (defined($pos_calculating)) {
213 if ($pos_calculating->fen() eq $pos_for_movelist->fen()) {
214 $pos_calculating->{'history'} = \@pretty_movelist;
217 $getting_movelist = 0;
219 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
220 my ($who, $msg) = ($1, $2);
222 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
224 if ($msg =~ /^fics (.*?)$/) {
225 $t->cmd("tell $who Executing '$1' on FICS.");
227 } elsif ($msg =~ /^uci (.*?)$/) {
228 $t->cmd("tell $who Sending '$1' to the engine.");
229 print { $engine->{'write'} } "$1\n";
230 } elsif ($msg =~ /^pgn (.*?)$/) {
232 $t->cmd("tell $who Starting to poll '$url'.");
234 } elsif ($msg =~ /^stoppgn$/) {
235 $t->cmd("tell $who Stopping poll.");
238 } elsif ($msg =~ /^quit$/) {
239 $t->cmd("tell $who Bye bye.");
242 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
245 #print "FICS: [$line]\n";
248 # Starts periodic fetching of PGNs from the given URL.
251 AnyEvent::HTTP::http_get($url, sub {
252 handle_pgn(@_, $url);
256 my ($last_pgn_white, $last_pgn_black);
257 my @last_pgn_uci_moves = ();
258 my $pgn_hysteresis_counter = 0;
261 my ($body, $header, $url) = @_;
263 if ($stop_pgn_fetch) {
269 my $pgn = Chess::PGN::Parse->new(undef, $body);
270 if (!defined($pgn)) {
271 warn "Error in parsing PGN from $url [body='$body']\n";
272 } elsif (!$pgn->read_game()) {
273 warn "Error in reading PGN game from $url [body='$body']\n";
274 } elsif ($body !~ /^\[/) {
275 warn "Malformed PGN from $url [body='$body']\n";
278 # Skip to the right game.
279 while (defined($remoteglotconf::pgn_filter) &&
280 !&$remoteglotconf::pgn_filter($pgn)) {
281 $pgn->read_game() or die "Out of games during filtering";
284 $pgn->parse_game({ save_comments => 'yes' });
285 my $white = $pgn->white;
286 my $black = $pgn->black;
287 $white =~ s/,.*//; # Remove first name.
288 $black =~ s/,.*//; # Remove first name.
289 my $tags = $pgn->tags();
291 if (exists($tags->{'FEN'})) {
292 $pos = Position->from_fen($tags->{'FEN'});
293 $pos->{'player_w'} = $white;
294 $pos->{'player_b'} = $black;
295 $pos->{'start_fen'} = $tags->{'FEN'};
297 $pos = Position->start_pos($white, $black);
299 my $moves = $pgn->moves;
301 my @repretty_moves = ();
302 for my $move (@$moves) {
303 my ($npos, $uci_move) = $pos->make_pretty_move($move);
304 push @uci_moves, $uci_move;
306 # Re-prettyprint the move.
307 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
308 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
309 push @repretty_moves, $pretty;
312 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
313 $pos->{'result'} = $pgn->result;
315 $pos->{'history'} = \@repretty_moves;
317 extract_clock($pgn, $pos);
319 # Sometimes, PGNs lose a move or two for a short while,
320 # or people push out new ones non-atomically.
321 # Thus, if we PGN doesn't change names but becomes
322 # shorter, we mistrust it for a few seconds.
324 if (defined($last_pgn_white) && defined($last_pgn_black) &&
325 $last_pgn_white eq $pgn->white &&
326 $last_pgn_black eq $pgn->black &&
327 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
328 if (++$pgn_hysteresis_counter < 3) {
333 $last_pgn_white = $pgn->white;
334 $last_pgn_black = $pgn->black;
335 @last_pgn_uci_moves = @uci_moves;
336 $pgn_hysteresis_counter = 0;
337 handle_position($pos);
341 warn "Error in parsing moves from $url: $@\n";
345 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
350 sub handle_position {
352 find_clock_start($pos, $pos_calculating);
354 # If we're already chewing on this and there's nothing else in the queue,
356 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
357 $pos_calculating->{'result'} = $pos->{'result'};
358 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
359 $pos_calculating->{$key} //= $pos->{$key};
364 # If we're already thinking on something, stop and wait for the engine
366 if (defined($pos_calculating)) {
367 # Store the final data we have for this position in the history,
368 # with the precise clock information we just got from the new
369 # position. (Historic positions store the clock at the end of
372 # Do not output anything new to the main analysis; that's
373 # going to be obsolete really soon.
374 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
375 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
376 delete $pos_calculating->{'white_clock_target'};
377 delete $pos_calculating->{'black_clock_target'};
380 # Ask the engine to stop; we will throw away its data until it
381 # sends us "bestmove", signaling the end of it.
382 $engine->{'stopping'} = 1;
383 uciprint($engine, "stop");
386 # It's wrong to just give the FEN (the move history is useful,
387 # and per the UCI spec, we should really have sent "ucinewgame"),
388 # but it's easier, and it works around a Stockfish repetition issue.
389 uciprint($engine, "position fen " . $pos->fen());
390 uciprint($engine, "go infinite");
391 $pos_calculating = $pos;
393 if (defined($engine2)) {
394 if (defined($pos_calculating_second_engine)) {
395 $engine2->{'stopping'} = 1;
396 uciprint($engine2, "stop");
398 uciprint($engine2, "position fen " . $pos->fen());
399 uciprint($engine2, "go infinite");
400 $pos_calculating_second_engine = $pos;
401 $engine2->{'info'} = {};
404 $engine->{'info'} = {};
407 schedule_tb_lookup();
410 # Output a command every move to note that we're
411 # still paying attention -- this is a good tradeoff,
412 # since if no move has happened in the last half
413 # hour, the analysis/relay has most likely stopped
414 # and we should stop hogging server resources.
422 my ($engine, @x) = @_;
425 my $info = $engine->{'info'};
427 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
428 for my $i (0..$#x - 1) {
429 if ($x[$i] eq 'multipv') {
435 while (scalar @x > 0) {
436 if ($x[0] eq 'multipv') {
442 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
444 my $value = shift @x;
445 $info->{$key} = $value;
448 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
449 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
452 my $value = shift @x;
453 $info->{$key . $mpv} = $value;
456 if ($x[0] eq 'score') {
459 delete $info->{'score_cp' . $mpv};
460 delete $info->{'score_mate' . $mpv};
462 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
465 $info->{'score_cp' . $mpv} = shift @x;
466 } elsif ($x[0] eq 'mate') {
468 $info->{'score_mate' . $mpv} = shift @x;
476 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
479 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
483 #print "unknown info '$x[0]', trying to recover...\n";
485 die "Unknown info '" . join(',', @x) . "'";
491 my ($engine, @x) = @_;
493 while (scalar @x > 0) {
494 if ($x[0] eq 'name') {
495 my $value = join(' ', @x);
496 $engine->{'id'}{'author'} = $value;
505 sub prettyprint_pv_no_cache {
506 my ($board, @pvs) = @_;
508 if (scalar @pvs == 0 || !defined($pvs[0])) {
513 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
514 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
515 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
519 my ($pos, @pvs) = @_;
521 my $cachekey = join('', @pvs);
522 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
523 return @{$pos->{'prettyprint_cache'}{$cachekey}};
525 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
526 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
531 my %tbprobe_cache = ();
533 sub complete_using_tbprobe {
534 my ($pos, $info, $mpv) = @_;
536 # We need Fathom installed to do standalone TB probes.
537 return if (!defined($remoteglotconf::fathom_cmdline));
539 # If we already have a mate, don't bother; in some cases, it would even be
540 # better than a tablebase score.
541 return if defined($info->{'score_mate' . $mpv});
543 # If we have a draw or near-draw score, there's also not much interesting
544 # we could add from a tablebase. We only really want mates.
545 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
547 # Run through the PV until we are at a 6-man position.
548 # TODO: We could in theory only have 5-man data.
549 my @pv = @{$info->{'pv' . $mpv}};
550 my $key = $pos->fen() . " " . join('', @pv);
552 if (exists($tbprobe_cache{$key})) {
553 @moves = @{$tbprobe_cache{$key}};
556 # Force doing at least one move of the PV.
557 my $move = shift @pv;
559 $pos = $pos->make_move(parse_uci_move($move));
562 while ($pos->num_pieces() > 6 && $#pv > -1) {
563 my $move = shift @pv;
565 $pos = $pos->make_move(parse_uci_move($move));
568 return if ($pos->num_pieces() > 6);
570 my $fen = $pos->fen();
571 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
572 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
573 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
574 $pgn->quick_parse_game;
575 $info->{'pv' . $mpv} = \@moves;
577 # Splice the PV from the tablebase onto what we have so far.
578 for my $move (@{$pgn->moves}) {
579 last if $move eq '#';
581 ($pos, $uci_move) = $pos->make_pretty_move($move);
582 push @moves, $uci_move;
585 $tbprobe_cache{$key} = \@moves;
588 $info->{'pv' . $mpv} = \@moves;
590 my $matelen = int((1 + scalar @moves) / 2);
591 if ((scalar @moves) % 2 == 0) {
592 $info->{'score_mate' . $mpv} = -$matelen;
594 $info->{'score_mate' . $mpv} = $matelen;
601 return if (!defined($pos_calculating));
603 # Don't update too often.
604 my $age = Time::HiRes::tv_interval($latest_update);
605 if ($age < $remoteglotconf::update_max_interval) {
606 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
607 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
611 my $info = $engine->{'info'};
614 # If we have tablebase data from a previous lookup, replace the
615 # engine data with the data from the tablebase.
617 my $fen = $pos_calculating->fen();
618 if (exists($tb_cache{$fen})) {
619 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
620 delete $info->{$key . '1'};
621 delete $info->{$key};
623 $info->{'nodes'} = 0;
625 $info->{'depth'} = 0;
626 $info->{'seldepth'} = 0;
627 $info->{'tbhits'} = 0;
629 my $t = $tb_cache{$fen};
631 my $matelen = int((1 + $t->{'score'}) / 2);
632 if ($t->{'result'} eq '1/2-1/2') {
633 $info->{'score_cp'} = 0;
634 } elsif ($t->{'result'} eq '1-0') {
635 if ($pos_calculating->{'toplay'} eq 'B') {
636 $info->{'score_mate'} = -$matelen;
638 $info->{'score_mate'} = $matelen;
641 if ($pos_calculating->{'toplay'} eq 'B') {
642 $info->{'score_mate'} = $matelen;
644 $info->{'score_mate'} = -$matelen;
648 $info->{'tablebase'} = 1;
650 $info->{'tablebase'} = 0;
654 # Some programs _always_ report MultiPV, even with only one PV.
655 # In this case, we simply use that data as if MultiPV was never
658 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
659 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
660 if (exists($info->{$key . '1'})) {
661 $info->{$key} = $info->{$key . '1'};
663 delete $info->{$key};
669 # Check the PVs first. if they're invalid, just wait, as our data
670 # is most likely out of sync. This isn't a very good solution, as
671 # it can frequently miss stuff, but it's good enough for most users.
675 if (exists($info->{'pv'})) {
676 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
680 while (exists($info->{'pv' . $mpv})) {
681 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
686 $engine->{'info'} = {};
690 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
691 if (exists($info->{'pv'})) {
692 complete_using_tbprobe($pos_calculating, $info, '');
696 while (exists($info->{'pv' . $mpv})) {
697 complete_using_tbprobe($pos_calculating, $info, $mpv);
703 $latest_update = [Time::HiRes::gettimeofday];
707 my $info = $engine->{'info'};
708 my $id = $engine->{'id'};
710 my $text = 'Analysis';
711 if ($pos_calculating->{'last_move'} ne 'none') {
712 if ($pos_calculating->{'toplay'} eq 'W') {
713 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
715 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
717 if (exists($id->{'name'})) {
722 if (exists($id->{'name'})) {
723 $text .= " by $id->{'name'}:\n\n";
728 return unless (exists($pos_calculating->{'board'}));
730 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
733 while (exists($info->{'pv' . $mpv})) {
734 $text .= sprintf " PV%2u", $mpv;
735 my $score = short_score($info, $pos_calculating, $mpv);
736 $text .= " ($score)" if (defined($score));
739 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
740 if ($info->{'tbhits' . $mpv} == 1) {
741 $tbhits = ", 1 tbhit";
743 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
747 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
748 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
749 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
753 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
759 my $score = long_score($info, $pos_calculating, '');
760 $text .= " $score\n" if defined($score);
761 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
764 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
765 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
766 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
768 if (exists($info->{'seldepth'})) {
769 $text .= sprintf " (%u selective)", $info->{'seldepth'};
771 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
772 if ($info->{'tbhits'} == 1) {
773 $text .= ", one Syzygy hit";
775 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
781 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
783 my @refutation_lines = ();
784 if (defined($engine2)) {
785 for (my $mpv = 1; $mpv < 500; ++$mpv) {
786 my $info = $engine2->{'info'};
787 last if (!exists($info->{'pv' . $mpv}));
789 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
790 my $pv = $info->{'pv' . $mpv};
791 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
792 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
793 if (scalar @pretty_pv > 5) {
794 @pretty_pv = @pretty_pv[0..4];
795 push @pretty_pv, "...";
797 my $key = $pretty_move;
798 my $line = sprintf(" %-6s %6s %3s %s",
800 short_score($info, $pos_calculating_second_engine, $mpv),
801 "d" . $info->{'depth' . $mpv},
802 join(', ', @pretty_pv));
803 push @refutation_lines, [ $key, $line ];
808 if ($#refutation_lines >= 0) {
809 $text .= "Shallow search of all legal moves:\n\n";
810 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
811 $text .= $line->[1] . "\n";
816 if ($last_text ne $text) {
817 print "
\e[H
\e[2J"; # clear the screen
824 my $historic_json_only = shift;
825 my $info = $engine->{'info'};
828 $json->{'position'} = $pos_calculating->to_json_hash();
829 $json->{'engine'} = $engine->{'id'};
830 if (defined($remoteglotconf::engine_url)) {
831 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
833 if (defined($remoteglotconf::engine_details)) {
834 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
836 my @grpc_backends = ();
837 if (defined($remoteglotconf::engine_grpc_backend)) {
838 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
840 if (defined($remoteglotconf::engine2_grpc_backend)) {
841 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
843 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
844 if (defined($remoteglotconf::move_source)) {
845 $json->{'move_source'} = $remoteglotconf::move_source;
847 if (defined($remoteglotconf::move_source_url)) {
848 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
850 $json->{'score'} = score_digest($info, $pos_calculating, '');
851 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
853 $json->{'nodes'} = $info->{'nodes'};
854 $json->{'nps'} = $info->{'nps'};
855 $json->{'depth'} = $info->{'depth'};
856 $json->{'tbhits'} = $info->{'tbhits'};
857 $json->{'seldepth'} = $info->{'seldepth'};
858 $json->{'tablebase'} = $info->{'tablebase'};
859 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
861 my %refutation_lines = ();
862 my @refutation_lines = ();
863 if (defined($engine2)) {
864 for (my $mpv = 1; $mpv < 500; ++$mpv) {
865 my $info = $engine2->{'info'};
866 my $pretty_move = "";
868 last if (!exists($info->{'pv' . $mpv}));
871 complete_using_tbprobe($pos_calculating, $info, $mpv);
872 my $pv = $info->{'pv' . $mpv};
873 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
874 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
875 $refutation_lines{$pretty_move} = {
876 depth => $info->{'depth' . $mpv},
877 score => score_digest($info, $pos_calculating, $mpv),
878 move => $pretty_move,
884 $json->{'refutation_lines'} = \%refutation_lines;
886 # Piece together historic score information, to the degree we have it.
887 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
888 my %score_history = ();
890 local $dbh->{AutoCommit} = 0;
891 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
893 if (exists($pos_calculating->{'start_fen'})) {
894 $pos = Position->from_fen($pos_calculating->{'start_fen'});
896 $pos = Position->start_pos('white', 'black');
898 my $halfmove_num = 0;
899 for my $move (@{$pos_calculating->{'history'}}) {
900 my $id = id_for_pos($pos, $halfmove_num);
901 my $ref = $dbh->selectrow_hashref($q, undef, $id);
903 $score_history{$halfmove_num} = [
904 $ref->{'score_type'},
905 $ref->{'score_value'}
909 ($pos) = $pos->make_pretty_move($move);
914 # If at any point we are missing 10 consecutive moves,
915 # truncate the history there. This is so we don't get into
916 # a situation where we e.g. start analyzing at move 45,
917 # but we have analysis for 1. e4 from some completely different game
918 # and thus show a huge hole.
919 my $consecutive_missing = 0;
920 my $truncate_until = 0;
921 for (my $i = $halfmove_num; $i --> 0; ) {
922 if ($consecutive_missing >= 10) {
923 delete $score_history{$i};
926 if (exists($score_history{$i})) {
927 $consecutive_missing = 0;
929 ++$consecutive_missing;
933 $json->{'score_history'} = \%score_history;
936 # Give out a list of other games going on. (Empty is fine.)
937 # TODO: Don't bother reading our own file, the data will be stale anyway.
938 if (!$historic_json_only) {
941 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
943 while (my $ref = $q->fetchrow_hashref) {
945 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
946 my $other_game_json = JSON::XS::decode_json($other_game_contents);
948 die "Missing position" if (!exists($other_game_json->{'position'}));
949 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
950 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
954 name => "$white–$black",
955 url => $ref->{'url'},
956 hashurl => $ref->{'hash_url'},
958 if (defined($other_game_json->{'position'}{'result'})) {
959 $game->{'result'} = $other_game_json->{'position'}{'result'};
961 $game->{'score'} = $other_game_json->{'score'};
966 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
970 if (scalar @games > 0) {
971 $json->{'games'} = \@games;
975 my $json_enc = JSON::XS->new;
976 $json_enc->canonical(1);
977 my $encoded = $json_enc->encode($json);
978 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
979 (defined($last_written_json) && $last_written_json eq $encoded)) {
980 atomic_set_contents($remoteglotconf::json_output, $encoded);
981 $last_written_json = $encoded;
984 if (exists($pos_calculating->{'history'}) &&
985 defined($remoteglotconf::json_history_dir)) {
986 my $id = id_for_pos($pos_calculating);
987 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
989 # Overwrite old analysis (assuming it exists at all) if we're
990 # using a different engine, or if we've calculated deeper.
991 # nodes is used as a tiebreaker. Don't bother about Multi-PV
992 # data; it's not that important.
993 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
994 my $new_depth = $json->{'depth'} // 0;
995 my $new_nodes = $json->{'nodes'} // 0;
996 if (!defined($old_engine) ||
997 $old_engine ne $json->{'engine'}{'name'} ||
998 $new_depth > $old_depth ||
999 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1000 atomic_set_contents($filename, $encoded);
1001 if (defined($json->{'score'})) {
1002 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1003 ' ON CONFLICT (id) DO UPDATE SET ' .
1004 ' score_type=EXCLUDED.score_type, ' .
1005 ' score_value=EXCLUDED.score_value, ' .
1006 ' engine=EXCLUDED.engine, ' .
1007 ' depth=EXCLUDED.depth, ' .
1008 ' nodes=EXCLUDED.nodes',
1010 $id, $json->{'score'}[0], $json->{'score'}[1],
1011 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1017 sub atomic_set_contents {
1018 my ($filename, $contents) = @_;
1020 open my $fh, ">", $filename . ".tmp"
1022 print $fh $contents;
1024 rename($filename . ".tmp", $filename);
1028 my ($pos, $halfmove_num) = @_;
1030 $halfmove_num //= scalar @{$pos->{'history'}};
1031 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1032 return "move$halfmove_num-$fen";
1035 sub get_json_analysis_stats {
1037 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1038 if (defined($ref)) {
1039 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1046 my ($engine, $msg) = @_;
1047 $engine->print($msg);
1048 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1052 my ($info, $pos, $mpv) = @_;
1054 my $invert = ($pos->{'toplay'} eq 'B');
1055 if (defined($info->{'score_mate' . $mpv})) {
1057 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1059 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1062 if (exists($info->{'score_cp' . $mpv})) {
1063 my $score = $info->{'score_cp' . $mpv} * 0.01;
1065 if ($info->{'tablebase'}) {
1074 return sprintf "%+5.2f", $score;
1081 # Sufficient for computing long_score, short_score, plot_score and
1082 # (with side-to-play information) score_sort_key.
1084 my ($info, $pos, $mpv) = @_;
1086 if (defined($info->{'score_mate' . $mpv})) {
1087 my $mate = $info->{'score_mate' . $mpv};
1088 if ($pos->{'toplay'} eq 'B') {
1091 return ['m', $mate];
1093 if (exists($info->{'score_cp' . $mpv})) {
1094 my $score = $info->{'score_cp' . $mpv};
1095 if ($pos->{'toplay'} eq 'B') {
1098 if ($score == 0 && $info->{'tablebase'}) {
1099 return ['d', undef];
1101 return ['cp', int($score)];
1110 my ($info, $pos, $mpv) = @_;
1112 if (defined($info->{'score_mate' . $mpv})) {
1113 my $mate = $info->{'score_mate' . $mpv};
1114 if ($pos->{'toplay'} eq 'B') {
1118 return sprintf "White mates in %u", $mate;
1120 return sprintf "Black mates in %u", -$mate;
1123 if (exists($info->{'score_cp' . $mpv})) {
1124 my $score = $info->{'score_cp' . $mpv} * 0.01;
1126 if ($info->{'tablebase'}) {
1127 return "Theoretical draw";
1129 return "Score: 0.00";
1132 if ($pos->{'toplay'} eq 'B') {
1135 return sprintf "Score: %+5.2f", $score;
1142 # For graphs; a single number in centipawns, capped at +/- 500.
1144 my ($info, $pos, $mpv) = @_;
1146 my $invert = ($pos->{'toplay'} eq 'B');
1147 if (defined($info->{'score_mate' . $mpv})) {
1148 my $mate = $info->{'score_mate' . $mpv};
1158 if (exists($info->{'score_cp' . $mpv})) {
1159 my $score = $info->{'score_cp' . $mpv};
1163 $score = 500 if ($score > 500);
1164 $score = -500 if ($score < -500);
1172 my %book_cache = ();
1174 my ($fen, $board, $toplay) = @_;
1176 if (exists($book_cache{$fen})) {
1177 return $book_cache{$fen};
1180 my $ret = `./booklook $fen`;
1181 return "" if ($ret =~ /Not found/ || $ret eq '');
1185 for my $m (split /\n/, $ret) {
1186 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1190 $pmove = '(current)';
1192 ($pmove) = prettyprint_pv_no_cache($board, $move);
1193 $pmove .= $annotation;
1197 if ($toplay eq 'W') {
1198 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1200 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1202 my $n = $win + $draw + $lose;
1208 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1211 push @moves, [ $pmove, $n, $percent, $rating ];
1214 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1216 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1217 for my $m (@moves) {
1218 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1225 my ($pgn, $pos) = @_;
1227 # Look for extended PGN clock tags.
1228 my $tags = $pgn->tags;
1229 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1230 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1231 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1235 # Look for TCEC-style time comments.
1236 my $moves = $pgn->moves;
1237 my $comments = $pgn->comments;
1238 my $last_black_move = int((scalar @$moves) / 2);
1239 my $last_white_move = int((1 + scalar @$moves) / 2);
1241 my $black_key = $last_black_move . "b";
1242 my $white_key = $last_white_move . "w";
1244 if (exists($comments->{$white_key}) &&
1245 exists($comments->{$black_key}) &&
1246 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1247 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1248 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1249 $pos->{'white_clock'} = hms_to_sec($1);
1250 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1251 $pos->{'black_clock'} = hms_to_sec($1);
1255 delete $pos->{'white_clock'};
1256 delete $pos->{'black_clock'};
1261 return undef if (!defined($hms));
1262 $hms =~ /(\d+):(\d+):(\d+)/;
1263 return $1 * 3600 + $2 * 60 + $3;
1266 sub find_clock_start {
1267 my ($pos, $prev_pos) = @_;
1269 # If the game is over, the clock is stopped.
1270 if (exists($pos->{'result'}) &&
1271 ($pos->{'result'} eq '1-0' ||
1272 $pos->{'result'} eq '1/2-1/2' ||
1273 $pos->{'result'} eq '0-1')) {
1277 # When we don't have any moves, we assume the clock hasn't started yet.
1278 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1279 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1280 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1285 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1286 # The history is needed for id_for_pos.
1287 if (!exists($pos->{'history'})) {
1291 my $id = id_for_pos($pos);
1292 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);
1293 if (defined($clock_info)) {
1294 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1295 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1296 if ($pos->{'toplay'} eq 'W') {
1297 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1299 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1304 # OK, we haven't seen this position before, so we assume the move
1305 # happened right now.
1307 # See if we should do our own clock management (ie., clock information
1308 # is spurious or non-existent).
1309 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1310 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1311 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1312 if (defined($prev_pos->{'white_clock_target'})) {
1313 $wc = $prev_pos->{'white_clock_target'} - time;
1315 if (defined($prev_pos->{'black_clock_target'})) {
1316 $bc = $prev_pos->{'black_clock_target'} - time;
1318 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1319 $pos->{'white_clock'} = $wc;
1320 $pos->{'black_clock'} = $bc;
1323 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1324 if (!exists($pos->{$key})) {
1325 # No clock information.
1328 my $time_left = $pos->{$key};
1329 my ($white_clock_target, $black_clock_target);
1330 if ($pos->{'toplay'} eq 'W') {
1331 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1333 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1335 local $dbh->{AutoCommit} = 0;
1336 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1337 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1338 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1342 sub schedule_tb_lookup {
1343 return if (!defined($remoteglotconf::tb_serial_key));
1344 my $pos = $pos_calculating;
1345 return if (exists($tb_cache{$pos->fen()}));
1347 # If there's more than seven pieces, there's not going to be an answer,
1349 return if ($pos->num_pieces() > 7);
1351 # Max one at a time. If it's still relevant when it returns,
1352 # schedule_tb_lookup() will be called again.
1353 return if ($tb_lookup_running);
1355 $tb_lookup_running = 1;
1356 my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1357 $remoteglotconf::tb_serial_key .
1358 '&auth.password=aquarium&type=0&fen=' .
1359 URI::Escape::uri_escape($pos->fen());
1360 print TBLOG "Downloading $url...\n";
1361 AnyEvent::HTTP::http_get($url, sub {
1362 handle_tb_lookup_return(@_, $pos, $pos->fen());
1366 sub handle_tb_lookup_return {
1367 my ($body, $header, $pos, $fen) = @_;
1368 print TBLOG "Response for [$fen]:\n";
1369 print TBLOG $header . "\n\n";
1370 print TBLOG $body . "\n\n";
1372 my $response = JSON::XS::decode_json($body);
1373 if ($response->{'ErrorCode'} != 0) {
1374 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1376 my $state = $response->{'Response'}{'StateString'};
1377 if ($state eq 'COMPLETE') {
1378 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1379 if (!defined($pgn) || !$pgn->read_game()) {
1380 warn "Error in parsing PGN\n";
1382 $pgn->quick_parse_game;
1384 my $moves = $pgn->moves;
1386 for my $move (@$moves) {
1388 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1389 push @uci_moves, $uci_move;
1392 result => $pgn->result,
1394 score => $response->{'Response'}{'Score'},
1398 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1399 # Try again in a second. Note that if we have changed
1400 # position in the meantime, we might query a completely
1401 # different position! But that's fine.
1403 die "Unknown response state " . $state;
1406 # Wait a second before we schedule another one.
1407 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1408 $tb_lookup_running = 0;
1409 schedule_tb_lookup();
1413 warn "Error in tablebase lookup: $@";
1415 # Don't try this one again, but don't block new lookups either.
1416 $tb_lookup_running = 0;
1421 my ($cmdline, $tag, $cb) = @_;
1422 return undef if (!defined($cmdline));
1423 return Engine->open($cmdline, $tag, $cb);
1426 sub col_letter_to_num {
1427 return ord(shift) - ord('a');
1430 sub row_letter_to_num {
1431 return 7 - (ord(shift) - ord('1'));
1434 sub parse_uci_move {
1436 my $from_col = col_letter_to_num(substr($move, 0, 1));
1437 my $from_row = row_letter_to_num(substr($move, 1, 1));
1438 my $to_col = col_letter_to_num(substr($move, 2, 1));
1439 my $to_row = row_letter_to_num(substr($move, 3, 1));
1440 my $promo = substr($move, 4, 1);
1441 return ($from_row, $from_col, $to_row, $to_col, $promo);