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'};
352 # If we're already thinking on something, stop and wait for the engine
354 if (defined($pos_calculating)) {
355 # Store the final data we have for this position in the history,
356 # with the precise clock information we just got from the new
357 # position. (Historic positions store the clock at the end of
360 # Do not output anything new to the main analysis; that's
361 # going to be obsolete really soon.
362 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
363 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
364 delete $pos_calculating->{'white_clock_target'};
365 delete $pos_calculating->{'black_clock_target'};
368 # Ask the engine to stop; we will throw away its data until it
369 # sends us "bestmove", signaling the end of it.
370 $engine->{'stopping'} = 1;
371 uciprint($engine, "stop");
374 # It's wrong to just give the FEN (the move history is useful,
375 # and per the UCI spec, we should really have sent "ucinewgame"),
376 # but it's easier, and it works around a Stockfish repetition issue.
377 uciprint($engine, "position fen " . $pos->fen());
378 uciprint($engine, "go infinite");
379 $pos_calculating = $pos;
381 if (defined($engine2)) {
382 if (defined($pos_calculating_second_engine)) {
383 $engine2->{'stopping'} = 1;
384 uciprint($engine2, "stop");
386 uciprint($engine2, "position fen " . $pos->fen());
387 uciprint($engine2, "go infinite");
388 $pos_calculating_second_engine = $pos;
389 $engine2->{'info'} = {};
392 $engine->{'info'} = {};
395 schedule_tb_lookup();
398 # Output a command every move to note that we're
399 # still paying attention -- this is a good tradeoff,
400 # since if no move has happened in the last half
401 # hour, the analysis/relay has most likely stopped
402 # and we should stop hogging server resources.
410 my ($engine, @x) = @_;
413 my $info = $engine->{'info'};
415 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
416 for my $i (0..$#x - 1) {
417 if ($x[$i] eq 'multipv') {
423 while (scalar @x > 0) {
424 if ($x[0] eq 'multipv') {
430 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
432 my $value = shift @x;
433 $info->{$key} = $value;
436 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
437 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
440 my $value = shift @x;
441 $info->{$key . $mpv} = $value;
444 if ($x[0] eq 'score') {
447 delete $info->{'score_cp' . $mpv};
448 delete $info->{'score_mate' . $mpv};
450 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
453 $info->{'score_cp' . $mpv} = shift @x;
454 } elsif ($x[0] eq 'mate') {
456 $info->{'score_mate' . $mpv} = shift @x;
464 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
467 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
471 #print "unknown info '$x[0]', trying to recover...\n";
473 die "Unknown info '" . join(',', @x) . "'";
479 my ($engine, @x) = @_;
481 while (scalar @x > 0) {
482 if ($x[0] eq 'name') {
483 my $value = join(' ', @x);
484 $engine->{'id'}{'author'} = $value;
493 sub prettyprint_pv_no_cache {
494 my ($board, @pvs) = @_;
496 if (scalar @pvs == 0 || !defined($pvs[0])) {
501 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
502 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
503 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
507 my ($pos, @pvs) = @_;
509 my $cachekey = join('', @pvs);
510 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
511 return @{$pos->{'prettyprint_cache'}{$cachekey}};
513 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
514 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
519 my %tbprobe_cache = ();
521 sub complete_using_tbprobe {
522 my ($pos, $info, $mpv) = @_;
524 # We need Fathom installed to do standalone TB probes.
525 return if (!defined($remoteglotconf::fathom_cmdline));
527 # If we already have a mate, don't bother; in some cases, it would even be
528 # better than a tablebase score.
529 return if defined($info->{'score_mate' . $mpv});
531 # If we have a draw or near-draw score, there's also not much interesting
532 # we could add from a tablebase. We only really want mates.
533 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
535 # Run through the PV until we are at a 6-man position.
536 # TODO: We could in theory only have 5-man data.
537 my @pv = @{$info->{'pv' . $mpv}};
538 my $key = $pos->fen() . " " . join('', @pv);
540 if (exists($tbprobe_cache{$key})) {
541 @moves = @{$tbprobe_cache{$key}};
544 # Force doing at least one move of the PV.
545 my $move = shift @pv;
547 $pos = $pos->make_move(parse_uci_move($move));
550 while ($pos->num_pieces() > 6 && $#pv > -1) {
551 my $move = shift @pv;
553 $pos = $pos->make_move(parse_uci_move($move));
556 return if ($pos->num_pieces() > 6);
558 my $fen = $pos->fen();
559 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
560 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
561 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
562 $pgn->quick_parse_game;
563 $info->{'pv' . $mpv} = \@moves;
565 # Splice the PV from the tablebase onto what we have so far.
566 for my $move (@{$pgn->moves}) {
567 last if $move eq '#';
569 ($pos, $uci_move) = $pos->make_pretty_move($move);
570 push @moves, $uci_move;
573 $tbprobe_cache{$key} = \@moves;
576 $info->{'pv' . $mpv} = \@moves;
578 my $matelen = int((1 + scalar @moves) / 2);
579 if ((scalar @moves) % 2 == 0) {
580 $info->{'score_mate' . $mpv} = -$matelen;
582 $info->{'score_mate' . $mpv} = $matelen;
589 return if (!defined($pos_calculating));
591 # Don't update too often.
592 my $age = Time::HiRes::tv_interval($latest_update);
593 if ($age < $remoteglotconf::update_max_interval) {
594 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
595 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
599 my $info = $engine->{'info'};
602 # If we have tablebase data from a previous lookup, replace the
603 # engine data with the data from the tablebase.
605 my $fen = $pos_calculating->fen();
606 if (exists($tb_cache{$fen})) {
607 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
608 delete $info->{$key . '1'};
609 delete $info->{$key};
611 $info->{'nodes'} = 0;
613 $info->{'depth'} = 0;
614 $info->{'seldepth'} = 0;
615 $info->{'tbhits'} = 0;
617 my $t = $tb_cache{$fen};
619 my $matelen = int((1 + $t->{'score'}) / 2);
620 if ($t->{'result'} eq '1/2-1/2') {
621 $info->{'score_cp'} = 0;
622 } elsif ($t->{'result'} eq '1-0') {
623 if ($pos_calculating->{'toplay'} eq 'B') {
624 $info->{'score_mate'} = -$matelen;
626 $info->{'score_mate'} = $matelen;
629 if ($pos_calculating->{'toplay'} eq 'B') {
630 $info->{'score_mate'} = $matelen;
632 $info->{'score_mate'} = -$matelen;
636 $info->{'tablebase'} = 1;
638 $info->{'tablebase'} = 0;
642 # Some programs _always_ report MultiPV, even with only one PV.
643 # In this case, we simply use that data as if MultiPV was never
646 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
647 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
648 if (exists($info->{$key . '1'})) {
649 $info->{$key} = $info->{$key . '1'};
651 delete $info->{$key};
657 # Check the PVs first. if they're invalid, just wait, as our data
658 # is most likely out of sync. This isn't a very good solution, as
659 # it can frequently miss stuff, but it's good enough for most users.
663 if (exists($info->{'pv'})) {
664 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
668 while (exists($info->{'pv' . $mpv})) {
669 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
674 $engine->{'info'} = {};
678 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
679 if (exists($info->{'pv'})) {
680 complete_using_tbprobe($pos_calculating, $info, '');
684 while (exists($info->{'pv' . $mpv})) {
685 complete_using_tbprobe($pos_calculating, $info, $mpv);
691 $latest_update = [Time::HiRes::gettimeofday];
695 my $info = $engine->{'info'};
696 my $id = $engine->{'id'};
698 my $text = 'Analysis';
699 if ($pos_calculating->{'last_move'} ne 'none') {
700 if ($pos_calculating->{'toplay'} eq 'W') {
701 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
703 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
705 if (exists($id->{'name'})) {
710 if (exists($id->{'name'})) {
711 $text .= " by $id->{'name'}:\n\n";
716 return unless (exists($pos_calculating->{'board'}));
718 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
721 while (exists($info->{'pv' . $mpv})) {
722 $text .= sprintf " PV%2u", $mpv;
723 my $score = short_score($info, $pos_calculating, $mpv);
724 $text .= " ($score)" if (defined($score));
727 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
728 if ($info->{'tbhits' . $mpv} == 1) {
729 $tbhits = ", 1 tbhit";
731 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
735 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
736 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
737 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
741 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
747 my $score = long_score($info, $pos_calculating, '');
748 $text .= " $score\n" if defined($score);
749 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
752 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
753 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
754 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
756 if (exists($info->{'seldepth'})) {
757 $text .= sprintf " (%u selective)", $info->{'seldepth'};
759 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
760 if ($info->{'tbhits'} == 1) {
761 $text .= ", one Syzygy hit";
763 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
769 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
771 my @refutation_lines = ();
772 if (defined($engine2)) {
773 for (my $mpv = 1; $mpv < 500; ++$mpv) {
774 my $info = $engine2->{'info'};
775 last if (!exists($info->{'pv' . $mpv}));
777 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
778 my $pv = $info->{'pv' . $mpv};
779 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
780 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
781 if (scalar @pretty_pv > 5) {
782 @pretty_pv = @pretty_pv[0..4];
783 push @pretty_pv, "...";
785 my $key = $pretty_move;
786 my $line = sprintf(" %-6s %6s %3s %s",
788 short_score($info, $pos_calculating_second_engine, $mpv),
789 "d" . $info->{'depth' . $mpv},
790 join(', ', @pretty_pv));
791 push @refutation_lines, [ $key, $line ];
796 if ($#refutation_lines >= 0) {
797 $text .= "Shallow search of all legal moves:\n\n";
798 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
799 $text .= $line->[1] . "\n";
804 if ($last_text ne $text) {
805 print "
\e[H
\e[2J"; # clear the screen
812 my $historic_json_only = shift;
813 my $info = $engine->{'info'};
816 $json->{'position'} = $pos_calculating->to_json_hash();
817 $json->{'engine'} = $engine->{'id'};
818 if (defined($remoteglotconf::engine_url)) {
819 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
821 if (defined($remoteglotconf::engine_details)) {
822 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
824 my @grpc_backends = ();
825 if (defined($remoteglotconf::engine_grpc_backend)) {
826 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
828 if (defined($remoteglotconf::engine2_grpc_backend)) {
829 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
831 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
832 if (defined($remoteglotconf::move_source)) {
833 $json->{'move_source'} = $remoteglotconf::move_source;
835 if (defined($remoteglotconf::move_source_url)) {
836 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
838 $json->{'score'} = score_digest($info, $pos_calculating, '');
839 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
841 $json->{'nodes'} = $info->{'nodes'};
842 $json->{'nps'} = $info->{'nps'};
843 $json->{'depth'} = $info->{'depth'};
844 $json->{'tbhits'} = $info->{'tbhits'};
845 $json->{'seldepth'} = $info->{'seldepth'};
846 $json->{'tablebase'} = $info->{'tablebase'};
847 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
849 my %refutation_lines = ();
850 my @refutation_lines = ();
851 if (defined($engine2)) {
852 for (my $mpv = 1; $mpv < 500; ++$mpv) {
853 my $info = $engine2->{'info'};
854 my $pretty_move = "";
856 last if (!exists($info->{'pv' . $mpv}));
859 complete_using_tbprobe($pos_calculating, $info, $mpv);
860 my $pv = $info->{'pv' . $mpv};
861 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
862 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
863 $refutation_lines{$pretty_move} = {
864 depth => $info->{'depth' . $mpv},
865 score => score_digest($info, $pos_calculating, $mpv),
866 move => $pretty_move,
872 $json->{'refutation_lines'} = \%refutation_lines;
874 # Piece together historic score information, to the degree we have it.
875 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
876 my %score_history = ();
878 local $dbh->{AutoCommit} = 0;
879 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
880 my $pos = Position->start_pos('white', 'black');
881 my $halfmove_num = 0;
882 for my $move (@{$pos_calculating->{'history'}}) {
883 my $id = id_for_pos($pos, $halfmove_num);
884 my $ref = $dbh->selectrow_hashref($q, undef, $id);
886 $score_history{$halfmove_num} = [
887 $ref->{'score_type'},
888 $ref->{'score_value'}
892 ($pos) = $pos->make_pretty_move($move);
897 # If at any point we are missing 10 consecutive moves,
898 # truncate the history there. This is so we don't get into
899 # a situation where we e.g. start analyzing at move 45,
900 # but we have analysis for 1. e4 from some completely different game
901 # and thus show a huge hole.
902 my $consecutive_missing = 0;
903 my $truncate_until = 0;
904 for (my $i = $halfmove_num; $i --> 0; ) {
905 if ($consecutive_missing >= 10) {
906 delete $score_history{$i};
909 if (exists($score_history{$i})) {
910 $consecutive_missing = 0;
912 ++$consecutive_missing;
916 $json->{'score_history'} = \%score_history;
919 # Give out a list of other games going on. (Empty is fine.)
920 # TODO: Don't bother reading our own file, the data will be stale anyway.
921 if (!$historic_json_only) {
924 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
926 while (my $ref = $q->fetchrow_hashref) {
928 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
929 my $other_game_json = JSON::XS::decode_json($other_game_contents);
931 die "Missing position" if (!exists($other_game_json->{'position'}));
932 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
933 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
937 name => "$white–$black",
938 url => $ref->{'url'},
939 hashurl => $ref->{'hash_url'},
941 if (defined($other_game_json->{'position'}{'result'})) {
942 $game->{'result'} = $other_game_json->{'position'}{'result'};
944 $game->{'score'} = $other_game_json->{'score'};
949 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
953 if (scalar @games > 0) {
954 $json->{'games'} = \@games;
958 my $json_enc = JSON::XS->new;
959 $json_enc->canonical(1);
960 my $encoded = $json_enc->encode($json);
961 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
962 (defined($last_written_json) && $last_written_json eq $encoded)) {
963 atomic_set_contents($remoteglotconf::json_output, $encoded);
964 $last_written_json = $encoded;
967 if (exists($pos_calculating->{'history'}) &&
968 defined($remoteglotconf::json_history_dir)) {
969 my $id = id_for_pos($pos_calculating);
970 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
972 # Overwrite old analysis (assuming it exists at all) if we're
973 # using a different engine, or if we've calculated deeper.
974 # nodes is used as a tiebreaker. Don't bother about Multi-PV
975 # data; it's not that important.
976 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
977 my $new_depth = $json->{'depth'} // 0;
978 my $new_nodes = $json->{'nodes'} // 0;
979 if (!defined($old_engine) ||
980 $old_engine ne $json->{'engine'}{'name'} ||
981 $new_depth > $old_depth ||
982 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
983 atomic_set_contents($filename, $encoded);
984 if (defined($json->{'score'})) {
985 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
986 ' ON CONFLICT (id) DO UPDATE SET ' .
987 ' score_type=EXCLUDED.score_type, ' .
988 ' score_value=EXCLUDED.score_value, ' .
989 ' engine=EXCLUDED.engine, ' .
990 ' depth=EXCLUDED.depth, ' .
991 ' nodes=EXCLUDED.nodes',
993 $id, $json->{'score'}[0], $json->{'score'}[1],
994 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1000 sub atomic_set_contents {
1001 my ($filename, $contents) = @_;
1003 open my $fh, ">", $filename . ".tmp"
1005 print $fh $contents;
1007 rename($filename . ".tmp", $filename);
1011 my ($pos, $halfmove_num) = @_;
1013 $halfmove_num //= scalar @{$pos->{'history'}};
1014 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1015 return "move$halfmove_num-$fen";
1018 sub get_json_analysis_stats {
1020 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1021 if (defined($ref)) {
1022 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1029 my ($engine, $msg) = @_;
1030 $engine->print($msg);
1031 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1035 my ($info, $pos, $mpv) = @_;
1037 my $invert = ($pos->{'toplay'} eq 'B');
1038 if (defined($info->{'score_mate' . $mpv})) {
1040 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1042 return sprintf "M%3d", $info->{'score_mate' . $mpv};
1045 if (exists($info->{'score_cp' . $mpv})) {
1046 my $score = $info->{'score_cp' . $mpv} * 0.01;
1048 if ($info->{'tablebase'}) {
1057 return sprintf "%+5.2f", $score;
1064 # Sufficient for computing long_score, short_score, plot_score and
1065 # (with side-to-play information) score_sort_key.
1067 my ($info, $pos, $mpv) = @_;
1069 if (defined($info->{'score_mate' . $mpv})) {
1070 my $mate = $info->{'score_mate' . $mpv};
1071 if ($pos->{'toplay'} eq 'B') {
1074 return ['m', $mate];
1076 if (exists($info->{'score_cp' . $mpv})) {
1077 my $score = $info->{'score_cp' . $mpv};
1078 if ($pos->{'toplay'} eq 'B') {
1081 if ($score == 0 && $info->{'tablebase'}) {
1082 return ['d', undef];
1084 return ['cp', int($score)];
1093 my ($info, $pos, $mpv) = @_;
1095 if (defined($info->{'score_mate' . $mpv})) {
1096 my $mate = $info->{'score_mate' . $mpv};
1097 if ($pos->{'toplay'} eq 'B') {
1101 return sprintf "White mates in %u", $mate;
1103 return sprintf "Black mates in %u", -$mate;
1106 if (exists($info->{'score_cp' . $mpv})) {
1107 my $score = $info->{'score_cp' . $mpv} * 0.01;
1109 if ($info->{'tablebase'}) {
1110 return "Theoretical draw";
1112 return "Score: 0.00";
1115 if ($pos->{'toplay'} eq 'B') {
1118 return sprintf "Score: %+5.2f", $score;
1125 # For graphs; a single number in centipawns, capped at +/- 500.
1127 my ($info, $pos, $mpv) = @_;
1129 my $invert = ($pos->{'toplay'} eq 'B');
1130 if (defined($info->{'score_mate' . $mpv})) {
1131 my $mate = $info->{'score_mate' . $mpv};
1141 if (exists($info->{'score_cp' . $mpv})) {
1142 my $score = $info->{'score_cp' . $mpv};
1146 $score = 500 if ($score > 500);
1147 $score = -500 if ($score < -500);
1155 my %book_cache = ();
1157 my ($fen, $board, $toplay) = @_;
1159 if (exists($book_cache{$fen})) {
1160 return $book_cache{$fen};
1163 my $ret = `./booklook $fen`;
1164 return "" if ($ret =~ /Not found/ || $ret eq '');
1168 for my $m (split /\n/, $ret) {
1169 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1173 $pmove = '(current)';
1175 ($pmove) = prettyprint_pv_no_cache($board, $move);
1176 $pmove .= $annotation;
1180 if ($toplay eq 'W') {
1181 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1183 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1185 my $n = $win + $draw + $lose;
1191 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1194 push @moves, [ $pmove, $n, $percent, $rating ];
1197 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1199 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1200 for my $m (@moves) {
1201 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1208 my ($pgn, $pos) = @_;
1210 # Look for extended PGN clock tags.
1211 my $tags = $pgn->tags;
1212 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1213 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1214 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1218 # Look for TCEC-style time comments.
1219 my $moves = $pgn->moves;
1220 my $comments = $pgn->comments;
1221 my $last_black_move = int((scalar @$moves) / 2);
1222 my $last_white_move = int((1 + scalar @$moves) / 2);
1224 my $black_key = $last_black_move . "b";
1225 my $white_key = $last_white_move . "w";
1227 if (exists($comments->{$white_key}) &&
1228 exists($comments->{$black_key}) &&
1229 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1230 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1231 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1232 $pos->{'white_clock'} = hms_to_sec($1);
1233 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1234 $pos->{'black_clock'} = hms_to_sec($1);
1238 delete $pos->{'white_clock'};
1239 delete $pos->{'black_clock'};
1244 return undef if (!defined($hms));
1245 $hms =~ /(\d+):(\d+):(\d+)/;
1246 return $1 * 3600 + $2 * 60 + $3;
1249 sub find_clock_start {
1250 my ($pos, $prev_pos) = @_;
1252 # If the game is over, the clock is stopped.
1253 if (exists($pos->{'result'}) &&
1254 ($pos->{'result'} eq '1-0' ||
1255 $pos->{'result'} eq '1/2-1/2' ||
1256 $pos->{'result'} eq '0-1')) {
1260 # When we don't have any moves, we assume the clock hasn't started yet.
1261 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1262 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1263 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1268 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1269 # The history is needed for id_for_pos.
1270 if (!exists($pos->{'history'})) {
1274 my $id = id_for_pos($pos);
1275 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1276 if (defined($clock_info)) {
1277 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1278 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1279 if ($pos->{'toplay'} eq 'W') {
1280 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1282 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1287 # OK, we haven't seen this position before, so we assume the move
1288 # happened right now.
1290 # See if we should do our own clock management (ie., clock information
1291 # is spurious or non-existent).
1292 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1293 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1294 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1295 if (defined($prev_pos->{'white_clock_target'})) {
1296 $wc = $prev_pos->{'white_clock_target'} - time;
1298 if (defined($prev_pos->{'black_clock_target'})) {
1299 $bc = $prev_pos->{'black_clock_target'} - time;
1301 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1302 $pos->{'white_clock'} = $wc;
1303 $pos->{'black_clock'} = $bc;
1306 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1307 if (!exists($pos->{$key})) {
1308 # No clock information.
1311 my $time_left = $pos->{$key};
1312 my ($white_clock_target, $black_clock_target);
1313 if ($pos->{'toplay'} eq 'W') {
1314 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1316 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1318 local $dbh->{AutoCommit} = 0;
1319 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1320 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1321 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1325 sub schedule_tb_lookup {
1326 return if (!defined($remoteglotconf::tb_serial_key));
1327 my $pos = $pos_calculating;
1328 return if (exists($tb_cache{$pos->fen()}));
1330 # If there's more than seven pieces, there's not going to be an answer,
1332 return if ($pos->num_pieces() > 7);
1334 # Max one at a time. If it's still relevant when it returns,
1335 # schedule_tb_lookup() will be called again.
1336 return if ($tb_lookup_running);
1338 $tb_lookup_running = 1;
1339 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1340 $remoteglotconf::tb_serial_key .
1341 '&auth.password=aquarium&type=0&fen=' .
1342 URI::Escape::uri_escape($pos->fen());
1343 print TBLOG "Downloading $url...\n";
1344 AnyEvent::HTTP::http_get($url, sub {
1345 handle_tb_lookup_return(@_, $pos, $pos->fen());
1349 sub handle_tb_lookup_return {
1350 my ($body, $header, $pos, $fen) = @_;
1351 print TBLOG "Response for [$fen]:\n";
1352 print TBLOG $header . "\n\n";
1353 print TBLOG $body . "\n\n";
1355 my $response = JSON::XS::decode_json($body);
1356 if ($response->{'ErrorCode'} != 0) {
1357 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1359 my $state = $response->{'Response'}{'StateString'};
1360 if ($state eq 'COMPLETE') {
1361 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1362 if (!defined($pgn) || !$pgn->read_game()) {
1363 warn "Error in parsing PGN\n";
1365 $pgn->quick_parse_game;
1367 my $moves = $pgn->moves;
1369 for my $move (@$moves) {
1371 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1372 push @uci_moves, $uci_move;
1375 result => $pgn->result,
1377 score => $response->{'Response'}{'Score'},
1381 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1382 # Try again in a second. Note that if we have changed
1383 # position in the meantime, we might query a completely
1384 # different position! But that's fine.
1386 die "Unknown response state " . $state;
1389 # Wait a second before we schedule another one.
1390 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1391 $tb_lookup_running = 0;
1392 schedule_tb_lookup();
1396 warn "Error in tablebase lookup: $@";
1398 # Don't try this one again, but don't block new lookups either.
1399 $tb_lookup_running = 0;
1404 my ($cmdline, $tag, $cb) = @_;
1405 return undef if (!defined($cmdline));
1406 return Engine->open($cmdline, $tag, $cb);
1409 sub col_letter_to_num {
1410 return ord(shift) - ord('a');
1413 sub row_letter_to_num {
1414 return 7 - (ord(shift) - ord('1'));
1417 sub parse_uci_move {
1419 my $from_col = col_letter_to_num(substr($move, 0, 1));
1420 my $from_row = row_letter_to_num(substr($move, 1, 1));
1421 my $to_col = col_letter_to_num(substr($move, 2, 1));
1422 my $to_row = row_letter_to_num(substr($move, 3, 1));
1423 my $promo = substr($move, 4, 1);
1424 return ($from_row, $from_col, $to_row, $to_col, $promo);