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 <sgunderson@bigfoot.com>
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->{'pretty_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 $pos = Position->start_pos($pgn->white, $pgn->black);
295 my $moves = $pgn->moves;
297 my @repretty_moves = ();
298 for my $move (@$moves) {
299 my ($npos, $uci_move) = $pos->make_pretty_move($move);
300 push @uci_moves, $uci_move;
302 # Re-prettyprint the move.
303 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
304 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
305 push @repretty_moves, $pretty;
308 $pos->{'result'} = $pgn->result;
309 $pos->{'pretty_history'} = \@repretty_moves;
311 extract_clock($pgn, $pos);
313 # Sometimes, PGNs lose a move or two for a short while,
314 # or people push out new ones non-atomically.
315 # Thus, if we PGN doesn't change names but becomes
316 # shorter, we mistrust it for a few seconds.
318 if (defined($last_pgn_white) && defined($last_pgn_black) &&
319 $last_pgn_white eq $pgn->white &&
320 $last_pgn_black eq $pgn->black &&
321 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
322 if (++$pgn_hysteresis_counter < 3) {
327 $last_pgn_white = $pgn->white;
328 $last_pgn_black = $pgn->black;
329 @last_pgn_uci_moves = @uci_moves;
330 $pgn_hysteresis_counter = 0;
331 handle_position($pos);
335 warn "Error in parsing moves from $url: $@\n";
339 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
344 sub handle_position {
346 find_clock_start($pos, $pos_calculating);
348 # if this is already in the queue, ignore it (just update the result)
349 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
350 $pos_waiting->{'result'} = $pos->{'result'};
354 # if we're already chewing on this and there's nothing else in the queue,
356 if (!defined($pos_waiting) && defined($pos_calculating) &&
357 $pos->fen() eq $pos_calculating->fen()) {
358 $pos_calculating->{'result'} = $pos->{'result'};
362 # if we're already thinking on something, stop and wait for the engine
364 if (defined($pos_calculating)) {
365 # Store the final data we have for this position in the history,
366 # with the precise clock information we just got from the new
367 # position. (Historic positions store the clock at the end of
370 # Do not output anything new to the main analysis; that's
371 # going to be obsolete really soon.
372 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
373 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
374 delete $pos_calculating->{'white_clock_target'};
375 delete $pos_calculating->{'black_clock_target'};
378 if (!defined($pos_waiting)) {
379 uciprint($engine, "stop");
381 if ($remoteglotconf::uci_assume_full_compliance) {
384 uciprint($engine, "position fen " . $pos->fen());
385 uciprint($engine, "go infinite");
386 $pos_calculating = $pos;
389 # it's wrong just to give the FEN (the move history is useful,
390 # and per the UCI spec, we should really have sent "ucinewgame"),
392 uciprint($engine, "position fen " . $pos->fen());
393 uciprint($engine, "go infinite");
394 $pos_calculating = $pos;
397 if (defined($engine2)) {
398 if (defined($pos_calculating_second_engine)) {
399 uciprint($engine2, "stop");
401 uciprint($engine2, "position fen " . $pos->fen());
402 uciprint($engine2, "go infinite");
403 $pos_calculating_second_engine = $pos;
405 $engine2->{'info'} = {};
408 $engine->{'info'} = {};
411 schedule_tb_lookup();
414 # Output a command every move to note that we're
415 # still paying attention -- this is a good tradeoff,
416 # since if no move has happened in the last half
417 # hour, the analysis/relay has most likely stopped
418 # and we should stop hogging server resources.
424 my ($engine, @x) = @_;
427 my $info = $engine->{'info'};
429 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
430 for my $i (0..$#x - 1) {
431 if ($x[$i] eq 'multipv') {
437 while (scalar @x > 0) {
438 if ($x[0] eq 'multipv') {
444 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
446 my $value = shift @x;
447 $info->{$key} = $value;
450 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
451 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
454 my $value = shift @x;
455 $info->{$key . $mpv} = $value;
458 if ($x[0] eq 'score') {
461 delete $info->{'score_cp' . $mpv};
462 delete $info->{'score_mate' . $mpv};
464 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
467 $info->{'score_cp' . $mpv} = shift @x;
468 } elsif ($x[0] eq 'mate') {
470 $info->{'score_mate' . $mpv} = shift @x;
478 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
481 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
485 #print "unknown info '$x[0]', trying to recover...\n";
487 die "Unknown info '" . join(',', @x) . "'";
493 my ($engine, @x) = @_;
495 while (scalar @x > 0) {
496 if ($x[0] eq 'name') {
497 my $value = join(' ', @x);
498 $engine->{'id'}{'author'} = $value;
507 sub prettyprint_pv_no_cache {
508 my ($board, @pvs) = @_;
510 if (scalar @pvs == 0 || !defined($pvs[0])) {
515 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
516 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
517 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
521 my ($pos, @pvs) = @_;
523 my $cachekey = join('', @pvs);
524 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
525 return @{$pos->{'prettyprint_cache'}{$cachekey}};
527 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
528 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
536 return if (!defined($pos_calculating));
538 # Don't update too often.
539 my $age = Time::HiRes::tv_interval($latest_update);
540 if ($age < $remoteglotconf::update_max_interval) {
541 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
542 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
546 my $info = $engine->{'info'};
549 # If we have tablebase data from a previous lookup, replace the
550 # engine data with the data from the tablebase.
552 my $fen = $pos_calculating->fen();
553 if (exists($tb_cache{$fen})) {
554 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
555 delete $info->{$key . '1'};
556 delete $info->{$key};
558 $info->{'nodes'} = 0;
560 $info->{'depth'} = 0;
561 $info->{'seldepth'} = 0;
562 $info->{'tbhits'} = 0;
564 my $t = $tb_cache{$fen};
566 my $matelen = int((1 + $t->{'score'}) / 2);
567 if ($t->{'result'} eq '1/2-1/2') {
568 $info->{'score_cp'} = 0;
569 } elsif ($t->{'result'} eq '1-0') {
570 if ($pos_calculating->{'toplay'} eq 'B') {
571 $info->{'score_mate'} = -$matelen;
573 $info->{'score_mate'} = $matelen;
576 if ($pos_calculating->{'toplay'} eq 'B') {
577 $info->{'score_mate'} = $matelen;
579 $info->{'score_mate'} = -$matelen;
583 $info->{'tablebase'} = 1;
585 $info->{'tablebase'} = 0;
589 # Some programs _always_ report MultiPV, even with only one PV.
590 # In this case, we simply use that data as if MultiPV was never
593 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
594 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
595 if (exists($info->{$key . '1'})) {
596 $info->{$key} = $info->{$key . '1'};
602 # Check the PVs first. if they're invalid, just wait, as our data
603 # is most likely out of sync. This isn't a very good solution, as
604 # it can frequently miss stuff, but it's good enough for most users.
608 if (exists($info->{'pv'})) {
609 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
613 while (exists($info->{'pv' . $mpv})) {
614 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
619 $engine->{'info'} = {};
625 $latest_update = [Time::HiRes::gettimeofday];
629 my $info = $engine->{'info'};
630 my $id = $engine->{'id'};
632 my $text = 'Analysis';
633 if ($pos_calculating->{'last_move'} ne 'none') {
634 if ($pos_calculating->{'toplay'} eq 'W') {
635 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
637 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
639 if (exists($id->{'name'})) {
644 if (exists($id->{'name'})) {
645 $text .= " by $id->{'name'}:\n\n";
650 return unless (exists($pos_calculating->{'board'}));
652 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
655 while (exists($info->{'pv' . $mpv})) {
656 $text .= sprintf " PV%2u", $mpv;
657 my $score = short_score($info, $pos_calculating, $mpv);
658 $text .= " ($score)" if (defined($score));
661 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
662 if ($info->{'tbhits' . $mpv} == 1) {
663 $tbhits = ", 1 tbhit";
665 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
669 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
670 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
671 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
675 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
681 my $score = long_score($info, $pos_calculating, '');
682 $text .= " $score\n" if defined($score);
683 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
686 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
687 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
688 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
690 if (exists($info->{'seldepth'})) {
691 $text .= sprintf " (%u selective)", $info->{'seldepth'};
693 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
694 if ($info->{'tbhits'} == 1) {
695 $text .= ", one Syzygy hit";
697 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
703 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
705 my @refutation_lines = ();
706 if (defined($engine2)) {
707 for (my $mpv = 1; $mpv < 500; ++$mpv) {
708 my $info = $engine2->{'info'};
709 last if (!exists($info->{'pv' . $mpv}));
711 my $pv = $info->{'pv' . $mpv};
713 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
714 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
715 if (scalar @pretty_pv > 5) {
716 @pretty_pv = @pretty_pv[0..4];
717 push @pretty_pv, "...";
719 my $key = $pretty_move;
720 my $line = sprintf(" %-6s %6s %3s %s",
722 short_score($info, $pos_calculating_second_engine, $mpv),
723 "d" . $info->{'depth' . $mpv},
724 join(', ', @pretty_pv));
725 push @refutation_lines, [ $key, $line ];
730 if ($#refutation_lines >= 0) {
731 $text .= "Shallow search of all legal moves:\n\n";
732 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
733 $text .= $line->[1] . "\n";
738 if ($last_text ne $text) {
739 print "
\e[H
\e[2J"; # clear the screen
746 my $historic_json_only = shift;
747 my $info = $engine->{'info'};
750 $json->{'position'} = $pos_calculating->to_json_hash();
751 $json->{'engine'} = $engine->{'id'};
752 if (defined($remoteglotconf::engine_url)) {
753 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
755 if (defined($remoteglotconf::engine_details)) {
756 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
758 if (defined($remoteglotconf::move_source)) {
759 $json->{'move_source'} = $remoteglotconf::move_source;
761 if (defined($remoteglotconf::move_source_url)) {
762 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
764 $json->{'score'} = long_score($info, $pos_calculating, '');
765 $json->{'short_score'} = short_score($info, $pos_calculating, '');
766 $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
767 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
769 $json->{'nodes'} = $info->{'nodes'};
770 $json->{'nps'} = $info->{'nps'};
771 $json->{'depth'} = $info->{'depth'};
772 $json->{'tbhits'} = $info->{'tbhits'};
773 $json->{'seldepth'} = $info->{'seldepth'};
774 $json->{'tablebase'} = $info->{'tablebase'};
776 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
777 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
779 my %refutation_lines = ();
780 my @refutation_lines = ();
781 if (defined($engine2)) {
782 for (my $mpv = 1; $mpv < 500; ++$mpv) {
783 my $info = $engine2->{'info'};
784 my $pretty_move = "";
786 last if (!exists($info->{'pv' . $mpv}));
789 my $pv = $info->{'pv' . $mpv};
790 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
791 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
792 $refutation_lines{$pv->[0]} = {
793 sort_key => $pretty_move,
794 depth => $info->{'depth' . $mpv},
795 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
796 pretty_score => short_score($info, $pos_calculating, $mpv),
797 pretty_move => $pretty_move,
798 pv_pretty => \@pretty_pv,
803 $json->{'refutation_lines'} = \%refutation_lines;
805 # Piece together historic score information, to the degree we have it.
806 if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
807 my %score_history = ();
809 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
810 my $pos = Position->start_pos('white', 'black');
811 my $halfmove_num = 0;
812 for my $move (@{$pos_calculating->{'pretty_history'}}) {
813 my $id = id_for_pos($pos, $halfmove_num);
814 my $ref = $dbh->selectrow_hashref($q, undef, $id);
816 $score_history{$halfmove_num} = [
817 $ref->{'plot_score'},
818 $ref->{'short_score'}
822 ($pos) = $pos->make_pretty_move($move);
826 # If at any point we are missing 10 consecutive moves,
827 # truncate the history there. This is so we don't get into
828 # a situation where we e.g. start analyzing at move 45,
829 # but we have analysis for 1. e4 from some completely different game
830 # and thus show a huge hole.
831 my $consecutive_missing = 0;
832 my $truncate_until = 0;
833 for (my $i = $halfmove_num; $i --> 0; ) {
834 if ($consecutive_missing >= 10) {
835 delete $score_history{$i};
838 if (exists($score_history{$i})) {
839 $consecutive_missing = 0;
841 ++$consecutive_missing;
845 $json->{'score_history'} = \%score_history;
848 # Give out a list of other games going on. (Empty is fine.)
849 if (!$historic_json_only) {
852 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
854 while (my $ref = $q->fetchrow_hashref) {
856 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
857 my $other_game_json = JSON::XS::decode_json($other_game_contents);
859 die "Missing position" if (!exists($other_game_json->{'position'}));
860 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
861 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
865 name => "$white–$black",
870 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
874 if (scalar @games > 0) {
875 $json->{'games'} = \@games;
879 my $json_enc = JSON::XS->new;
880 $json_enc->canonical(1);
881 my $encoded = $json_enc->encode($json);
882 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
883 (defined($last_written_json) && $last_written_json eq $encoded)) {
884 atomic_set_contents($remoteglotconf::json_output, $encoded);
885 $last_written_json = $encoded;
888 if (exists($pos_calculating->{'pretty_history'}) &&
889 defined($remoteglotconf::json_history_dir)) {
890 my $id = id_for_pos($pos_calculating);
891 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
893 # Overwrite old analysis (assuming it exists at all) if we're
894 # using a different engine, or if we've calculated deeper.
895 # nodes is used as a tiebreaker. Don't bother about Multi-PV
896 # data; it's not that important.
897 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
898 my $new_depth = $json->{'depth'} // 0;
899 my $new_nodes = $json->{'nodes'} // 0;
900 if (!defined($old_engine) ||
901 $old_engine ne $json->{'engine'}{'name'} ||
902 $new_depth > $old_depth ||
903 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
904 atomic_set_contents($filename, $encoded);
905 if (defined($json->{'plot_score'})) {
906 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
907 ' ON CONFLICT (id) DO UPDATE SET ' .
908 ' plot_score=EXCLUDED.plot_score, ' .
909 ' short_score=EXCLUDED.short_score, ' .
910 ' engine=EXCLUDED.engine, ' .
911 ' depth=EXCLUDED.depth, ' .
912 ' nodes=EXCLUDED.nodes',
914 $id, $json->{'plot_score'}, $json->{'short_score'},
915 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
921 sub atomic_set_contents {
922 my ($filename, $contents) = @_;
924 open my $fh, ">", $filename . ".tmp"
928 rename($filename . ".tmp", $filename);
932 my ($pos, $halfmove_num) = @_;
934 $halfmove_num //= scalar @{$pos->{'pretty_history'}};
935 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
936 return "move$halfmove_num-$fen";
939 sub get_json_analysis_stats {
941 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
943 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
950 my ($engine, $msg) = @_;
951 $engine->print($msg);
952 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
956 my ($info, $pos, $mpv) = @_;
958 my $invert = ($pos->{'toplay'} eq 'B');
959 if (defined($info->{'score_mate' . $mpv})) {
961 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
963 return sprintf "M%3d", $info->{'score_mate' . $mpv};
966 if (exists($info->{'score_cp' . $mpv})) {
967 my $score = $info->{'score_cp' . $mpv} * 0.01;
969 if ($info->{'tablebase'}) {
978 return sprintf "%+5.2f", $score;
986 my ($info, $pos, $mpv, $invert) = @_;
988 if (defined($info->{'score_mate' . $mpv})) {
989 my $mate = $info->{'score_mate' . $mpv};
993 $score = 99999 - $mate;
995 # Side to move is getting mated (note the double negative for $mate)
996 $score = -99999 - $mate;
1003 if (exists($info->{'score_cp' . $mpv})) {
1004 my $score = $info->{'score_cp' . $mpv};
1016 my ($info, $pos, $mpv) = @_;
1018 if (defined($info->{'score_mate' . $mpv})) {
1019 my $mate = $info->{'score_mate' . $mpv};
1020 if ($pos->{'toplay'} eq 'B') {
1024 return sprintf "White mates in %u", $mate;
1026 return sprintf "Black mates in %u", -$mate;
1029 if (exists($info->{'score_cp' . $mpv})) {
1030 my $score = $info->{'score_cp' . $mpv} * 0.01;
1032 if ($info->{'tablebase'}) {
1033 return "Theoretical draw";
1035 return "Score: 0.00";
1038 if ($pos->{'toplay'} eq 'B') {
1041 return sprintf "Score: %+5.2f", $score;
1048 # For graphs; a single number in centipawns, capped at +/- 500.
1050 my ($info, $pos, $mpv) = @_;
1052 my $invert = ($pos->{'toplay'} eq 'B');
1053 if (defined($info->{'score_mate' . $mpv})) {
1054 my $mate = $info->{'score_mate' . $mpv};
1064 if (exists($info->{'score_cp' . $mpv})) {
1065 my $score = $info->{'score_cp' . $mpv};
1069 $score = 500 if ($score > 500);
1070 $score = -500 if ($score < -500);
1078 my %book_cache = ();
1080 my ($fen, $board, $toplay) = @_;
1082 if (exists($book_cache{$fen})) {
1083 return $book_cache{$fen};
1086 my $ret = `./booklook $fen`;
1087 return "" if ($ret =~ /Not found/ || $ret eq '');
1091 for my $m (split /\n/, $ret) {
1092 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1096 $pmove = '(current)';
1098 ($pmove) = prettyprint_pv_no_cache($board, $move);
1099 $pmove .= $annotation;
1103 if ($toplay eq 'W') {
1104 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1106 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1108 my $n = $win + $draw + $lose;
1114 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1117 push @moves, [ $pmove, $n, $percent, $rating ];
1120 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1122 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1123 for my $m (@moves) {
1124 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1131 my ($pgn, $pos) = @_;
1133 # Look for extended PGN clock tags.
1134 my $tags = $pgn->tags;
1135 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1136 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1137 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1141 # Look for TCEC-style time comments.
1142 my $moves = $pgn->moves;
1143 my $comments = $pgn->comments;
1144 my $last_black_move = int((scalar @$moves) / 2);
1145 my $last_white_move = int((1 + scalar @$moves) / 2);
1147 my $black_key = $last_black_move . "b";
1148 my $white_key = $last_white_move . "w";
1150 if (exists($comments->{$white_key}) &&
1151 exists($comments->{$black_key}) &&
1152 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1153 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1154 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1155 $pos->{'white_clock'} = hms_to_sec($1);
1156 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1157 $pos->{'black_clock'} = hms_to_sec($1);
1161 delete $pos->{'white_clock'};
1162 delete $pos->{'black_clock'};
1167 return undef if (!defined($hms));
1168 $hms =~ /(\d+):(\d+):(\d+)/;
1169 return $1 * 3600 + $2 * 60 + $3;
1172 sub find_clock_start {
1173 my ($pos, $prev_pos) = @_;
1175 # If the game is over, the clock is stopped.
1176 if (exists($pos->{'result'}) &&
1177 ($pos->{'result'} eq '1-0' ||
1178 $pos->{'result'} eq '1/2-1/2' ||
1179 $pos->{'result'} eq '0-1')) {
1183 # When we don't have any moves, we assume the clock hasn't started yet.
1184 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1185 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1186 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1191 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1192 # The history is needed for id_for_pos.
1193 if (!exists($pos->{'pretty_history'})) {
1197 my $id = id_for_pos($pos);
1198 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1199 if (defined($clock_info)) {
1200 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1201 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1202 if ($pos->{'toplay'} eq 'W') {
1203 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1205 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1210 # OK, we haven't seen this position before, so we assume the move
1211 # happened right now.
1213 # See if we should do our own clock management (ie., clock information
1214 # is spurious or non-existent).
1215 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1216 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1217 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1218 if (defined($prev_pos->{'white_clock_target'})) {
1219 $wc = $prev_pos->{'white_clock_target'} - time;
1221 if (defined($prev_pos->{'black_clock_target'})) {
1222 $bc = $prev_pos->{'black_clock_target'} - time;
1224 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1225 $pos->{'white_clock'} = $wc;
1226 $pos->{'black_clock'} = $bc;
1229 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1230 if (!exists($pos->{$key})) {
1231 # No clock information.
1234 my $time_left = $pos->{$key};
1235 my ($white_clock_target, $black_clock_target);
1236 if ($pos->{'toplay'} eq 'W') {
1237 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1239 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1241 local $dbh->{AutoCommit} = 0;
1242 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1243 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1244 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1248 sub schedule_tb_lookup {
1249 return if (!defined($remoteglotconf::tb_serial_key));
1250 my $pos = $pos_waiting // $pos_calculating;
1251 return if (exists($tb_cache{$pos->fen()}));
1253 # If there's more than seven pieces, there's not going to be an answer,
1255 return if ($pos->num_pieces() > 7);
1257 # Max one at a time. If it's still relevant when it returns,
1258 # schedule_tb_lookup() will be called again.
1259 return if ($tb_lookup_running);
1261 $tb_lookup_running = 1;
1262 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1263 $remoteglotconf::tb_serial_key .
1264 '&auth.password=aquarium&type=0&fen=' .
1265 URI::Escape::uri_escape($pos->fen());
1266 print TBLOG "Downloading $url...\n";
1267 AnyEvent::HTTP::http_get($url, sub {
1268 handle_tb_lookup_return(@_, $pos, $pos->fen());
1272 sub handle_tb_lookup_return {
1273 my ($body, $header, $pos, $fen) = @_;
1274 print TBLOG "Response for [$fen]:\n";
1275 print TBLOG $header . "\n\n";
1276 print TBLOG $body . "\n\n";
1278 my $response = JSON::XS::decode_json($body);
1279 if ($response->{'ErrorCode'} != 0) {
1280 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1282 my $state = $response->{'Response'}{'StateString'};
1283 if ($state eq 'COMPLETE') {
1284 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1285 if (!defined($pgn) || !$pgn->read_game()) {
1286 warn "Error in parsing PGN\n";
1288 $pgn->quick_parse_game;
1290 my $moves = $pgn->moves;
1292 for my $move (@$moves) {
1294 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1295 push @uci_moves, $uci_move;
1298 result => $pgn->result,
1300 score => $response->{'Response'}{'Score'},
1304 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1305 # Try again in a second. Note that if we have changed
1306 # position in the meantime, we might query a completely
1307 # different position! But that's fine.
1309 die "Unknown response state " . $state;
1312 # Wait a second before we schedule another one.
1313 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1314 $tb_lookup_running = 0;
1315 schedule_tb_lookup();
1319 warn "Error in tablebase lookup: $@";
1321 # Don't try this one again, but don't block new lookups either.
1322 $tb_lookup_running = 0;
1327 my ($cmdline, $tag, $cb) = @_;
1328 return undef if (!defined($cmdline));
1329 return Engine->open($cmdline, $tag, $cb);
1332 sub col_letter_to_num {
1333 return ord(shift) - ord('a');
1336 sub row_letter_to_num {
1337 return 7 - (ord(shift) - ord('1'));
1340 sub parse_uci_move {
1342 my $from_col = col_letter_to_num(substr($move, 0, 1));
1343 my $from_row = row_letter_to_num(substr($move, 1, 1));
1344 my $to_col = col_letter_to_num(substr($move, 2, 1));
1345 my $to_row = row_letter_to_num(substr($move, 3, 1));
1346 my $promo = substr($move, 4, 1);
1347 return ($from_row, $from_col, $to_row, $to_col, $promo);