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 $pos = Position->start_pos($white, $black);
290 my $moves = $pgn->moves;
292 my @repretty_moves = ();
293 for my $move (@$moves) {
294 my ($npos, $uci_move) = $pos->make_pretty_move($move);
295 push @uci_moves, $uci_move;
297 # Re-prettyprint the move.
298 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
299 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
300 push @repretty_moves, $pretty;
303 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
304 $pos->{'result'} = $pgn->result;
306 $pos->{'history'} = \@repretty_moves;
308 extract_clock($pgn, $pos);
310 # Sometimes, PGNs lose a move or two for a short while,
311 # or people push out new ones non-atomically.
312 # Thus, if we PGN doesn't change names but becomes
313 # shorter, we mistrust it for a few seconds.
315 if (defined($last_pgn_white) && defined($last_pgn_black) &&
316 $last_pgn_white eq $pgn->white &&
317 $last_pgn_black eq $pgn->black &&
318 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
319 if (++$pgn_hysteresis_counter < 3) {
324 $last_pgn_white = $pgn->white;
325 $last_pgn_black = $pgn->black;
326 @last_pgn_uci_moves = @uci_moves;
327 $pgn_hysteresis_counter = 0;
328 handle_position($pos);
332 warn "Error in parsing moves from $url: $@\n";
336 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
341 sub handle_position {
343 find_clock_start($pos, $pos_calculating);
345 # If we're already chewing on this and there's nothing else in the queue,
347 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
348 $pos_calculating->{'result'} = $pos->{'result'};
349 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
350 $pos_calculating->{$key} //= $pos->{$key};
355 # If we're already thinking on something, stop and wait for the engine
357 if (defined($pos_calculating)) {
358 # Store the final data we have for this position in the history,
359 # with the precise clock information we just got from the new
360 # position. (Historic positions store the clock at the end of
363 # Do not output anything new to the main analysis; that's
364 # going to be obsolete really soon.
365 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
366 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
367 delete $pos_calculating->{'white_clock_target'};
368 delete $pos_calculating->{'black_clock_target'};
371 # Ask the engine to stop; we will throw away its data until it
372 # sends us "bestmove", signaling the end of it.
373 $engine->{'stopping'} = 1;
374 uciprint($engine, "stop");
377 # It's wrong to just give the FEN (the move history is useful,
378 # and per the UCI spec, we should really have sent "ucinewgame"),
379 # but it's easier, and it works around a Stockfish repetition issue.
380 uciprint($engine, "position fen " . $pos->fen());
381 uciprint($engine, "go infinite");
382 $pos_calculating = $pos;
384 if (defined($engine2)) {
385 if (defined($pos_calculating_second_engine)) {
386 $engine2->{'stopping'} = 1;
387 uciprint($engine2, "stop");
389 uciprint($engine2, "position fen " . $pos->fen());
390 uciprint($engine2, "go infinite");
391 $pos_calculating_second_engine = $pos;
392 $engine2->{'info'} = {};
395 $engine->{'info'} = {};
398 schedule_tb_lookup();
401 # Output a command every move to note that we're
402 # still paying attention -- this is a good tradeoff,
403 # since if no move has happened in the last half
404 # hour, the analysis/relay has most likely stopped
405 # and we should stop hogging server resources.
413 my ($engine, @x) = @_;
416 my $info = $engine->{'info'};
418 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
419 for my $i (0..$#x - 1) {
420 if ($x[$i] eq 'multipv') {
426 while (scalar @x > 0) {
427 if ($x[0] eq 'multipv') {
433 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
435 my $value = shift @x;
436 $info->{$key} = $value;
439 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
440 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
443 my $value = shift @x;
444 $info->{$key . $mpv} = $value;
447 if ($x[0] eq 'score') {
450 delete $info->{'score_cp' . $mpv};
451 delete $info->{'score_mate' . $mpv};
453 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
456 $info->{'score_cp' . $mpv} = shift @x;
457 } elsif ($x[0] eq 'mate') {
459 $info->{'score_mate' . $mpv} = shift @x;
467 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
470 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
474 #print "unknown info '$x[0]', trying to recover...\n";
476 die "Unknown info '" . join(',', @x) . "'";
482 my ($engine, @x) = @_;
484 while (scalar @x > 0) {
485 if ($x[0] eq 'name') {
486 my $value = join(' ', @x);
487 $engine->{'id'}{'author'} = $value;
496 sub prettyprint_pv_no_cache {
497 my ($board, @pvs) = @_;
499 if (scalar @pvs == 0 || !defined($pvs[0])) {
504 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
505 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
506 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
510 my ($pos, @pvs) = @_;
512 my $cachekey = join('', @pvs);
513 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
514 return @{$pos->{'prettyprint_cache'}{$cachekey}};
516 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
517 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
522 my %tbprobe_cache = ();
524 sub complete_using_tbprobe {
525 my ($pos, $info, $mpv) = @_;
527 # We need Fathom installed to do standalone TB probes.
528 return if (!defined($remoteglotconf::fathom_cmdline));
530 # If we already have a mate, don't bother; in some cases, it would even be
531 # better than a tablebase score.
532 return if defined($info->{'score_mate' . $mpv});
534 # If we have a draw or near-draw score, there's also not much interesting
535 # we could add from a tablebase. We only really want mates.
536 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
538 # Run through the PV until we are at a 6-man position.
539 # TODO: We could in theory only have 5-man data.
540 my @pv = @{$info->{'pv' . $mpv}};
541 my $key = $pos->fen() . " " . join('', @pv);
543 if (exists($tbprobe_cache{$key})) {
544 @moves = @{$tbprobe_cache{$key}};
547 # Force doing at least one move of the PV.
548 my $move = shift @pv;
550 $pos = $pos->make_move(parse_uci_move($move));
553 while ($pos->num_pieces() > 6 && $#pv > -1) {
554 my $move = shift @pv;
556 $pos = $pos->make_move(parse_uci_move($move));
559 return if ($pos->num_pieces() > 6);
561 my $fen = $pos->fen();
562 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
563 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
564 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
565 $pgn->quick_parse_game;
566 $info->{'pv' . $mpv} = \@moves;
568 # Splice the PV from the tablebase onto what we have so far.
569 for my $move (@{$pgn->moves}) {
570 last if $move eq '#';
572 ($pos, $uci_move) = $pos->make_pretty_move($move);
573 push @moves, $uci_move;
576 $tbprobe_cache{$key} = \@moves;
579 $info->{'pv' . $mpv} = \@moves;
581 my $matelen = int((1 + scalar @moves) / 2);
582 if ((scalar @moves) % 2 == 0) {
583 $info->{'score_mate' . $mpv} = -$matelen;
585 $info->{'score_mate' . $mpv} = $matelen;
592 return if (!defined($pos_calculating));
594 # Don't update too often.
595 my $age = Time::HiRes::tv_interval($latest_update);
596 if ($age < $remoteglotconf::update_max_interval) {
597 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
598 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
602 my $info = $engine->{'info'};
605 # If we have tablebase data from a previous lookup, replace the
606 # engine data with the data from the tablebase.
608 my $fen = $pos_calculating->fen();
609 if (exists($tb_cache{$fen})) {
610 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
611 delete $info->{$key . '1'};
612 delete $info->{$key};
614 $info->{'nodes'} = 0;
616 $info->{'depth'} = 0;
617 $info->{'seldepth'} = 0;
618 $info->{'tbhits'} = 0;
620 my $t = $tb_cache{$fen};
622 my $matelen = int((1 + $t->{'score'}) / 2);
623 if ($t->{'result'} eq '1/2-1/2') {
624 $info->{'score_cp'} = 0;
625 } elsif ($t->{'result'} eq '1-0') {
626 if ($pos_calculating->{'toplay'} eq 'B') {
627 $info->{'score_mate'} = -$matelen;
629 $info->{'score_mate'} = $matelen;
632 if ($pos_calculating->{'toplay'} eq 'B') {
633 $info->{'score_mate'} = $matelen;
635 $info->{'score_mate'} = -$matelen;
639 $info->{'tablebase'} = 1;
641 $info->{'tablebase'} = 0;
645 # Some programs _always_ report MultiPV, even with only one PV.
646 # In this case, we simply use that data as if MultiPV was never
649 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
650 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
651 if (exists($info->{$key . '1'})) {
652 $info->{$key} = $info->{$key . '1'};
654 delete $info->{$key};
660 # Check the PVs first. if they're invalid, just wait, as our data
661 # is most likely out of sync. This isn't a very good solution, as
662 # it can frequently miss stuff, but it's good enough for most users.
666 if (exists($info->{'pv'})) {
667 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
671 while (exists($info->{'pv' . $mpv})) {
672 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
677 $engine->{'info'} = {};
681 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
682 if (exists($info->{'pv'})) {
683 complete_using_tbprobe($pos_calculating, $info, '');
687 while (exists($info->{'pv' . $mpv})) {
688 complete_using_tbprobe($pos_calculating, $info, $mpv);
694 $latest_update = [Time::HiRes::gettimeofday];
698 my $info = $engine->{'info'};
699 my $id = $engine->{'id'};
701 my $text = 'Analysis';
702 if ($pos_calculating->{'last_move'} ne 'none') {
703 if ($pos_calculating->{'toplay'} eq 'W') {
704 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
706 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
708 if (exists($id->{'name'})) {
713 if (exists($id->{'name'})) {
714 $text .= " by $id->{'name'}:\n\n";
719 return unless (exists($pos_calculating->{'board'}));
721 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
724 while (exists($info->{'pv' . $mpv})) {
725 $text .= sprintf " PV%2u", $mpv;
726 my $score = short_score($info, $pos_calculating, $mpv);
727 $text .= " ($score)" if (defined($score));
730 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
731 if ($info->{'tbhits' . $mpv} == 1) {
732 $tbhits = ", 1 tbhit";
734 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
738 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
739 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
740 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
744 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
750 my $score = long_score($info, $pos_calculating, '');
751 $text .= " $score\n" if defined($score);
752 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
755 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
756 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
757 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
759 if (exists($info->{'seldepth'})) {
760 $text .= sprintf " (%u selective)", $info->{'seldepth'};
762 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
763 if ($info->{'tbhits'} == 1) {
764 $text .= ", one Syzygy hit";
766 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
772 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
774 my @refutation_lines = ();
775 if (defined($engine2)) {
776 for (my $mpv = 1; $mpv < 500; ++$mpv) {
777 my $info = $engine2->{'info'};
778 last if (!exists($info->{'pv' . $mpv}));
780 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
781 my $pv = $info->{'pv' . $mpv};
782 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
783 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
784 if (scalar @pretty_pv > 5) {
785 @pretty_pv = @pretty_pv[0..4];
786 push @pretty_pv, "...";
788 my $key = $pretty_move;
789 my $line = sprintf(" %-6s %6s %3s %s",
791 short_score($info, $pos_calculating_second_engine, $mpv),
792 "d" . $info->{'depth' . $mpv},
793 join(', ', @pretty_pv));
794 push @refutation_lines, [ $key, $line ];
799 if ($#refutation_lines >= 0) {
800 $text .= "Shallow search of all legal moves:\n\n";
801 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
802 $text .= $line->[1] . "\n";
807 if ($last_text ne $text) {
808 print "
\e[H
\e[2J"; # clear the screen
815 my $historic_json_only = shift;
816 my $info = $engine->{'info'};
819 $json->{'position'} = $pos_calculating->to_json_hash();
820 $json->{'engine'} = $engine->{'id'};
821 if (defined($remoteglotconf::engine_url)) {
822 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
824 if (defined($remoteglotconf::engine_details)) {
825 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
827 my @grpc_backends = ();
828 if (defined($remoteglotconf::engine_grpc_backend)) {
829 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
831 if (defined($remoteglotconf::engine2_grpc_backend)) {
832 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
834 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
835 if (defined($remoteglotconf::move_source)) {
836 $json->{'move_source'} = $remoteglotconf::move_source;
838 if (defined($remoteglotconf::move_source_url)) {
839 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
841 $json->{'score'} = score_digest($info, $pos_calculating, '');
842 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
844 $json->{'nodes'} = $info->{'nodes'};
845 $json->{'nps'} = $info->{'nps'};
846 $json->{'depth'} = $info->{'depth'};
847 $json->{'tbhits'} = $info->{'tbhits'};
848 $json->{'seldepth'} = $info->{'seldepth'};
849 $json->{'tablebase'} = $info->{'tablebase'};
850 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
852 my %refutation_lines = ();
853 my @refutation_lines = ();
854 if (defined($engine2)) {
855 for (my $mpv = 1; $mpv < 500; ++$mpv) {
856 my $info = $engine2->{'info'};
857 my $pretty_move = "";
859 last if (!exists($info->{'pv' . $mpv}));
862 complete_using_tbprobe($pos_calculating, $info, $mpv);
863 my $pv = $info->{'pv' . $mpv};
864 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
865 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
866 $refutation_lines{$pretty_move} = {
867 depth => $info->{'depth' . $mpv},
868 score => score_digest($info, $pos_calculating, $mpv),
869 move => $pretty_move,
875 $json->{'refutation_lines'} = \%refutation_lines;
877 # Piece together historic score information, to the degree we have it.
878 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
879 my %score_history = ();
881 local $dbh->{AutoCommit} = 0;
882 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
883 my $pos = Position->start_pos('white', 'black');
884 my $halfmove_num = 0;
885 for my $move (@{$pos_calculating->{'history'}}) {
886 my $id = id_for_pos($pos, $halfmove_num);
887 my $ref = $dbh->selectrow_hashref($q, undef, $id);
889 $score_history{$halfmove_num} = [
890 $ref->{'score_type'},
891 $ref->{'score_value'}
895 ($pos) = $pos->make_pretty_move($move);
900 # If at any point we are missing 10 consecutive moves,
901 # truncate the history there. This is so we don't get into
902 # a situation where we e.g. start analyzing at move 45,
903 # but we have analysis for 1. e4 from some completely different game
904 # and thus show a huge hole.
905 my $consecutive_missing = 0;
906 my $truncate_until = 0;
907 for (my $i = $halfmove_num; $i --> 0; ) {
908 if ($consecutive_missing >= 10) {
909 delete $score_history{$i};
912 if (exists($score_history{$i})) {
913 $consecutive_missing = 0;
915 ++$consecutive_missing;
919 $json->{'score_history'} = \%score_history;
922 # Give out a list of other games going on. (Empty is fine.)
923 # TODO: Don't bother reading our own file, the data will be stale anyway.
924 if (!$historic_json_only) {
927 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
929 while (my $ref = $q->fetchrow_hashref) {
931 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
932 my $other_game_json = JSON::XS::decode_json($other_game_contents);
934 die "Missing position" if (!exists($other_game_json->{'position'}));
935 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
936 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
940 name => "$white–$black",
941 url => $ref->{'url'},
942 hashurl => $ref->{'hash_url'},
944 if (defined($other_game_json->{'position'}{'result'})) {
945 $game->{'result'} = $other_game_json->{'position'}{'result'};
947 $game->{'score'} = $other_game_json->{'score'};
952 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
956 if (scalar @games > 0) {
957 $json->{'games'} = \@games;
961 my $json_enc = JSON::XS->new;
962 $json_enc->canonical(1);
963 my $encoded = $json_enc->encode($json);
964 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
965 (defined($last_written_json) && $last_written_json eq $encoded)) {
966 atomic_set_contents($remoteglotconf::json_output, $encoded);
967 $last_written_json = $encoded;
970 if (exists($pos_calculating->{'history'}) &&
971 defined($remoteglotconf::json_history_dir)) {
972 my $id = id_for_pos($pos_calculating);
973 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
975 # Overwrite old analysis (assuming it exists at all) if we're
976 # using a different engine, or if we've calculated deeper.
977 # nodes is used as a tiebreaker. Don't bother about Multi-PV
978 # data; it's not that important.
979 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
980 my $new_depth = $json->{'depth'} // 0;
981 my $new_nodes = $json->{'nodes'} // 0;
982 if (!defined($old_engine) ||
983 $old_engine ne $json->{'engine'}{'name'} ||
984 $new_depth > $old_depth ||
985 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
986 atomic_set_contents($filename, $encoded);
987 if (defined($json->{'score'})) {
988 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
989 ' ON CONFLICT (id) DO UPDATE SET ' .
990 ' score_type=EXCLUDED.score_type, ' .
991 ' score_value=EXCLUDED.score_value, ' .
992 ' engine=EXCLUDED.engine, ' .
993 ' depth=EXCLUDED.depth, ' .
994 ' nodes=EXCLUDED.nodes',
996 $id, $json->{'score'}[0], $json->{'score'}[1],
997 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1003 sub atomic_set_contents {
1004 my ($filename, $contents) = @_;
1006 open my $fh, ">", $filename . ".tmp"
1008 print $fh $contents;
1010 rename($filename . ".tmp", $filename);
1014 my ($pos, $halfmove_num) = @_;
1016 $halfmove_num //= scalar @{$pos->{'history'}};
1017 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1018 return "move$halfmove_num-$fen";
1021 sub get_json_analysis_stats {
1023 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1024 if (defined($ref)) {
1025 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1032 my ($engine, $msg) = @_;
1033 $engine->print($msg);
1034 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1038 my ($info, $pos, $mpv) = @_;
1040 my $invert = ($pos->{'toplay'} eq 'B');
1041 if (defined($info->{'score_mate' . $mpv})) {
1043 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1045 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1048 if (exists($info->{'score_cp' . $mpv})) {
1049 my $score = $info->{'score_cp' . $mpv} * 0.01;
1051 if ($info->{'tablebase'}) {
1060 return sprintf "%+5.2f", $score;
1067 # Sufficient for computing long_score, short_score, plot_score and
1068 # (with side-to-play information) score_sort_key.
1070 my ($info, $pos, $mpv) = @_;
1072 if (defined($info->{'score_mate' . $mpv})) {
1073 my $mate = $info->{'score_mate' . $mpv};
1074 if ($pos->{'toplay'} eq 'B') {
1077 return ['m', $mate];
1079 if (exists($info->{'score_cp' . $mpv})) {
1080 my $score = $info->{'score_cp' . $mpv};
1081 if ($pos->{'toplay'} eq 'B') {
1084 if ($score == 0 && $info->{'tablebase'}) {
1085 return ['d', undef];
1087 return ['cp', int($score)];
1096 my ($info, $pos, $mpv) = @_;
1098 if (defined($info->{'score_mate' . $mpv})) {
1099 my $mate = $info->{'score_mate' . $mpv};
1100 if ($pos->{'toplay'} eq 'B') {
1104 return sprintf "White mates in %u", $mate;
1106 return sprintf "Black mates in %u", -$mate;
1109 if (exists($info->{'score_cp' . $mpv})) {
1110 my $score = $info->{'score_cp' . $mpv} * 0.01;
1112 if ($info->{'tablebase'}) {
1113 return "Theoretical draw";
1115 return "Score: 0.00";
1118 if ($pos->{'toplay'} eq 'B') {
1121 return sprintf "Score: %+5.2f", $score;
1128 # For graphs; a single number in centipawns, capped at +/- 500.
1130 my ($info, $pos, $mpv) = @_;
1132 my $invert = ($pos->{'toplay'} eq 'B');
1133 if (defined($info->{'score_mate' . $mpv})) {
1134 my $mate = $info->{'score_mate' . $mpv};
1144 if (exists($info->{'score_cp' . $mpv})) {
1145 my $score = $info->{'score_cp' . $mpv};
1149 $score = 500 if ($score > 500);
1150 $score = -500 if ($score < -500);
1158 my %book_cache = ();
1160 my ($fen, $board, $toplay) = @_;
1162 if (exists($book_cache{$fen})) {
1163 return $book_cache{$fen};
1166 my $ret = `./booklook $fen`;
1167 return "" if ($ret =~ /Not found/ || $ret eq '');
1171 for my $m (split /\n/, $ret) {
1172 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1176 $pmove = '(current)';
1178 ($pmove) = prettyprint_pv_no_cache($board, $move);
1179 $pmove .= $annotation;
1183 if ($toplay eq 'W') {
1184 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1186 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1188 my $n = $win + $draw + $lose;
1194 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1197 push @moves, [ $pmove, $n, $percent, $rating ];
1200 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1202 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1203 for my $m (@moves) {
1204 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1211 my ($pgn, $pos) = @_;
1213 # Look for extended PGN clock tags.
1214 my $tags = $pgn->tags;
1215 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1216 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1217 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1221 # Look for TCEC-style time comments.
1222 my $moves = $pgn->moves;
1223 my $comments = $pgn->comments;
1224 my $last_black_move = int((scalar @$moves) / 2);
1225 my $last_white_move = int((1 + scalar @$moves) / 2);
1227 my $black_key = $last_black_move . "b";
1228 my $white_key = $last_white_move . "w";
1230 if (exists($comments->{$white_key}) &&
1231 exists($comments->{$black_key}) &&
1232 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1233 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1234 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1235 $pos->{'white_clock'} = hms_to_sec($1);
1236 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1237 $pos->{'black_clock'} = hms_to_sec($1);
1241 delete $pos->{'white_clock'};
1242 delete $pos->{'black_clock'};
1247 return undef if (!defined($hms));
1248 $hms =~ /(\d+):(\d+):(\d+)/;
1249 return $1 * 3600 + $2 * 60 + $3;
1252 sub find_clock_start {
1253 my ($pos, $prev_pos) = @_;
1255 # If the game is over, the clock is stopped.
1256 if (exists($pos->{'result'}) &&
1257 ($pos->{'result'} eq '1-0' ||
1258 $pos->{'result'} eq '1/2-1/2' ||
1259 $pos->{'result'} eq '0-1')) {
1263 # When we don't have any moves, we assume the clock hasn't started yet.
1264 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1265 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1266 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1271 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1272 # The history is needed for id_for_pos.
1273 if (!exists($pos->{'history'})) {
1277 my $id = id_for_pos($pos);
1278 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);
1279 if (defined($clock_info)) {
1280 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1281 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1282 if ($pos->{'toplay'} eq 'W') {
1283 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1285 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1290 # OK, we haven't seen this position before, so we assume the move
1291 # happened right now.
1293 # See if we should do our own clock management (ie., clock information
1294 # is spurious or non-existent).
1295 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1296 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1297 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1298 if (defined($prev_pos->{'white_clock_target'})) {
1299 $wc = $prev_pos->{'white_clock_target'} - time;
1301 if (defined($prev_pos->{'black_clock_target'})) {
1302 $bc = $prev_pos->{'black_clock_target'} - time;
1304 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1305 $pos->{'white_clock'} = $wc;
1306 $pos->{'black_clock'} = $bc;
1309 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1310 if (!exists($pos->{$key})) {
1311 # No clock information.
1314 my $time_left = $pos->{$key};
1315 my ($white_clock_target, $black_clock_target);
1316 if ($pos->{'toplay'} eq 'W') {
1317 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1319 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1321 local $dbh->{AutoCommit} = 0;
1322 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1323 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1324 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1328 sub schedule_tb_lookup {
1329 return if (!defined($remoteglotconf::tb_serial_key));
1330 my $pos = $pos_calculating;
1331 return if (exists($tb_cache{$pos->fen()}));
1333 # If there's more than seven pieces, there's not going to be an answer,
1335 return if ($pos->num_pieces() > 7);
1337 # Max one at a time. If it's still relevant when it returns,
1338 # schedule_tb_lookup() will be called again.
1339 return if ($tb_lookup_running);
1341 $tb_lookup_running = 1;
1342 my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1343 $remoteglotconf::tb_serial_key .
1344 '&auth.password=aquarium&type=0&fen=' .
1345 URI::Escape::uri_escape($pos->fen());
1346 print TBLOG "Downloading $url...\n";
1347 AnyEvent::HTTP::http_get($url, sub {
1348 handle_tb_lookup_return(@_, $pos, $pos->fen());
1352 sub handle_tb_lookup_return {
1353 my ($body, $header, $pos, $fen) = @_;
1354 print TBLOG "Response for [$fen]:\n";
1355 print TBLOG $header . "\n\n";
1356 print TBLOG $body . "\n\n";
1358 my $response = JSON::XS::decode_json($body);
1359 if ($response->{'ErrorCode'} != 0) {
1360 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1362 my $state = $response->{'Response'}{'StateString'};
1363 if ($state eq 'COMPLETE') {
1364 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1365 if (!defined($pgn) || !$pgn->read_game()) {
1366 warn "Error in parsing PGN\n";
1368 $pgn->quick_parse_game;
1370 my $moves = $pgn->moves;
1372 for my $move (@$moves) {
1374 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1375 push @uci_moves, $uci_move;
1378 result => $pgn->result,
1380 score => $response->{'Response'}{'Score'},
1384 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1385 # Try again in a second. Note that if we have changed
1386 # position in the meantime, we might query a completely
1387 # different position! But that's fine.
1389 die "Unknown response state " . $state;
1392 # Wait a second before we schedule another one.
1393 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1394 $tb_lookup_running = 0;
1395 schedule_tb_lookup();
1399 warn "Error in tablebase lookup: $@";
1401 # Don't try this one again, but don't block new lookups either.
1402 $tb_lookup_running = 0;
1407 my ($cmdline, $tag, $cb) = @_;
1408 return undef if (!defined($cmdline));
1409 return Engine->open($cmdline, $tag, $cb);
1412 sub col_letter_to_num {
1413 return ord(shift) - ord('a');
1416 sub row_letter_to_num {
1417 return 7 - (ord(shift) - ord('1'));
1420 sub parse_uci_move {
1422 my $from_col = col_letter_to_num(substr($move, 0, 1));
1423 my $from_row = row_letter_to_num(substr($move, 1, 1));
1424 my $to_col = col_letter_to_num(substr($move, 2, 1));
1425 my $to_row = row_letter_to_num(substr($move, 3, 1));
1426 my $promo = substr($move, 4, 1);
1427 return ($from_row, $from_col, $to_row, $to_col, $promo);