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";
71 # open the chess engine
72 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
73 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
76 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
78 uciprint($engine, "setoption name UCI_AnalyseMode value true");
79 while (my ($key, $value) = each %remoteglotconf::engine_config) {
80 uciprint($engine, "setoption name $key value $value");
82 uciprint($engine, "ucinewgame");
84 if (defined($engine2)) {
85 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
86 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
87 uciprint($engine2, "setoption name $key value $value");
89 uciprint($engine2, "setoption name MultiPV value 500");
90 uciprint($engine2, "ucinewgame");
93 print "Chess engine ready.\n";
96 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
97 $t->input_log(\*FICSLOG);
98 $t->open($remoteglotconf::server);
99 $t->print($remoteglotconf::nick);
100 $t->waitfor('/Press return to enter the server/');
104 $t->cmd("set shout 0");
105 $t->cmd("set seek 0");
106 $t->cmd("set style 12");
108 my $ev1 = AnyEvent->io(
111 cb => sub { # what callback to execute
113 my $line = $t->getline(Timeout => 0, errmode => 'return');
114 return if (!defined($line));
122 if (defined($remoteglotconf::target)) {
123 if ($remoteglotconf::target =~ /^http:/) {
124 fetch_pgn($remoteglotconf::target);
126 $t->cmd("observe $remoteglotconf::target");
129 print "FICS ready.\n";
131 # Engine events have already been set up by Engine.pm.
135 my ($engine, $line, $primary) = @_;
137 return if $line =~ /(upper|lower)bound/;
139 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
140 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
141 if ($line =~ /^info/) {
142 my (@infos) = split / /, $line;
145 parse_infos($engine, @infos);
147 if ($line =~ /^id/) {
148 my (@ids) = split / /, $line;
151 parse_ids($engine, @ids);
153 if ($line =~ /^bestmove/) {
155 return if (!$remoteglotconf::uci_assume_full_compliance);
156 if (defined($pos_waiting)) {
157 uciprint($engine, "position fen " . $pos_waiting->fen());
158 uciprint($engine, "go infinite");
160 $pos_calculating = $pos_waiting;
161 $pos_waiting = undef;
164 $engine2->{'info'} = {};
165 my $pos = $pos_waiting // $pos_calculating;
166 uciprint($engine2, "position fen " . $pos->fen());
167 uciprint($engine2, "go infinite");
168 $pos_calculating_second_engine = $pos;
174 my $getting_movelist = 0;
175 my $pos_for_movelist = undef;
176 my @uci_movelist = ();
177 my @pretty_movelist = ();
181 if ($line =~ /^<12> /) {
182 handle_position(Position->new($line));
185 if ($line =~ /^Movelist for game /) {
186 my $pos = $pos_waiting // $pos_calculating;
189 @pretty_movelist = ();
190 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
191 $getting_movelist = 1;
194 if ($getting_movelist &&
195 $line =~ /^\s* \d+\. \s+ # move number
196 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
197 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
201 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
202 push @uci_movelist, $uci_move;
203 push @pretty_movelist, $1;
206 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
207 push @uci_movelist, $uci_move;
208 push @pretty_movelist, $2;
212 warn "Error when getting FICS move history: $@";
213 $getting_movelist = 0;
216 if ($getting_movelist &&
217 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
219 for my $pos ($pos_waiting, $pos_calculating) {
220 next if (!defined($pos));
221 if ($pos->fen() eq $pos_for_movelist->fen()) {
222 $pos->{'pretty_history'} = \@pretty_movelist;
225 $getting_movelist = 0;
227 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
228 my ($who, $msg) = ($1, $2);
230 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
232 if ($msg =~ /^fics (.*?)$/) {
233 $t->cmd("tell $who Executing '$1' on FICS.");
235 } elsif ($msg =~ /^uci (.*?)$/) {
236 $t->cmd("tell $who Sending '$1' to the engine.");
237 print { $engine->{'write'} } "$1\n";
238 } elsif ($msg =~ /^pgn (.*?)$/) {
240 $t->cmd("tell $who Starting to poll '$url'.");
242 } elsif ($msg =~ /^stoppgn$/) {
243 $t->cmd("tell $who Stopping poll.");
246 } elsif ($msg =~ /^quit$/) {
247 $t->cmd("tell $who Bye bye.");
250 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
253 #print "FICS: [$line]\n";
256 # Starts periodic fetching of PGNs from the given URL.
259 AnyEvent::HTTP::http_get($url, sub {
260 handle_pgn(@_, $url);
264 my ($last_pgn_white, $last_pgn_black);
265 my @last_pgn_uci_moves = ();
266 my $pgn_hysteresis_counter = 0;
269 my ($body, $header, $url) = @_;
271 if ($stop_pgn_fetch) {
277 my $pgn = Chess::PGN::Parse->new(undef, $body);
278 if (!defined($pgn) || !$pgn->read_game() || $body !~ /^\[/) {
279 warn "Error in parsing PGN from $url\n";
282 # Skip to the right game.
283 while (defined($remoteglotconf::pgn_filter) &&
284 !&$remoteglotconf::pgn_filter($pgn)) {
285 $pgn->read_game() or die "Out of games during filtering";
288 $pgn->parse_game({ save_comments => 'yes' });
289 my $pos = Position->start_pos($pgn->white, $pgn->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_col, $from_row, $to_col, $to_row, $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 $pos->{'result'} = $pgn->result;
304 $pos->{'pretty_history'} = \@repretty_moves;
306 extract_clock($pgn, $pos);
308 # Sometimes, PGNs lose a move or two for a short while,
309 # or people push out new ones non-atomically.
310 # Thus, if we PGN doesn't change names but becomes
311 # shorter, we mistrust it for a few seconds.
313 if (defined($last_pgn_white) && defined($last_pgn_black) &&
314 $last_pgn_white eq $pgn->white &&
315 $last_pgn_black eq $pgn->black &&
316 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
317 if (++$pgn_hysteresis_counter < 3) {
322 $last_pgn_white = $pgn->white;
323 $last_pgn_black = $pgn->black;
324 @last_pgn_uci_moves = @uci_moves;
325 $pgn_hysteresis_counter = 0;
326 handle_position($pos);
330 warn "Error in parsing moves from $url: $@\n";
334 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
339 sub handle_position {
341 find_clock_start($pos, $pos_calculating);
343 # if this is already in the queue, ignore it (just update the result)
344 if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen()) {
345 $pos_waiting->{'result'} = $pos->{'result'};
349 # if we're already chewing on this and there's nothing else in the queue,
351 if (!defined($pos_waiting) && defined($pos_calculating) &&
352 $pos->fen() eq $pos_calculating->fen()) {
353 $pos_calculating->{'result'} = $pos->{'result'};
357 # if we're already thinking on something, stop and wait for the engine
359 if (defined($pos_calculating)) {
360 # Store the final data we have for this position in the history,
361 # with the precise clock information we just got from the new
362 # position. (Historic positions store the clock at the end of
365 # Do not output anything new to the main analysis; that's
366 # going to be obsolete really soon.
367 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
368 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
369 delete $pos_calculating->{'white_clock_target'};
370 delete $pos_calculating->{'black_clock_target'};
373 if (!defined($pos_waiting)) {
374 uciprint($engine, "stop");
376 if ($remoteglotconf::uci_assume_full_compliance) {
379 uciprint($engine, "position fen " . $pos->fen());
380 uciprint($engine, "go infinite");
381 $pos_calculating = $pos;
384 # it's wrong just to give the FEN (the move history is useful,
385 # and per the UCI spec, we should really have sent "ucinewgame"),
387 uciprint($engine, "position fen " . $pos->fen());
388 uciprint($engine, "go infinite");
389 $pos_calculating = $pos;
392 if (defined($engine2)) {
393 if (defined($pos_calculating_second_engine)) {
394 uciprint($engine2, "stop");
396 uciprint($engine2, "position fen " . $pos->fen());
397 uciprint($engine2, "go infinite");
398 $pos_calculating_second_engine = $pos;
400 $engine2->{'info'} = {};
403 $engine->{'info'} = {};
406 schedule_tb_lookup();
409 # Output a command every move to note that we're
410 # still paying attention -- this is a good tradeoff,
411 # since if no move has happened in the last half
412 # hour, the analysis/relay has most likely stopped
413 # and we should stop hogging server resources.
419 my ($engine, @x) = @_;
422 my $info = $engine->{'info'};
424 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
425 for my $i (0..$#x - 1) {
426 if ($x[$i] eq 'multipv') {
432 while (scalar @x > 0) {
433 if ($x[0] eq 'multipv') {
439 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
441 my $value = shift @x;
442 $info->{$key} = $value;
445 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
446 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
449 my $value = shift @x;
450 $info->{$key . $mpv} = $value;
453 if ($x[0] eq 'score') {
456 delete $info->{'score_cp' . $mpv};
457 delete $info->{'score_mate' . $mpv};
459 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
462 $info->{'score_cp' . $mpv} = shift @x;
463 } elsif ($x[0] eq 'mate') {
465 $info->{'score_mate' . $mpv} = shift @x;
473 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
476 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
480 #print "unknown info '$x[0]', trying to recover...\n";
482 die "Unknown info '" . join(',', @x) . "'";
488 my ($engine, @x) = @_;
490 while (scalar @x > 0) {
491 if ($x[0] eq 'name') {
492 my $value = join(' ', @x);
493 $engine->{'id'}{'author'} = $value;
502 sub prettyprint_pv_no_cache {
503 my ($board, @pvs) = @_;
505 if (scalar @pvs == 0 || !defined($pvs[0])) {
510 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
511 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
512 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
516 my ($pos, @pvs) = @_;
518 my $cachekey = join('', @pvs);
519 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
520 return @{$pos->{'prettyprint_cache'}{$cachekey}};
522 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
523 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
531 return if (!defined($pos_calculating));
533 # Don't update too often.
534 my $age = Time::HiRes::tv_interval($latest_update);
535 if ($age < $remoteglotconf::update_max_interval) {
536 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
537 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
541 my $info = $engine->{'info'};
544 # If we have tablebase data from a previous lookup, replace the
545 # engine data with the data from the tablebase.
547 my $fen = $pos_calculating->fen();
548 if (exists($tb_cache{$fen})) {
549 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
550 delete $info->{$key . '1'};
551 delete $info->{$key};
553 $info->{'nodes'} = 0;
555 $info->{'depth'} = 0;
556 $info->{'seldepth'} = 0;
557 $info->{'tbhits'} = 0;
559 my $t = $tb_cache{$fen};
561 my $matelen = int((1 + $t->{'score'}) / 2);
562 if ($t->{'result'} eq '1/2-1/2') {
563 $info->{'score_cp'} = 0;
564 } elsif ($t->{'result'} eq '1-0') {
565 if ($pos_calculating->{'toplay'} eq 'B') {
566 $info->{'score_mate'} = -$matelen;
568 $info->{'score_mate'} = $matelen;
571 if ($pos_calculating->{'toplay'} eq 'B') {
572 $info->{'score_mate'} = $matelen;
574 $info->{'score_mate'} = -$matelen;
578 $info->{'tablebase'} = 1;
580 $info->{'tablebase'} = 0;
584 # Some programs _always_ report MultiPV, even with only one PV.
585 # In this case, we simply use that data as if MultiPV was never
588 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
589 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
590 if (exists($info->{$key . '1'})) {
591 $info->{$key} = $info->{$key . '1'};
597 # Check the PVs first. if they're invalid, just wait, as our data
598 # is most likely out of sync. This isn't a very good solution, as
599 # it can frequently miss stuff, but it's good enough for most users.
603 if (exists($info->{'pv'})) {
604 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
608 while (exists($info->{'pv' . $mpv})) {
609 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
614 $engine->{'info'} = {};
620 $latest_update = [Time::HiRes::gettimeofday];
624 my $info = $engine->{'info'};
625 my $id = $engine->{'id'};
627 my $text = 'Analysis';
628 if ($pos_calculating->{'last_move'} ne 'none') {
629 if ($pos_calculating->{'toplay'} eq 'W') {
630 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
632 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
634 if (exists($id->{'name'})) {
639 if (exists($id->{'name'})) {
640 $text .= " by $id->{'name'}:\n\n";
645 return unless (exists($pos_calculating->{'board'}));
647 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
650 while (exists($info->{'pv' . $mpv})) {
651 $text .= sprintf " PV%2u", $mpv;
652 my $score = short_score($info, $pos_calculating, $mpv);
653 $text .= " ($score)" if (defined($score));
656 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
657 if ($info->{'tbhits' . $mpv} == 1) {
658 $tbhits = ", 1 tbhit";
660 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
664 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
665 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
666 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
670 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
676 my $score = long_score($info, $pos_calculating, '');
677 $text .= " $score\n" if defined($score);
678 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
681 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
682 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
683 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
685 if (exists($info->{'seldepth'})) {
686 $text .= sprintf " (%u selective)", $info->{'seldepth'};
688 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
689 if ($info->{'tbhits'} == 1) {
690 $text .= ", one Syzygy hit";
692 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
698 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
700 my @refutation_lines = ();
701 if (defined($engine2)) {
702 for (my $mpv = 1; $mpv < 500; ++$mpv) {
703 my $info = $engine2->{'info'};
704 last if (!exists($info->{'pv' . $mpv}));
706 my $pv = $info->{'pv' . $mpv};
708 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
709 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
710 if (scalar @pretty_pv > 5) {
711 @pretty_pv = @pretty_pv[0..4];
712 push @pretty_pv, "...";
714 my $key = $pretty_move;
715 my $line = sprintf(" %-6s %6s %3s %s",
717 short_score($info, $pos_calculating_second_engine, $mpv),
718 "d" . $info->{'depth' . $mpv},
719 join(', ', @pretty_pv));
720 push @refutation_lines, [ $key, $line ];
725 if ($#refutation_lines >= 0) {
726 $text .= "Shallow search of all legal moves:\n\n";
727 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
728 $text .= $line->[1] . "\n";
733 if ($last_text ne $text) {
734 print "
\e[H
\e[2J"; # clear the screen
741 my $historic_json_only = shift;
742 my $info = $engine->{'info'};
745 $json->{'position'} = $pos_calculating->to_json_hash();
746 $json->{'engine'} = $engine->{'id'};
747 if (defined($remoteglotconf::engine_url)) {
748 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
750 if (defined($remoteglotconf::engine_details)) {
751 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
753 if (defined($remoteglotconf::move_source)) {
754 $json->{'move_source'} = $remoteglotconf::move_source;
756 if (defined($remoteglotconf::move_source_url)) {
757 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
759 $json->{'score'} = long_score($info, $pos_calculating, '');
760 $json->{'short_score'} = short_score($info, $pos_calculating, '');
761 $json->{'plot_score'} = plot_score($info, $pos_calculating, '');
762 $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
764 $json->{'nodes'} = $info->{'nodes'};
765 $json->{'nps'} = $info->{'nps'};
766 $json->{'depth'} = $info->{'depth'};
767 $json->{'tbhits'} = $info->{'tbhits'};
768 $json->{'seldepth'} = $info->{'seldepth'};
769 $json->{'tablebase'} = $info->{'tablebase'};
771 $json->{'pv_uci'} = $info->{'pv'}; # Still needs to be there for the JS to calculate arrows; only for the primary PV, though!
772 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
774 my %refutation_lines = ();
775 my @refutation_lines = ();
776 if (defined($engine2)) {
777 for (my $mpv = 1; $mpv < 500; ++$mpv) {
778 my $info = $engine2->{'info'};
779 my $pretty_move = "";
781 last if (!exists($info->{'pv' . $mpv}));
784 my $pv = $info->{'pv' . $mpv};
785 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
786 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
787 $refutation_lines{$pv->[0]} = {
788 sort_key => $pretty_move,
789 depth => $info->{'depth' . $mpv},
790 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
791 pretty_score => short_score($info, $pos_calculating, $mpv),
792 pretty_move => $pretty_move,
793 pv_pretty => \@pretty_pv,
798 $json->{'refutation_lines'} = \%refutation_lines;
800 # Piece together historic score information, to the degree we have it.
801 if (!$historic_json_only && exists($pos_calculating->{'pretty_history'})) {
802 my %score_history = ();
804 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
805 my $pos = Position->start_pos('white', 'black');
806 my $halfmove_num = 0;
807 for my $move (@{$pos_calculating->{'pretty_history'}}) {
808 my $id = id_for_pos($pos, $halfmove_num);
809 my $ref = $dbh->selectrow_hashref($q, undef, $id);
811 $score_history{$halfmove_num} = [
812 $ref->{'plot_score'},
813 $ref->{'short_score'}
817 ($pos) = $pos->make_pretty_move($move);
821 # If at any point we are missing 10 consecutive moves,
822 # truncate the history there. This is so we don't get into
823 # a situation where we e.g. start analyzing at move 45,
824 # but we have analysis for 1. e4 from some completely different game
825 # and thus show a huge hole.
826 my $consecutive_missing = 0;
827 my $truncate_until = 0;
828 for (my $i = $halfmove_num; $i --> 0; ) {
829 if ($consecutive_missing >= 10) {
830 delete $score_history{$i};
833 if (exists($score_history{$i})) {
834 $consecutive_missing = 0;
836 ++$consecutive_missing;
840 $json->{'score_history'} = \%score_history;
843 # Give out a list of other games going on. (Empty is fine.)
844 if (!$historic_json_only) {
847 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
849 while (my $ref = $q->fetchrow_hashref) {
851 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
852 my $other_game_json = JSON::XS::decode_json($other_game_contents);
854 die "Missing position" if (!exists($other_game_json->{'position'}));
855 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
856 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
860 name => "$white–$black",
865 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
869 if (scalar @games > 0) {
870 $json->{'games'} = \@games;
874 my $json_enc = JSON::XS->new;
875 $json_enc->canonical(1);
876 my $encoded = $json_enc->encode($json);
877 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
878 (defined($last_written_json) && $last_written_json eq $encoded)) {
879 atomic_set_contents($remoteglotconf::json_output, $encoded);
880 $last_written_json = $encoded;
883 if (exists($pos_calculating->{'pretty_history'}) &&
884 defined($remoteglotconf::json_history_dir)) {
885 my $id = id_for_pos($pos_calculating);
886 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
888 # Overwrite old analysis (assuming it exists at all) if we're
889 # using a different engine, or if we've calculated deeper.
890 # nodes is used as a tiebreaker. Don't bother about Multi-PV
891 # data; it's not that important.
892 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
893 my $new_depth = $json->{'depth'} // 0;
894 my $new_nodes = $json->{'nodes'} // 0;
895 if (!defined($old_engine) ||
896 $old_engine ne $json->{'engine'}{'name'} ||
897 $new_depth > $old_depth ||
898 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
899 atomic_set_contents($filename, $encoded);
900 if (defined($json->{'plot_score'})) {
901 local $dbh->{AutoCommit} = 0;
902 $dbh->do('DELETE FROM scores WHERE id=?', undef, $id);
903 $dbh->do('INSERT INTO scores (id, plot_score, short_score, engine, depth, nodes) VALUES (?,?,?,?,?,?)', undef,
904 $id, $json->{'plot_score'}, $json->{'short_score'},
905 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
912 sub atomic_set_contents {
913 my ($filename, $contents) = @_;
915 open my $fh, ">", $filename . ".tmp"
919 rename($filename . ".tmp", $filename);
923 my ($pos, $halfmove_num) = @_;
925 $halfmove_num //= scalar @{$pos->{'pretty_history'}};
926 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
927 return "move$halfmove_num-$fen";
930 sub get_json_analysis_stats {
932 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
934 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
941 my ($engine, $msg) = @_;
942 $engine->print($msg);
943 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
947 my ($info, $pos, $mpv) = @_;
949 my $invert = ($pos->{'toplay'} eq 'B');
950 if (defined($info->{'score_mate' . $mpv})) {
952 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
954 return sprintf "M%3d", $info->{'score_mate' . $mpv};
957 if (exists($info->{'score_cp' . $mpv})) {
958 my $score = $info->{'score_cp' . $mpv} * 0.01;
960 if ($info->{'tablebase'}) {
969 return sprintf "%+5.2f", $score;
977 my ($info, $pos, $mpv, $invert) = @_;
979 if (defined($info->{'score_mate' . $mpv})) {
980 my $mate = $info->{'score_mate' . $mpv};
984 $score = 99999 - $mate;
986 # Side to move is getting mated (note the double negative for $mate)
987 $score = -99999 - $mate;
994 if (exists($info->{'score_cp' . $mpv})) {
995 my $score = $info->{'score_cp' . $mpv};
1007 my ($info, $pos, $mpv) = @_;
1009 if (defined($info->{'score_mate' . $mpv})) {
1010 my $mate = $info->{'score_mate' . $mpv};
1011 if ($pos->{'toplay'} eq 'B') {
1015 return sprintf "White mates in %u", $mate;
1017 return sprintf "Black mates in %u", -$mate;
1020 if (exists($info->{'score_cp' . $mpv})) {
1021 my $score = $info->{'score_cp' . $mpv} * 0.01;
1023 if ($info->{'tablebase'}) {
1024 return "Theoretical draw";
1026 return "Score: 0.00";
1029 if ($pos->{'toplay'} eq 'B') {
1032 return sprintf "Score: %+5.2f", $score;
1039 # For graphs; a single number in centipawns, capped at +/- 500.
1041 my ($info, $pos, $mpv) = @_;
1043 my $invert = ($pos->{'toplay'} eq 'B');
1044 if (defined($info->{'score_mate' . $mpv})) {
1045 my $mate = $info->{'score_mate' . $mpv};
1055 if (exists($info->{'score_cp' . $mpv})) {
1056 my $score = $info->{'score_cp' . $mpv};
1060 $score = 500 if ($score > 500);
1061 $score = -500 if ($score < -500);
1069 my %book_cache = ();
1071 my ($fen, $board, $toplay) = @_;
1073 if (exists($book_cache{$fen})) {
1074 return $book_cache{$fen};
1077 my $ret = `./booklook $fen`;
1078 return "" if ($ret =~ /Not found/ || $ret eq '');
1082 for my $m (split /\n/, $ret) {
1083 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1087 $pmove = '(current)';
1089 ($pmove) = prettyprint_pv_no_cache($board, $move);
1090 $pmove .= $annotation;
1094 if ($toplay eq 'W') {
1095 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1097 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1099 my $n = $win + $draw + $lose;
1105 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1108 push @moves, [ $pmove, $n, $percent, $rating ];
1111 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1113 my $text = "Book moves:\n\n Perf. N Rating\n\n";
1114 for my $m (@moves) {
1115 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1122 my ($pgn, $pos) = @_;
1124 # Look for extended PGN clock tags.
1125 my $tags = $pgn->tags;
1126 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1127 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1128 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1132 # Look for TCEC-style time comments.
1133 my $moves = $pgn->moves;
1134 my $comments = $pgn->comments;
1135 my $last_black_move = int((scalar @$moves) / 2);
1136 my $last_white_move = int((1 + scalar @$moves) / 2);
1138 my $black_key = $last_black_move . "b";
1139 my $white_key = $last_white_move . "w";
1141 if (exists($comments->{$white_key}) &&
1142 exists($comments->{$black_key}) &&
1143 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1144 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1145 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1146 $pos->{'white_clock'} = hms_to_sec($1);
1147 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1148 $pos->{'black_clock'} = hms_to_sec($1);
1152 delete $pos->{'white_clock'};
1153 delete $pos->{'black_clock'};
1158 return undef if (!defined($hms));
1159 $hms =~ /(\d+):(\d+):(\d+)/;
1160 return $1 * 3600 + $2 * 60 + $3;
1163 sub find_clock_start {
1164 my ($pos, $prev_pos) = @_;
1166 # If the game is over, the clock is stopped.
1167 if (exists($pos->{'result'}) &&
1168 ($pos->{'result'} eq '1-0' ||
1169 $pos->{'result'} eq '1/2-1/2' ||
1170 $pos->{'result'} eq '0-1')) {
1174 # When we don't have any moves, we assume the clock hasn't started yet.
1175 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1176 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1177 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1182 # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1183 # The history is needed for id_for_pos.
1184 if (!exists($pos->{'pretty_history'})) {
1188 my $id = id_for_pos($pos);
1189 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=?', undef, $id);
1190 if (defined($clock_info)) {
1191 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1192 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1193 if ($pos->{'toplay'} eq 'W') {
1194 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1196 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1201 # OK, we haven't seen this position before, so we assume the move
1202 # happened right now.
1204 # See if we should do our own clock management (ie., clock information
1205 # is spurious or non-existent).
1206 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1207 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1208 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1209 if (defined($prev_pos->{'white_clock_target'})) {
1210 $wc = $prev_pos->{'white_clock_target'} - time;
1212 if (defined($prev_pos->{'black_clock_target'})) {
1213 $bc = $prev_pos->{'black_clock_target'} - time;
1215 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1216 $pos->{'white_clock'} = $wc;
1217 $pos->{'black_clock'} = $bc;
1220 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1221 if (!exists($pos->{$key})) {
1222 # No clock information.
1225 my $time_left = $pos->{$key};
1226 my ($white_clock_target, $black_clock_target);
1227 if ($pos->{'toplay'} eq 'W') {
1228 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1230 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1232 local $dbh->{AutoCommit} = 0;
1233 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1234 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1235 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1239 sub schedule_tb_lookup {
1240 return if (!defined($remoteglotconf::tb_serial_key));
1241 my $pos = $pos_waiting // $pos_calculating;
1242 return if (exists($tb_cache{$pos->fen()}));
1244 # If there's more than seven pieces, there's not going to be an answer,
1246 return if ($pos->num_pieces() > 7);
1248 # Max one at a time. If it's still relevant when it returns,
1249 # schedule_tb_lookup() will be called again.
1250 return if ($tb_lookup_running);
1252 $tb_lookup_running = 1;
1253 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
1254 $remoteglotconf::tb_serial_key .
1255 '&auth.password=aquarium&type=0&fen=' .
1256 URI::Escape::uri_escape($pos->fen());
1257 print TBLOG "Downloading $url...\n";
1258 AnyEvent::HTTP::http_get($url, sub {
1259 handle_tb_lookup_return(@_, $pos, $pos->fen());
1263 sub handle_tb_lookup_return {
1264 my ($body, $header, $pos, $fen) = @_;
1265 print TBLOG "Response for [$fen]:\n";
1266 print TBLOG $header . "\n\n";
1267 print TBLOG $body . "\n\n";
1269 my $response = JSON::XS::decode_json($body);
1270 if ($response->{'ErrorCode'} != 0) {
1271 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1273 my $state = $response->{'Response'}{'StateString'};
1274 if ($state eq 'COMPLETE') {
1275 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1276 if (!defined($pgn) || !$pgn->read_game()) {
1277 warn "Error in parsing PGN\n";
1279 $pgn->quick_parse_game;
1281 my $moves = $pgn->moves;
1283 for my $move (@$moves) {
1285 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1286 push @uci_moves, $uci_move;
1289 result => $pgn->result,
1291 score => $response->{'Response'}{'Score'},
1295 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1296 # Try again in a second. Note that if we have changed
1297 # position in the meantime, we might query a completely
1298 # different position! But that's fine.
1300 die "Unknown response state " . $state;
1303 # Wait a second before we schedule another one.
1304 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1305 $tb_lookup_running = 0;
1306 schedule_tb_lookup();
1310 warn "Error in tablebase lookup: $@";
1312 # Don't try this one again, but don't block new lookups either.
1313 $tb_lookup_running = 0;
1318 my ($cmdline, $tag, $cb) = @_;
1319 return undef if (!defined($cmdline));
1320 return Engine->open($cmdline, $tag, $cb);
1323 sub col_letter_to_num {
1324 return ord(shift) - ord('a');
1327 sub row_letter_to_num {
1328 return 7 - (ord(shift) - ord('1'));
1331 sub parse_uci_move {
1333 my $from_col = col_letter_to_num(substr($move, 0, 1));
1334 my $from_row = row_letter_to_num(substr($move, 1, 1));
1335 my $to_col = col_letter_to_num(substr($move, 2, 1));
1336 my $to_row = row_letter_to_num(substr($move, 3, 1));
1337 my $promo = substr($move, 4, 1);
1338 return ($from_col, $from_row, $to_col, $to_row, $promo);