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";
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_waiting, $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";
97 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
98 $t->input_log(\*FICSLOG);
99 $t->open($remoteglotconf::server);
100 $t->print($remoteglotconf::nick);
101 $t->waitfor('/Press return to enter the server/');
105 $t->cmd("set shout 0");
106 $t->cmd("set seek 0");
107 $t->cmd("set style 12");
109 my $ev1 = AnyEvent->io(
112 cb => sub { # what callback to execute
114 my $line = $t->getline(Timeout => 0, errmode => 'return');
115 return if (!defined($line));
123 if (defined($remoteglotconf::target)) {
124 if ($remoteglotconf::target =~ /^http:/) {
125 fetch_pgn($remoteglotconf::target);
127 $t->cmd("observe $remoteglotconf::target");
130 print "FICS ready.\n";
132 # Engine events have already been set up by Engine.pm.
136 my ($engine, $line, $primary) = @_;
138 return if $line =~ /(upper|lower)bound/;
140 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
141 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
142 if ($line =~ /^info/) {
143 my (@infos) = split / /, $line;
146 parse_infos($engine, @infos);
148 if ($line =~ /^id/) {
149 my (@ids) = split / /, $line;
152 parse_ids($engine, @ids);
154 if ($line =~ /^bestmove/) {
156 return if (!$remoteglotconf::uci_assume_full_compliance);
157 if (defined($pos_waiting)) {
158 uciprint($engine, "position fen " . $pos_waiting->fen());
159 uciprint($engine, "go infinite");
161 $pos_calculating = $pos_waiting;
162 $pos_waiting = undef;
165 $engine2->{'info'} = {};
166 my $pos = $pos_waiting // $pos_calculating;
167 uciprint($engine2, "position fen " . $pos->fen());
168 uciprint($engine2, "go infinite");
169 $pos_calculating_second_engine = $pos;
175 my $getting_movelist = 0;
176 my $pos_for_movelist = undef;
177 my @uci_movelist = ();
178 my @pretty_movelist = ();
182 if ($line =~ /^<12> /) {
183 handle_position(Position->new($line));
186 if ($line =~ /^Movelist for game /) {
187 my $pos = $pos_waiting // $pos_calculating;
190 @pretty_movelist = ();
191 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
192 $getting_movelist = 1;
195 if ($getting_movelist &&
196 $line =~ /^\s* \d+\. \s+ # move number
197 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
198 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
202 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
203 push @uci_movelist, $uci_move;
204 push @pretty_movelist, $1;
207 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
208 push @uci_movelist, $uci_move;
209 push @pretty_movelist, $2;
213 warn "Error when getting FICS move history: $@";
214 $getting_movelist = 0;
217 if ($getting_movelist &&
218 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
220 for my $pos ($pos_waiting, $pos_calculating) {
221 next if (!defined($pos));
222 if ($pos->fen() eq $pos_for_movelist->fen()) {
223 $pos->{'history'} = \@pretty_movelist;
226 $getting_movelist = 0;
228 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
229 my ($who, $msg) = ($1, $2);
231 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
233 if ($msg =~ /^fics (.*?)$/) {
234 $t->cmd("tell $who Executing '$1' on FICS.");
236 } elsif ($msg =~ /^uci (.*?)$/) {
237 $t->cmd("tell $who Sending '$1' to the engine.");
238 print { $engine->{'write'} } "$1\n";
239 } elsif ($msg =~ /^pgn (.*?)$/) {
241 $t->cmd("tell $who Starting to poll '$url'.");
243 } elsif ($msg =~ /^stoppgn$/) {
244 $t->cmd("tell $who Stopping poll.");
247 } elsif ($msg =~ /^quit$/) {
248 $t->cmd("tell $who Bye bye.");
251 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
254 #print "FICS: [$line]\n";
257 # Starts periodic fetching of PGNs from the given URL.
260 AnyEvent::HTTP::http_get($url, sub {
261 handle_pgn(@_, $url);
265 my ($last_pgn_white, $last_pgn_black);
266 my @last_pgn_uci_moves = ();
267 my $pgn_hysteresis_counter = 0;
270 my ($body, $header, $url) = @_;
272 if ($stop_pgn_fetch) {
278 my $pgn = Chess::PGN::Parse->new(undef, $body);
279 if (!defined($pgn)) {
280 warn "Error in parsing PGN from $url [body='$body']\n";
281 } elsif (!$pgn->read_game()) {
282 warn "Error in reading PGN game from $url [body='$body']\n";
283 } elsif ($body !~ /^\[/) {
284 warn "Malformed PGN from $url [body='$body']\n";
287 # Skip to the right game.
288 while (defined($remoteglotconf::pgn_filter) &&
289 !&$remoteglotconf::pgn_filter($pgn)) {
290 $pgn->read_game() or die "Out of games during filtering";
293 $pgn->parse_game({ save_comments => 'yes' });
294 my $white = $pgn->white;
295 my $black = $pgn->black;
296 $white =~ s/,.*//; # Remove first name.
297 $black =~ s/,.*//; # Remove first name.
298 my $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 this is already in the queue, ignore it (just update the result)
355 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
356 $pos_waiting->{'result'} = $pos->{'result'};
360 # if we're already chewing on this and there's nothing else in the queue,
362 if (!defined($pos_waiting) && defined($pos_calculating) &&
363 $pos->fen() eq $pos_calculating->fen()) {
364 $pos_calculating->{'result'} = $pos->{'result'};
368 # if we're already thinking on something, stop and wait for the engine
370 if (defined($pos_calculating)) {
371 # Store the final data we have for this position in the history,
372 # with the precise clock information we just got from the new
373 # position. (Historic positions store the clock at the end of
376 # Do not output anything new to the main analysis; that's
377 # going to be obsolete really soon.
378 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
379 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
380 delete $pos_calculating->{'white_clock_target'};
381 delete $pos_calculating->{'black_clock_target'};
384 if (!defined($pos_waiting)) {
385 uciprint($engine, "stop");
387 if ($remoteglotconf::uci_assume_full_compliance) {
390 uciprint($engine, "position fen " . $pos->fen());
391 uciprint($engine, "go infinite");
392 $pos_calculating = $pos;
395 # it's wrong just to give the FEN (the move history is useful,
396 # and per the UCI spec, we should really have sent "ucinewgame"),
398 uciprint($engine, "position fen " . $pos->fen());
399 uciprint($engine, "go infinite");
400 $pos_calculating = $pos;
403 if (defined($engine2)) {
404 if (defined($pos_calculating_second_engine)) {
405 uciprint($engine2, "stop");
407 uciprint($engine2, "position fen " . $pos->fen());
408 uciprint($engine2, "go infinite");
409 $pos_calculating_second_engine = $pos;
411 $engine2->{'info'} = {};
414 $engine->{'info'} = {};
417 schedule_tb_lookup();
420 # Output a command every move to note that we're
421 # still paying attention -- this is a good tradeoff,
422 # since if no move has happened in the last half
423 # hour, the analysis/relay has most likely stopped
424 # and we should stop hogging server resources.
430 my ($engine, @x) = @_;
433 my $info = $engine->{'info'};
435 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
436 for my $i (0..$#x - 1) {
437 if ($x[$i] eq 'multipv') {
443 while (scalar @x > 0) {
444 if ($x[0] eq 'multipv') {
450 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
452 my $value = shift @x;
453 $info->{$key} = $value;
456 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
457 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
460 my $value = shift @x;
461 $info->{$key . $mpv} = $value;
464 if ($x[0] eq 'score') {
467 delete $info->{'score_cp' . $mpv};
468 delete $info->{'score_mate' . $mpv};
470 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
473 $info->{'score_cp' . $mpv} = shift @x;
474 } elsif ($x[0] eq 'mate') {
476 $info->{'score_mate' . $mpv} = shift @x;
484 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
487 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
491 #print "unknown info '$x[0]', trying to recover...\n";
493 die "Unknown info '" . join(',', @x) . "'";
499 my ($engine, @x) = @_;
501 while (scalar @x > 0) {
502 if ($x[0] eq 'name') {
503 my $value = join(' ', @x);
504 $engine->{'id'}{'author'} = $value;
513 sub prettyprint_pv_no_cache {
514 my ($board, @pvs) = @_;
516 if (scalar @pvs == 0 || !defined($pvs[0])) {
521 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
522 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
523 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
527 my ($pos, @pvs) = @_;
529 my $cachekey = join('', @pvs);
530 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
531 return @{$pos->{'prettyprint_cache'}{$cachekey}};
533 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
534 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
539 sub complete_using_tbprobe {
540 my ($pos, $info, $mpv) = @_;
542 # We need Fathom installed to do standalone TB probes.
543 return if (!defined($remoteglotconf::fathom_cmdline));
545 # If we already have a mate, don't bother; in some cases, it would even be
546 # better than a tablebase score.
547 return if defined($info->{'score_mate' . $mpv});
549 # If we have a draw or near-draw score, there's also not much interesting
550 # we could add from a tablebase. We only really want mates.
551 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
553 # Run through the PV until we are at a 6-man position.
554 # TODO: We could in theory only have 5-man data.
555 my @pv = @{$info->{'pv' . $mpv}};
556 my $key = join('', @pv);
558 if (exists($pos->{'tbprobe_cache'}{$key})) {
559 @moves = @{$pos->{'tbprobe_cache'}{$key}};
562 # Force doing at least one move of the PV.
563 my $move = shift @pv;
565 $pos = $pos->make_move(parse_uci_move($move));
568 while ($pos->num_pieces() > 6 && $#pv > -1) {
569 my $move = shift @pv;
571 $pos = $pos->make_move(parse_uci_move($move));
574 return if ($pos->num_pieces() > 6);
576 my $fen = $pos->fen();
577 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
578 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
579 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
580 $pgn->quick_parse_game;
581 $info->{'pv' . $mpv} = \@moves;
583 # Splice the PV from the tablebase onto what we have so far.
584 for my $move (@{$pgn->moves}) {
586 ($pos, $uci_move) = $pos->make_pretty_move($move);
587 push @moves, $uci_move;
590 $pos->{'tbprobe_cache'}{$key} = \@moves;
593 $info->{'pv' . $mpv} = \@moves;
595 my $matelen = int((1 + scalar @moves) / 2);
596 if ((scalar @moves) % 2 == 0) {
597 $info->{'score_mate' . $mpv} = -$matelen;
599 $info->{'score_mate' . $mpv} = $matelen;
606 return if (!defined($pos_calculating));
608 # Don't update too often.
609 my $age = Time::HiRes::tv_interval($latest_update);
610 if ($age < $remoteglotconf::update_max_interval) {
611 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
612 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
616 my $info = $engine->{'info'};
619 # If we have tablebase data from a previous lookup, replace the
620 # engine data with the data from the tablebase.
622 my $fen = $pos_calculating->fen();
623 if (exists($tb_cache{$fen})) {
624 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
625 delete $info->{$key . '1'};
626 delete $info->{$key};
628 $info->{'nodes'} = 0;
630 $info->{'depth'} = 0;
631 $info->{'seldepth'} = 0;
632 $info->{'tbhits'} = 0;
634 my $t = $tb_cache{$fen};
636 my $matelen = int((1 + $t->{'score'}) / 2);
637 if ($t->{'result'} eq '1/2-1/2') {
638 $info->{'score_cp'} = 0;
639 } elsif ($t->{'result'} eq '1-0') {
640 if ($pos_calculating->{'toplay'} eq 'B') {
641 $info->{'score_mate'} = -$matelen;
643 $info->{'score_mate'} = $matelen;
646 if ($pos_calculating->{'toplay'} eq 'B') {
647 $info->{'score_mate'} = $matelen;
649 $info->{'score_mate'} = -$matelen;
653 $info->{'tablebase'} = 1;
655 $info->{'tablebase'} = 0;
659 # Some programs _always_ report MultiPV, even with only one PV.
660 # In this case, we simply use that data as if MultiPV was never
663 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
664 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
665 if (exists($info->{$key . '1'})) {
666 $info->{$key} = $info->{$key . '1'};
668 delete $info->{$key};
674 # Check the PVs first. if they're invalid, just wait, as our data
675 # is most likely out of sync. This isn't a very good solution, as
676 # it can frequently miss stuff, but it's good enough for most users.
680 if (exists($info->{'pv'})) {
681 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
685 while (exists($info->{'pv' . $mpv})) {
686 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
691 $engine->{'info'} = {};
695 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
696 if (exists($info->{'pv'})) {
697 complete_using_tbprobe($pos_calculating, $info, '');
701 while (exists($info->{'pv' . $mpv})) {
702 complete_using_tbprobe($pos_calculating, $info, $mpv);
708 $latest_update = [Time::HiRes::gettimeofday];
712 my $info = $engine->{'info'};
713 my $id = $engine->{'id'};
715 my $text = 'Analysis';
716 if ($pos_calculating->{'last_move'} ne 'none') {
717 if ($pos_calculating->{'toplay'} eq 'W') {
718 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
720 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
722 if (exists($id->{'name'})) {
727 if (exists($id->{'name'})) {
728 $text .= " by $id->{'name'}:\n\n";
733 return unless (exists($pos_calculating->{'board'}));
735 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
738 while (exists($info->{'pv' . $mpv})) {
739 $text .= sprintf " PV%2u", $mpv;
740 my $score = short_score($info, $pos_calculating, $mpv);
741 $text .= " ($score)" if (defined($score));
744 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
745 if ($info->{'tbhits' . $mpv} == 1) {
746 $tbhits = ", 1 tbhit";
748 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
752 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
753 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
754 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
758 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
764 my $score = long_score($info, $pos_calculating, '');
765 $text .= " $score\n" if defined($score);
766 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
769 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
770 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
771 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
773 if (exists($info->{'seldepth'})) {
774 $text .= sprintf " (%u selective)", $info->{'seldepth'};
776 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
777 if ($info->{'tbhits'} == 1) {
778 $text .= ", one Syzygy hit";
780 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
786 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
788 my @refutation_lines = ();
789 if (defined($engine2)) {
790 for (my $mpv = 1; $mpv < 500; ++$mpv) {
791 my $info = $engine2->{'info'};
792 last if (!exists($info->{'pv' . $mpv}));
794 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
795 my $pv = $info->{'pv' . $mpv};
796 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
797 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
798 if (scalar @pretty_pv > 5) {
799 @pretty_pv = @pretty_pv[0..4];
800 push @pretty_pv, "...";
802 my $key = $pretty_move;
803 my $line = sprintf(" %-6s %6s %3s %s",
805 short_score($info, $pos_calculating_second_engine, $mpv),
806 "d" . $info->{'depth' . $mpv},
807 join(', ', @pretty_pv));
808 push @refutation_lines, [ $key, $line ];
813 if ($#refutation_lines >= 0) {
814 $text .= "Shallow search of all legal moves:\n\n";
815 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
816 $text .= $line->[1] . "\n";
821 if ($last_text ne $text) {
822 print "
\e[H
\e[2J"; # clear the screen
829 my $historic_json_only = shift;
830 my $info = $engine->{'info'};
833 $json->{'position'} = $pos_calculating->to_json_hash();
834 $json->{'engine'} = $engine->{'id'};
835 if (defined($remoteglotconf::engine_url)) {
836 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
838 if (defined($remoteglotconf::engine_details)) {
839 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
841 if (defined($remoteglotconf::move_source)) {
842 $json->{'move_source'} = $remoteglotconf::move_source;
844 if (defined($remoteglotconf::move_source_url)) {
845 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
847 $json->{'score'} = score_digest($info, $pos_calculating, '');
848 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
850 $json->{'nodes'} = $info->{'nodes'};
851 $json->{'nps'} = $info->{'nps'};
852 $json->{'depth'} = $info->{'depth'};
853 $json->{'tbhits'} = $info->{'tbhits'};
854 $json->{'seldepth'} = $info->{'seldepth'};
855 $json->{'tablebase'} = $info->{'tablebase'};
856 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
858 my %refutation_lines = ();
859 my @refutation_lines = ();
860 if (defined($engine2)) {
861 for (my $mpv = 1; $mpv < 500; ++$mpv) {
862 my $info = $engine2->{'info'};
863 my $pretty_move = "";
865 last if (!exists($info->{'pv' . $mpv}));
868 complete_using_tbprobe($pos_calculating, $info, $mpv);
869 my $pv = $info->{'pv' . $mpv};
870 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
871 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
872 $refutation_lines{$pretty_move} = {
873 depth => $info->{'depth' . $mpv},
874 score => score_digest($info, $pos_calculating, $mpv),
875 move => $pretty_move,
881 $json->{'refutation_lines'} = \%refutation_lines;
883 # Piece together historic score information, to the degree we have it.
884 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
885 my %score_history = ();
887 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
888 my $pos = Position->start_pos('white', 'black');
889 my $halfmove_num = 0;
890 for my $move (@{$pos_calculating->{'history'}}) {
891 my $id = id_for_pos($pos, $halfmove_num);
892 my $ref = $dbh->selectrow_hashref($q, undef, $id);
894 $score_history{$halfmove_num} = [
895 $ref->{'score_type'},
896 $ref->{'score_value'}
900 ($pos) = $pos->make_pretty_move($move);
904 # If at any point we are missing 10 consecutive moves,
905 # truncate the history there. This is so we don't get into
906 # a situation where we e.g. start analyzing at move 45,
907 # but we have analysis for 1. e4 from some completely different game
908 # and thus show a huge hole.
909 my $consecutive_missing = 0;
910 my $truncate_until = 0;
911 for (my $i = $halfmove_num; $i --> 0; ) {
912 if ($consecutive_missing >= 10) {
913 delete $score_history{$i};
916 if (exists($score_history{$i})) {
917 $consecutive_missing = 0;
919 ++$consecutive_missing;
923 $json->{'score_history'} = \%score_history;
926 # Give out a list of other games going on. (Empty is fine.)
927 # TODO: Don't bother reading our own file, the data will be stale anyway.
928 if (!$historic_json_only) {
931 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
933 while (my $ref = $q->fetchrow_hashref) {
935 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
936 my $other_game_json = JSON::XS::decode_json($other_game_contents);
938 die "Missing position" if (!exists($other_game_json->{'position'}));
939 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
940 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
944 name => "$white–$black",
945 url => $ref->{'url'},
946 hashurl => $ref->{'hash_url'},
948 if (defined($other_game_json->{'position'}{'result'})) {
949 $game->{'result'} = $other_game_json->{'position'}{'result'};
951 $game->{'score'} = $other_game_json->{'score'};
956 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
960 if (scalar @games > 0) {
961 $json->{'games'} = \@games;
965 my $json_enc = JSON::XS->new;
966 $json_enc->canonical(1);
967 my $encoded = $json_enc->encode($json);
968 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
969 (defined($last_written_json) && $last_written_json eq $encoded)) {
970 atomic_set_contents($remoteglotconf::json_output, $encoded);
971 $last_written_json = $encoded;
974 if (exists($pos_calculating->{'history'}) &&
975 defined($remoteglotconf::json_history_dir)) {
976 my $id = id_for_pos($pos_calculating);
977 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
979 # Overwrite old analysis (assuming it exists at all) if we're
980 # using a different engine, or if we've calculated deeper.
981 # nodes is used as a tiebreaker. Don't bother about Multi-PV
982 # data; it's not that important.
983 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
984 my $new_depth = $json->{'depth'} // 0;
985 my $new_nodes = $json->{'nodes'} // 0;
986 if (!defined($old_engine) ||
987 $old_engine ne $json->{'engine'}{'name'} ||
988 $new_depth > $old_depth ||
989 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
990 atomic_set_contents($filename, $encoded);
991 if (defined($json->{'score'})) {
992 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
993 ' ON CONFLICT (id) DO UPDATE SET ' .
994 ' score_type=EXCLUDED.score_type, ' .
995 ' score_value=EXCLUDED.score_value, ' .
996 ' engine=EXCLUDED.engine, ' .
997 ' depth=EXCLUDED.depth, ' .
998 ' nodes=EXCLUDED.nodes',
1000 $id, $json->{'score'}[0], $json->{'score'}[1],
1001 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1007 sub atomic_set_contents {
1008 my ($filename, $contents) = @_;
1010 open my $fh, ">", $filename . ".tmp"
1012 print $fh $contents;
1014 rename($filename . ".tmp", $filename);
1018 my ($pos, $halfmove_num) = @_;
1020 $halfmove_num //= scalar @{$pos->{'history'}};
1021 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1022 return "move$halfmove_num-$fen";
1025 sub get_json_analysis_stats {
1027 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1028 if (defined($ref)) {
1029 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1036 my ($engine, $msg) = @_;
1037 $engine->print($msg);
1038 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1042 my ($info, $pos, $mpv) = @_;
1044 my $invert = ($pos->{'toplay'} eq 'B');
1045 if (defined($info->{'score_mate' . $mpv})) {
1047 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1049 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1052 if (exists($info->{'score_cp' . $mpv})) {
1053 my $score = $info->{'score_cp' . $mpv} * 0.01;
1055 if ($info->{'tablebase'}) {
1064 return sprintf "%+5.2f", $score;
1071 # Sufficient for computing long_score, short_score, plot_score and
1072 # (with side-to-play information) score_sort_key.
1074 my ($info, $pos, $mpv) = @_;
1076 if (defined($info->{'score_mate' . $mpv})) {
1077 my $mate = $info->{'score_mate' . $mpv};
1078 if ($pos->{'toplay'} eq 'B') {
1081 return ['m', $mate];
1083 if (exists($info->{'score_cp' . $mpv})) {
1084 my $score = $info->{'score_cp' . $mpv};
1085 if ($pos->{'toplay'} eq 'B') {
1088 if ($score == 0 && $info->{'tablebase'}) {
1089 return ['d', undef];
1091 return ['cp', $score];
1100 my ($info, $pos, $mpv) = @_;
1102 if (defined($info->{'score_mate' . $mpv})) {
1103 my $mate = $info->{'score_mate' . $mpv};
1104 if ($pos->{'toplay'} eq 'B') {
1108 return sprintf "White mates in %u", $mate;
1110 return sprintf "Black mates in %u", -$mate;
1113 if (exists($info->{'score_cp' . $mpv})) {
1114 my $score = $info->{'score_cp' . $mpv} * 0.01;
1116 if ($info->{'tablebase'}) {
1117 return "Theoretical draw";
1119 return "Score: 0.00";
1122 if ($pos->{'toplay'} eq 'B') {
1125 return sprintf "Score: %+5.2f", $score;
1132 # For graphs; a single number in centipawns, capped at +/- 500.
1134 my ($info, $pos, $mpv) = @_;
1136 my $invert = ($pos->{'toplay'} eq 'B');
1137 if (defined($info->{'score_mate' . $mpv})) {
1138 my $mate = $info->{'score_mate' . $mpv};
1148 if (exists($info->{'score_cp' . $mpv})) {
1149 my $score = $info->{'score_cp' . $mpv};
1153 $score = 500 if ($score > 500);
1154 $score = -500 if ($score < -500);
1162 my %book_cache = ();
1164 my ($fen, $board, $toplay) = @_;
1166 if (exists($book_cache{$fen})) {
1167 return $book_cache{$fen};
1170 my $ret = `./booklook $fen`;
1171 return "" if ($ret =~ /Not found/ || $ret eq '');
1175 for my $m (split /\n/, $ret) {
1176 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1180 $pmove = '(current)';
1182 ($pmove) = prettyprint_pv_no_cache($board, $move);
1183 $pmove .= $annotation;
1187 if ($toplay eq 'W') {
1188 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1190 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1192 my $n = $win + $draw + $lose;
1198 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1201 push @moves, [ $pmove, $n, $percent, $rating ];
1204 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1206 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1207 for my $m (@moves) {
1208 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1215 my ($pgn, $pos) = @_;
1217 # Look for extended PGN clock tags.
1218 my $tags = $pgn->tags;
1219 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1220 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1221 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1225 # Look for TCEC-style time comments.
1226 my $moves = $pgn->moves;
1227 my $comments = $pgn->comments;
1228 my $last_black_move = int((scalar @$moves) / 2);
1229 my $last_white_move = int((1 + scalar @$moves) / 2);
1231 my $black_key = $last_black_move . "b";
1232 my $white_key = $last_white_move . "w";
1234 if (exists($comments->{$white_key}) &&
1235 exists($comments->{$black_key}) &&
1236 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1237 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1238 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1239 $pos->{'white_clock'} = hms_to_sec($1);
1240 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1241 $pos->{'black_clock'} = hms_to_sec($1);
1245 delete $pos->{'white_clock'};
1246 delete $pos->{'black_clock'};
1251 return undef if (!defined($hms));
1252 $hms =~ /(\d+):(\d+):(\d+)/;
1253 return $1 * 3600 + $2 * 60 + $3;
1256 sub find_clock_start {
1257 my ($pos, $prev_pos) = @_;
1259 # If the game is over, the clock is stopped.
1260 if (exists($pos->{'result'}) &&
1261 ($pos->{'result'} eq '1-0' ||
1262 $pos->{'result'} eq '1/2-1/2' ||
1263 $pos->{'result'} eq '0-1')) {
1267 # When we don't have any moves, we assume the clock hasn't started yet.
1268 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1269 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1270 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1275 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1276 # The history is needed for id_for_pos.
1277 if (!exists($pos->{'history'})) {
1281 my $id = id_for_pos($pos);
1282 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1283 if (defined($clock_info)) {
1284 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1285 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1286 if ($pos->{'toplay'} eq 'W') {
1287 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1289 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1294 # OK, we haven't seen this position before, so we assume the move
1295 # happened right now.
1297 # See if we should do our own clock management (ie., clock information
1298 # is spurious or non-existent).
1299 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1300 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1301 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1302 if (defined($prev_pos->{'white_clock_target'})) {
1303 $wc = $prev_pos->{'white_clock_target'} - time;
1305 if (defined($prev_pos->{'black_clock_target'})) {
1306 $bc = $prev_pos->{'black_clock_target'} - time;
1308 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1309 $pos->{'white_clock'} = $wc;
1310 $pos->{'black_clock'} = $bc;
1313 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1314 if (!exists($pos->{$key})) {
1315 # No clock information.
1318 my $time_left = $pos->{$key};
1319 my ($white_clock_target, $black_clock_target);
1320 if ($pos->{'toplay'} eq 'W') {
1321 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1323 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1325 local $dbh->{AutoCommit} = 0;
1326 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1327 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1328 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1332 sub schedule_tb_lookup {
1333 return if (!defined($remoteglotconf::tb_serial_key));
1334 my $pos = $pos_waiting // $pos_calculating;
1335 return if (exists($tb_cache{$pos->fen()}));
1337 # If there's more than seven pieces, there's not going to be an answer,
1339 return if ($pos->num_pieces() > 7);
1341 # Max one at a time. If it's still relevant when it returns,
1342 # schedule_tb_lookup() will be called again.
1343 return if ($tb_lookup_running);
1345 $tb_lookup_running = 1;
1346 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1347 $remoteglotconf::tb_serial_key .
1348 '&auth.password=aquarium&type=0&fen=' .
1349 URI::Escape::uri_escape($pos->fen());
1350 print TBLOG "Downloading $url...\n";
1351 AnyEvent::HTTP::http_get($url, sub {
1352 handle_tb_lookup_return(@_, $pos, $pos->fen());
1356 sub handle_tb_lookup_return {
1357 my ($body, $header, $pos, $fen) = @_;
1358 print TBLOG "Response for [$fen]:\n";
1359 print TBLOG $header . "\n\n";
1360 print TBLOG $body . "\n\n";
1362 my $response = JSON::XS::decode_json($body);
1363 if ($response->{'ErrorCode'} != 0) {
1364 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1366 my $state = $response->{'Response'}{'StateString'};
1367 if ($state eq 'COMPLETE') {
1368 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1369 if (!defined($pgn) || !$pgn->read_game()) {
1370 warn "Error in parsing PGN\n";
1372 $pgn->quick_parse_game;
1374 my $moves = $pgn->moves;
1376 for my $move (@$moves) {
1378 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1379 push @uci_moves, $uci_move;
1382 result => $pgn->result,
1384 score => $response->{'Response'}{'Score'},
1388 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1389 # Try again in a second. Note that if we have changed
1390 # position in the meantime, we might query a completely
1391 # different position! But that's fine.
1393 die "Unknown response state " . $state;
1396 # Wait a second before we schedule another one.
1397 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1398 $tb_lookup_running = 0;
1399 schedule_tb_lookup();
1403 warn "Error in tablebase lookup: $@";
1405 # Don't try this one again, but don't block new lookups either.
1406 $tb_lookup_running = 0;
1411 my ($cmdline, $tag, $cb) = @_;
1412 return undef if (!defined($cmdline));
1413 return Engine->open($cmdline, $tag, $cb);
1416 sub col_letter_to_num {
1417 return ord(shift) - ord('a');
1420 sub row_letter_to_num {
1421 return 7 - (ord(shift) - ord('1'));
1424 sub parse_uci_move {
1426 my $from_col = col_letter_to_num(substr($move, 0, 1));
1427 my $from_row = row_letter_to_num(substr($move, 1, 1));
1428 my $to_col = col_letter_to_num(substr($move, 2, 1));
1429 my $to_row = row_letter_to_num(substr($move, 3, 1));
1430 my $promo = substr($move, 4, 1);
1431 return ($from_row, $from_col, $to_row, $to_col, $promo);