4 # remoteglot - Connects an abitrary UCI-speaking engine to a (live) PGN,
5 # for live analysis of relayed games.
7 # Copyright 2007 Steinar H. Gunderson <steinar+remoteglot@gunderson.no>
8 # Licensed under the GNU General Public License, version 2.
14 use Chess::PGN::Parse;
23 require 'Position.pm';
31 my $latest_update = undef;
32 my $output_timer = undef;
33 my $http_timer = undef;
34 my $stop_pgn_fetch = 0;
35 my $tb_retry_timer = undef;
36 my $tb_lookup_running = 0;
37 my $last_written_json = undef;
39 # Persisted so we can restart.
40 # TODO: Figure out an appropriate way to deal with database restarts
41 # and/or Postgres going away entirely.
42 my $dbh = DBI->connect($remoteglotconf::dbistr, $remoteglotconf::dbiuser, $remoteglotconf::dbipass)
44 $dbh->{RaiseError} = 1;
48 open(UCILOG, ">ucilog.txt")
49 or die "ucilog.txt: $!";
50 print UCILOG "Log starting.\n";
54 open(TBLOG, ">tblog.txt")
55 or die "tblog.txt: $!";
56 print TBLOG "Log starting.\n";
61 umask 0022; # analysis.json should not be served to users.
63 # open the chess engine
64 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
65 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
68 my ($pos_calculating, $pos_calculating_second_engine);
70 # If not undef, we've started calculating this position but haven't ever given out
71 # any analysis for it, so we're on a forced timer to do so.
72 my $pos_calculating_started = undef;
74 # If not undef, we've output this position, but without a main PV, so we're on
75 # _another_ forced timer to do so.
76 my $pos_pv_started = undef;
77 my $last_output_had_pv = 0;
79 setoptions($engine, \%remoteglotconf::engine_config);
80 uciprint($engine, "ucinewgame");
82 if (defined($engine2)) {
83 setoptions($engine2, \%remoteglotconf::engine2_config);
84 uciprint($engine2, "setoption name MultiPV value 500");
85 uciprint($engine2, "ucinewgame");
88 print "Chess engine ready.\n";
90 if (defined($remoteglotconf::target)) {
91 if ($remoteglotconf::target =~ /^(?:\/|https?:)/) {
92 fetch_pgn($remoteglotconf::target);
96 # Engine events have already been set up by Engine.pm.
100 my ($engine, $line, $primary) = @_;
102 return if $line =~ /(upper|lower)bound/;
104 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
105 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
107 # If we've sent a stop command, gobble up lines until we see bestmove.
108 return if ($engine->{'stopping'} && $line !~ /^bestmove/);
109 $engine->{'stopping'} = 0;
111 if ($line =~ /^info/ && $line !~ / cluster /) {
112 my (@infos) = split / /, $line;
115 parse_infos($engine, @infos);
117 if ($line =~ /^id/) {
118 my (@ids) = split / /, $line;
121 parse_ids($engine, @ids);
126 my $getting_movelist = 0;
127 my $pos_for_movelist = undef;
128 my @uci_movelist = ();
129 my @pretty_movelist = ();
131 # Starts periodic fetching of PGNs from the given URL.
134 if ($url =~ m#^/#) { # Local file.
137 open my $fh, "<", $url
141 handle_pgn($pgn, '', $url);
145 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
150 AnyEvent::HTTP::http_get($url, sub {
151 handle_pgn(@_, $url);
156 my ($last_pgn_white, $last_pgn_black);
157 my @last_pgn_uci_moves = ();
158 my $pgn_hysteresis_counter = 0;
161 my ($body, $header, $url) = @_;
163 if ($stop_pgn_fetch) {
169 my $pgn = Chess::PGN::Parse->new(undef, $body);
170 if (!defined($pgn)) {
171 warn "Error in parsing PGN from $url [body='$body']\n";
172 } elsif (!$pgn->read_game()) {
173 warn "Error in reading PGN game from $url [body='$body']\n";
174 } elsif ($body !~ /^\[/) {
175 warn "Malformed PGN from $url [body='$body']\n";
178 # Skip to the right game.
179 while (defined($remoteglotconf::pgn_filter) &&
180 !&$remoteglotconf::pgn_filter($pgn)) {
181 $pgn->read_game() or die "Out of games during filtering";
184 $pgn->parse_game({ save_comments => 'yes' });
185 my $white = $pgn->white;
186 my $black = $pgn->black;
187 $white =~ s/,.*//; # Remove first name.
188 $black =~ s/,.*//; # Remove first name.
189 my $tags = $pgn->tags();
191 if (exists($tags->{'FEN'})) {
192 $pos = Position->from_fen($tags->{'FEN'});
193 $pos->{'last_move'} = 'none';
194 $pos->{'player_w'} = $white;
195 $pos->{'player_b'} = $black;
196 $pos->{'start_fen'} = $tags->{'FEN'};
198 $pos = Position->start_pos($white, $black);
200 if (exists($tags->{'Variant'}) &&
201 $tags->{'Variant'} =~ /960|fischer/i) {
202 $pos->{'chess960'} = 1;
204 $pos->{'chess960'} = 0;
206 my $moves = $pgn->moves;
208 my @repretty_moves = ();
209 for my $move (@$moves) {
210 my ($npos, $uci_move) = $pos->make_pretty_move($move);
211 push @uci_moves, $uci_move;
213 # Re-prettyprint the move.
214 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
215 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
216 push @repretty_moves, $pretty;
219 if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
220 $pos->{'result'} = $pgn->result;
223 my @extra_moves = ();
224 $pos = extend_from_manual_override($pos, \@repretty_moves, \@extra_moves);
225 extract_clock($pgn, $pos);
226 $pos->{'history'} = \@repretty_moves;
227 $pos->{'extra_moves'} = \@extra_moves;
229 # Sometimes, PGNs lose a move or two for a short while,
230 # or people push out new ones non-atomically.
231 # Thus, if we PGN doesn't change names but becomes
232 # shorter, we mistrust it for a few seconds.
234 if (defined($last_pgn_white) && defined($last_pgn_black) &&
235 $last_pgn_white eq $pgn->white &&
236 $last_pgn_black eq $pgn->black &&
237 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
238 if (++$pgn_hysteresis_counter < 3) {
243 $last_pgn_white = $pgn->white;
244 $last_pgn_black = $pgn->black;
245 @last_pgn_uci_moves = @uci_moves;
246 $pgn_hysteresis_counter = 0;
247 handle_position($pos);
251 warn "Error in parsing moves from $url: $@\n";
255 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
260 sub handle_position {
262 find_clock_start($pos, $pos_calculating);
264 # If we're already chewing on this and there's nothing else in the queue,
266 if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
267 $pos_calculating->{'result'} = $pos->{'result'};
268 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
269 $pos_calculating->{$key} //= $pos->{$key};
271 $pos_calculating->{'extra_moves'} = $pos->{'extra_moves'};
275 # If we're already thinking on something, stop and wait for the engine
277 if (defined($pos_calculating)) {
278 # Store the final data we have for this position in the history,
279 # with the precise clock information we just got from the new
280 # position. (Historic positions store the clock at the end of
283 # Do not output anything new to the main analysis; that's
284 # going to be obsolete really soon. (Exception: If we've never
285 # output anything for this move, ie., it didn't hit the 200ms
286 # limit, spit it out to the user anyway. It's probably a really
287 # fast blitz game or something, and it's good to show the moves
288 # as they come in even without great analysis.)
289 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
290 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
291 delete $pos_calculating->{'white_clock_target'};
292 delete $pos_calculating->{'black_clock_target'};
294 if (defined($pos_calculating_started)) {
299 $pos_calculating_started = [Time::HiRes::gettimeofday];
300 $pos_pv_started = undef;
302 # Ask the engine to stop; we will throw away its data until it
303 # sends us "bestmove", signaling the end of it.
304 $engine->{'stopping'} = 1;
305 uciprint($engine, "stop");
308 # It's wrong to just give the FEN (the move history is useful,
309 # and per the UCI spec, we should really have sent "ucinewgame"),
310 # but it's easier, and it works around a Stockfish repetition issue.
311 if ($engine->{'chess960'} != $pos->{'chess960'}) {
312 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
313 $engine->{'chess960'} = $pos->{'chess960'};
315 uciprint($engine, "position fen " . $pos->fen());
316 uciprint($engine, "go infinite");
317 $pos_calculating = $pos;
318 $pos_calculating_started = [Time::HiRes::gettimeofday];
319 $pos_pv_started = undef;
321 if (defined($engine2)) {
322 if (defined($pos_calculating_second_engine)) {
323 $engine2->{'stopping'} = 1;
324 uciprint($engine2, "stop");
326 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
327 uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
328 $engine2->{'chess960'} = $pos->{'chess960'};
330 uciprint($engine2, "position fen " . $pos->fen());
331 uciprint($engine2, "go infinite");
332 $pos_calculating_second_engine = $pos;
333 $engine2->{'info'} = {};
336 $engine->{'info'} = {};
341 my ($engine, @x) = @_;
344 my $info = $engine->{'info'};
346 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
347 for my $i (0..$#x - 1) {
348 if ($x[$i] eq 'multipv') {
354 while (scalar @x > 0) {
355 if ($x[0] eq 'multipv') {
361 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
363 my $value = shift @x;
364 $info->{$key} = $value;
367 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
368 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
371 my $value = shift @x;
372 $info->{$key . $mpv} = $value;
375 if ($x[0] eq 'score') {
378 delete $info->{'score_cp' . $mpv};
379 delete $info->{'score_mate' . $mpv};
380 delete $info->{'splicepos' . $mpv};
382 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
385 $info->{'score_cp' . $mpv} = shift @x;
386 } elsif ($x[0] eq 'mate') {
388 $info->{'score_mate' . $mpv} = shift @x;
396 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
399 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
403 #print "unknown info '$x[0]', trying to recover...\n";
405 die "Unknown info '" . join(',', @x) . "'";
411 my ($engine, @x) = @_;
413 while (scalar @x > 0) {
414 if ($x[0] eq 'name') {
415 my $value = join(' ', @x);
416 $engine->{'id'}{'author'} = $value;
425 sub prettyprint_pv_no_cache {
426 my ($board, @pvs) = @_;
428 if (scalar @pvs == 0 || !defined($pvs[0])) {
434 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
435 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
443 my ($pos, @pvs) = @_;
445 my $cachekey = join('', @pvs);
446 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
447 return @{$pos->{'prettyprint_cache'}{$cachekey}};
449 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
450 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
455 my %tbprobe_cache = ();
457 sub complete_using_tbprobe {
458 my ($pos, $info, $mpv) = @_;
460 # We need Fathom installed to do standalone TB probes.
461 return if (!defined($remoteglotconf::fathom_cmdline));
463 # If we already have a mate, don't bother; in some cases, it would even be
464 # better than a tablebase score.
465 return if defined($info->{'score_mate' . $mpv});
467 # If we have a draw or near-draw score, there's also not much interesting
468 # we could add from a tablebase. We only really want mates.
469 return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
471 # Run through the PV until we are at a 6-man position.
472 # TODO: We could in theory only have 5-man data.
473 my @pv = @{$info->{'pv' . $mpv}};
474 my $key = $pos->fen() . " " . join('', @pv);
477 if (exists($tbprobe_cache{$key})) {
478 my $c = $tbprobe_cache{$key};
479 @moves = @{$c->{'moves'}};
480 $splicepos = $c->{'splicepos'};
483 # Force doing at least one move of the PV.
484 my $move = shift @pv;
486 $pos = $pos->make_move(parse_uci_move($move));
489 while ($pos->num_pieces() > 7 && $#pv > -1) {
490 my $move = shift @pv;
492 $pos = $pos->make_move(parse_uci_move($move));
495 return if ($pos->num_pieces() > 7);
497 my $fen = $pos->fen();
498 my $pgn_text = `$remoteglotconf::fathom_cmdline "$fen"`;
499 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
500 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
501 $pgn->quick_parse_game;
503 # Splice the PV from the tablebase onto what we have so far.
504 $splicepos = scalar @moves;
505 for my $move (@{$pgn->moves}) {
506 last if $move eq '#';
507 last if $move eq '1-0';
508 last if $move eq '0-1';
509 last if $move eq '1/2-1/2';
511 ($pos, $uci_move) = $pos->make_pretty_move($move);
512 push @moves, $uci_move;
515 $tbprobe_cache{$key} = {
517 splicepos => $splicepos
521 $info->{'pv' . $mpv} = \@moves;
523 my $matelen = int((1 + scalar @moves) / 2);
524 if ((scalar @moves) % 2 == 0) {
525 $info->{'score_mate' . $mpv} = -$matelen;
527 $info->{'score_mate' . $mpv} = $matelen;
529 $info->{'splicepos' . $mpv} = $splicepos;
535 return if (!defined($pos_calculating));
537 my $info = $engine->{'info'};
539 # Don't update too often.
540 my $wait = $remoteglotconf::update_max_interval - Time::HiRes::tv_interval($latest_update);
541 if (defined($pos_calculating_started)) {
542 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_calculating_started);
543 $wait = $new_pos_wait if ($new_pos_wait < $wait);
545 if (!$last_output_had_pv && has_pv($info)) {
546 if (!defined($pos_pv_started)) {
547 $pos_pv_started = [Time::HiRes::gettimeofday];
549 # We just got initial PV, and we're in a hurry since we gave out a blank one earlier,
550 # so give us just 200ms more to increase the quality and then force a display.
551 my $new_pos_wait = $remoteglotconf::update_force_after_move - Time::HiRes::tv_interval($pos_pv_started);
552 $wait = $new_pos_wait if ($new_pos_wait < $wait);
555 $output_timer = AnyEvent->timer(after => $wait + 0.01, cb => \&output);
558 $pos_pv_started = undef;
560 # We're outputting something for this position now, so the special handling
561 # for new positions is off.
562 undef $pos_calculating_started;
565 # Some programs _always_ report MultiPV, even with only one PV.
566 # In this case, we simply use that data as if MultiPV was never
569 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
570 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits splicepos)) {
571 if (exists($info->{$key . '1'})) {
572 $info->{$key} = $info->{$key . '1'};
574 delete $info->{$key};
580 # Check the PVs first. if they're invalid, just wait, as our data
581 # is most likely out of sync. This isn't a very good solution, as
582 # it can frequently miss stuff, but it's good enough for most users.
586 if (exists($info->{'pv'})) {
587 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
591 while (exists($info->{'pv' . $mpv})) {
592 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
597 $engine->{'info'} = {};
601 # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
602 if (exists($info->{'pv'})) {
603 complete_using_tbprobe($pos_calculating, $info, '');
607 while (exists($info->{'pv' . $mpv})) {
608 complete_using_tbprobe($pos_calculating, $info, $mpv);
614 $latest_update = [Time::HiRes::gettimeofday];
615 $last_output_had_pv = has_pv($info);
620 return 1 if (exists($info->{'pv'}) && (scalar(@{$info->{'pv'}}) > 0));
621 return 1 if (exists($info->{'pv1'}) && (scalar(@{$info->{'pv1'}}) > 0));
626 my $info = $engine->{'info'};
627 my $id = $engine->{'id'};
629 my $text = 'Analysis';
630 if ($pos_calculating->{'last_move'} ne 'none') {
631 if ($pos_calculating->{'toplay'} eq 'W') {
632 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
634 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
636 if (exists($id->{'name'})) {
641 if (exists($id->{'name'})) {
642 $text .= " by $id->{'name'}:\n\n";
647 return unless (exists($pos_calculating->{'board'}));
649 my $extra_moves = $pos_calculating->{'extra_moves'};
650 if (defined($extra_moves) && scalar @$extra_moves > 0) {
651 $text .= " Manual move extensions: " . join(' ', @$extra_moves) . "\n";
654 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
657 while (exists($info->{'pv' . $mpv})) {
658 $text .= sprintf " PV%2u", $mpv;
659 my $score = short_score($info, $pos_calculating, $mpv);
660 $text .= " ($score)" if (defined($score));
663 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
664 if ($info->{'tbhits' . $mpv} == 1) {
665 $tbhits = ", 1 tbhit";
667 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
671 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
672 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
673 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
677 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
683 my $score = long_score($info, $pos_calculating, '');
684 $text .= " $score\n" if defined($score);
685 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
688 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
689 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
690 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
692 if (exists($info->{'seldepth'})) {
693 $text .= sprintf " (%u selective)", $info->{'seldepth'};
695 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
696 if ($info->{'tbhits'} == 1) {
697 $text .= ", one Syzygy hit";
699 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
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 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
712 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 my @grpc_backends = ();
759 if (defined($remoteglotconf::engine_grpc_backend)) {
760 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
762 if (defined($remoteglotconf::engine2_grpc_backend)) {
763 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
765 $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
766 if (defined($remoteglotconf::move_source)) {
767 $json->{'move_source'} = $remoteglotconf::move_source;
769 if (defined($remoteglotconf::move_source_url)) {
770 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
772 $json->{'score'} = score_digest($info, $pos_calculating, '');
774 $json->{'nodes'} = $info->{'nodes'};
775 $json->{'nps'} = $info->{'nps'};
776 $json->{'depth'} = $info->{'depth'};
777 $json->{'tbhits'} = $info->{'tbhits'};
778 $json->{'seldepth'} = $info->{'seldepth'};
779 $json->{'tablebase'} = $info->{'tablebase'};
780 $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
782 my %refutation_lines = ();
783 my @refutation_lines = ();
784 if (defined($engine2)) {
785 for (my $mpv = 1; $mpv < 500; ++$mpv) {
786 my $info = $engine2->{'info'};
787 my $pretty_move = "";
789 last if (!exists($info->{'pv' . $mpv}));
792 complete_using_tbprobe($pos_calculating, $info, $mpv);
793 my $pv = $info->{'pv' . $mpv};
794 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
795 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
796 $refutation_lines{$pretty_move} = {
797 depth => $info->{'depth' . $mpv},
798 score => score_digest($info, $pos_calculating, $mpv),
799 move => $pretty_move,
802 if (exists($info->{'splicepos' . $mpv})) {
803 $refutation_lines{$pretty_move}->{'splicepos'} = $info->{'splicepos' . $mpv};
808 $json->{'refutation_lines'} = \%refutation_lines;
810 # Piece together historic score information, to the degree we have it.
811 if (!$historic_json_only && exists($pos_calculating->{'history'})) {
812 my %score_history = ();
814 local $dbh->{AutoCommit} = 0;
815 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
817 if (exists($pos_calculating->{'start_fen'})) {
818 $pos = Position->from_fen($pos_calculating->{'start_fen'});
820 $pos = Position->start_pos('white', 'black');
822 $pos->{'chess960'} = $pos_calculating->{'chess960'};
823 my $halfmove_num = 0;
824 for my $move (@{$pos_calculating->{'history'}}) {
825 my $id = id_for_pos($pos, $halfmove_num);
826 my $ref = $dbh->selectrow_hashref($q, undef, $id);
828 $score_history{$halfmove_num} = [
829 $ref->{'score_type'},
830 $ref->{'score_value'}
834 ($pos) = $pos->make_pretty_move($move);
839 # If at any point we are missing 10 consecutive moves,
840 # truncate the history there. This is so we don't get into
841 # a situation where we e.g. start analyzing at move 45,
842 # but we have analysis for 1. e4 from some completely different game
843 # and thus show a huge hole.
844 my $consecutive_missing = 0;
845 my $truncate_until = 0;
846 for (my $i = $halfmove_num; $i --> 0; ) {
847 if ($consecutive_missing >= 10) {
848 delete $score_history{$i};
851 if (exists($score_history{$i})) {
852 $consecutive_missing = 0;
854 ++$consecutive_missing;
858 $json->{'score_history'} = \%score_history;
861 # Give out a list of other games going on. (Empty is fine.)
862 # TODO: Don't bother reading our own file, the data will be stale anyway.
863 if (!$historic_json_only) {
866 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
868 while (my $ref = $q->fetchrow_hashref) {
870 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
871 my $other_game_json = JSON::XS::decode_json($other_game_contents);
873 die "Missing position" if (!exists($other_game_json->{'position'}));
874 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
875 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
879 name => "$white–$black",
880 url => $ref->{'url'},
881 hashurl => $ref->{'hash_url'},
883 if (defined($other_game_json->{'position'}{'result'})) {
884 $game->{'result'} = $other_game_json->{'position'}{'result'};
886 $game->{'score'} = $other_game_json->{'score'};
891 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
895 if (scalar @games > 0) {
896 $json->{'games'} = \@games;
900 my $json_enc = JSON::XS->new;
901 $json_enc->canonical(1);
902 my $encoded = $json_enc->encode($json);
903 unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
904 (defined($last_written_json) && $last_written_json eq $encoded)) {
905 atomic_set_contents($remoteglotconf::json_output, $encoded);
906 $last_written_json = $encoded;
909 if (exists($pos_calculating->{'history'}) &&
910 defined($remoteglotconf::json_history_dir) && defined($json->{'engine'}{name})) {
911 my $id = id_for_pos($pos_calculating);
912 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
914 # Overwrite old analysis (assuming it exists at all) if we're
915 # using a different engine, or if we've calculated deeper.
916 # nodes is used as a tiebreaker. Don't bother about Multi-PV
917 # data; it's not that important.
918 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
919 my $new_depth = $json->{'depth'} // 0;
920 my $new_nodes = $json->{'nodes'} // 0;
921 if (!defined($old_engine) ||
922 $old_engine ne $json->{'engine'}{'name'} ||
923 $new_depth > $old_depth ||
924 ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
925 atomic_set_contents($filename, $encoded);
926 if (defined($json->{'score'})) {
927 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
928 ' ON CONFLICT (id) DO UPDATE SET ' .
929 ' score_type=EXCLUDED.score_type, ' .
930 ' score_value=EXCLUDED.score_value, ' .
931 ' engine=EXCLUDED.engine, ' .
932 ' depth=EXCLUDED.depth, ' .
933 ' nodes=EXCLUDED.nodes',
935 $id, $json->{'score'}[0], $json->{'score'}[1],
936 $json->{'engine'}{'name'}, $new_depth, $new_nodes);
942 sub atomic_set_contents {
943 my ($filename, $contents) = @_;
945 open my $fh, ">", $filename . ".tmp"
949 rename($filename . ".tmp", $filename);
953 my ($pos, $halfmove_num) = @_;
955 $halfmove_num //= scalar @{$pos->{'history'}};
956 (my $fen = $pos->fen()) =~ tr,/ ,-_,;
957 return "move$halfmove_num-$fen";
960 sub get_json_analysis_stats {
962 my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
964 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
971 my ($engine, $msg) = @_;
972 $engine->print($msg);
973 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
977 my ($info, $pos, $mpv) = @_;
979 my $invert = ($pos->{'toplay'} eq 'B');
980 if (defined($info->{'score_mate' . $mpv})) {
982 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
984 return sprintf "M%3d", $info->{'score_mate' . $mpv};
987 if (exists($info->{'score_cp' . $mpv})) {
988 my $score = $info->{'score_cp' . $mpv} * 0.01;
990 if ($info->{'tablebase'}) {
999 return sprintf "%+5.2f", $score;
1006 # Sufficient for computing long_score, short_score, plot_score and
1007 # (with side-to-play information) score_sort_key.
1009 my ($info, $pos, $mpv) = @_;
1011 if (defined($info->{'score_mate' . $mpv})) {
1012 my $mate = $info->{'score_mate' . $mpv};
1013 if ($pos->{'toplay'} eq 'B') {
1016 if (exists($info->{'splicepos' . $mpv})) {
1017 my $sp = $info->{'splicepos' . $mpv};
1025 return ['M', $mate];
1026 } elsif ($mate < 0) {
1027 return ['m', -$mate];
1028 } elsif ($pos->{'toplay'} eq 'B') {
1035 if (exists($info->{'score_cp' . $mpv})) {
1036 my $score = $info->{'score_cp' . $mpv};
1037 if ($pos->{'toplay'} eq 'B') {
1040 if ($score == 0 && $info->{'tablebase'}) {
1041 return ['d', undef];
1043 return ['cp', int($score)];
1052 my ($info, $pos, $mpv) = @_;
1054 if (defined($info->{'score_mate' . $mpv})) {
1055 my $mate = $info->{'score_mate' . $mpv};
1056 if ($pos->{'toplay'} eq 'B') {
1059 if (exists($info->{'splicepos' . $mpv})) {
1060 my $sp = $info->{'splicepos' . $mpv};
1062 return sprintf "White wins in %u", int(($sp + 1) * 0.5);
1064 return sprintf "Black wins in %u", int(($sp + 1) * 0.5);
1068 return sprintf "White mates in %u", $mate;
1070 return sprintf "Black mates in %u", -$mate;
1074 if (exists($info->{'score_cp' . $mpv})) {
1075 my $score = $info->{'score_cp' . $mpv} * 0.01;
1077 if ($info->{'tablebase'}) {
1078 return "Theoretical draw";
1080 return "Score: 0.00";
1083 if ($pos->{'toplay'} eq 'B') {
1086 return sprintf "Score: %+5.2f", $score;
1093 # For graphs; a single number in centipawns, capped at +/- 500.
1095 my ($info, $pos, $mpv) = @_;
1097 my $invert = ($pos->{'toplay'} eq 'B');
1098 if (defined($info->{'score_mate' . $mpv})) {
1099 my $mate = $info->{'score_mate' . $mpv};
1109 if (exists($info->{'score_cp' . $mpv})) {
1110 my $score = $info->{'score_cp' . $mpv};
1114 $score = 500 if ($score > 500);
1115 $score = -500 if ($score < -500);
1123 sub extend_from_manual_override {
1124 my ($pos, $moves, $extra_moves) = @_;
1126 my $q = $dbh->prepare('SELECT next_move FROM game_extensions WHERE fen=? AND history=? AND player_w=? AND player_b=? AND (CURRENT_TIMESTAMP - ts) < INTERVAL \'1 hour\'');
1128 my $player_w = $pos->{'player_w'};
1129 my $player_b = $pos->{'player_b'};
1130 if ($player_w =~ /^base64:(.*)$/) {
1131 $player_w = MIME::Base64::decode_base64($1);
1133 if ($player_b =~ /^base64:(.*)$/) {
1134 $player_b = MIME::Base64::decode_base64($1);
1136 #use Data::Dumper; print Dumper([$pos->fen(), JSON::XS::encode_json($moves), $player_w, $player_b]);
1137 $q->execute($pos->fen(), JSON::XS::encode_json($moves), $player_w, $player_b);
1138 my $ref = $q->fetchrow_hashref;
1139 if (defined($ref)) {
1140 my $move = $ref->{'next_move'};
1141 ($pos) = $pos->make_pretty_move($move);
1142 push @$moves, $move;
1143 push @$extra_moves, $move;
1152 my ($pgn, $pos) = @_;
1154 # Look for extended PGN clock tags.
1155 my $tags = $pgn->tags;
1156 if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1157 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1158 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1162 # Look for TCEC-style time comments.
1163 my $moves = $pgn->moves;
1164 my $comments = $pgn->comments;
1165 my $last_black_move = int((scalar @$moves) / 2);
1166 my $last_white_move = int((1 + scalar @$moves) / 2);
1168 my $black_key = $last_black_move . "b";
1169 my $white_key = $last_white_move . "w";
1171 if (exists($comments->{$white_key}) &&
1172 exists($comments->{$black_key}) &&
1173 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1174 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1175 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1176 $pos->{'white_clock'} = hms_to_sec($1);
1177 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1178 $pos->{'black_clock'} = hms_to_sec($1);
1182 delete $pos->{'white_clock'};
1183 delete $pos->{'black_clock'};
1188 return undef if (!defined($hms));
1189 $hms =~ /(\d+):(\d+):(\d+)/;
1190 return $1 * 3600 + $2 * 60 + $3;
1193 sub find_clock_start {
1194 my ($pos, $prev_pos) = @_;
1196 # If the game is over, the clock is stopped.
1197 if (exists($pos->{'result'}) &&
1198 ($pos->{'result'} eq '1-0' ||
1199 $pos->{'result'} eq '1/2-1/2' ||
1200 $pos->{'result'} eq '0-1')) {
1204 # When we don't have any moves, we assume the clock hasn't started yet.
1205 if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1206 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1207 &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1212 # The history is needed for id_for_pos.
1213 if (!exists($pos->{'history'})) {
1217 my $id = id_for_pos($pos);
1218 my $clock_info = $dbh->selectrow_hashref('SELECT * FROM clock_info WHERE id=? AND COALESCE(white_clock_target, black_clock_target) >= EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - INTERVAL \'1 day\'));', undef, $id);
1219 if (defined($clock_info)) {
1220 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1221 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1222 if ($pos->{'toplay'} eq 'W') {
1223 $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1225 $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1230 # OK, we haven't seen this position before, so we assume the move
1231 # happened right now.
1233 # See if we should do our own clock management (ie., clock information
1234 # is spurious or non-existent).
1235 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1236 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1237 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1238 if (defined($prev_pos->{'white_clock_target'})) {
1239 $wc = $prev_pos->{'white_clock_target'} - time;
1241 if (defined($prev_pos->{'black_clock_target'})) {
1242 $bc = $prev_pos->{'black_clock_target'} - time;
1244 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1245 $pos->{'white_clock'} = $wc;
1246 $pos->{'black_clock'} = $bc;
1249 my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1250 if (!exists($pos->{$key})) {
1251 # No clock information.
1254 my $time_left = $pos->{$key};
1255 my ($white_clock_target, $black_clock_target);
1256 if ($pos->{'toplay'} eq 'W') {
1257 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1259 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1261 local $dbh->{AutoCommit} = 0;
1262 $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1263 $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1264 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1269 my ($cmdline, $tag, $cb) = @_;
1270 return undef if (!defined($cmdline));
1271 return Engine->open($cmdline, $tag, $cb);
1274 sub col_letter_to_num {
1275 return ord(shift) - ord('a');
1278 sub row_letter_to_num {
1279 return 7 - (ord(shift) - ord('1'));
1282 sub parse_uci_move {
1284 my $from_col = col_letter_to_num(substr($move, 0, 1));
1285 my $from_row = row_letter_to_num(substr($move, 1, 1));
1286 my $to_col = col_letter_to_num(substr($move, 2, 1));
1287 my $to_row = row_letter_to_num(substr($move, 3, 1));
1288 my $promo = substr($move, 4, 1);
1289 return ($from_row, $from_col, $to_row, $to_col, $promo);
1293 my ($engine, $config) = @_;
1294 uciprint($engine, "setoption name UCI_AnalyseMode value true");
1295 uciprint($engine, "setoption name Analysis Contempt value Off");
1296 if (exists($config->{'Threads'})) { # Threads first, because clearing hash can be multithreaded then.
1297 uciprint($engine, "setoption name Threads value " . $config->{'Threads'});
1299 while (my ($key, $value) = each %$config) {
1300 next if $key eq 'Threads';
1301 uciprint($engine, "setoption name $key value $value");