]> git.sesse.net Git - remoteglot/blob - remoteglot.pl
Add pickup of games from old history.
[remoteglot] / remoteglot.pl
1 #! /usr/bin/perl
2
3 #
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.)
7 #
8 # Copyright 2007 Steinar H. Gunderson <steinar+remoteglot@gunderson.no>
9 # Licensed under the GNU General Public License, version 2.
10 #
11
12 use AnyEvent;
13 use AnyEvent::Handle;
14 use AnyEvent::HTTP;
15 use Chess::PGN::Parse;
16 use EV;
17 use Net::Telnet;
18 use File::Slurp;
19 use IPC::Open2;
20 use Time::HiRes;
21 use JSON::XS;
22 use URI::Escape;
23 use DBI;
24 use DBD::Pg;
25 require 'Position.pm';
26 require 'Engine.pm';
27 require 'config.pm';
28 use strict;
29 use warnings;
30 no warnings qw(once);
31
32 # Program starts here
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;
38 my %tb_cache = ();
39 my $tb_lookup_running = 0;
40 my $last_written_json = undef;
41
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)
46         or die DBI->errstr;
47 $dbh->{RaiseError} = 1;
48
49 $| = 1;
50
51 open(FICSLOG, ">ficslog.txt")
52         or die "ficslog.txt: $!";
53 print FICSLOG "Log starting.\n";
54 select(FICSLOG);
55 $| = 1;
56
57 open(UCILOG, ">ucilog.txt")
58         or die "ucilog.txt: $!";
59 print UCILOG "Log starting.\n";
60 select(UCILOG);
61 $| = 1;
62
63 open(TBLOG, ">tblog.txt")
64         or die "tblog.txt: $!";
65 print TBLOG "Log starting.\n";
66 select(TBLOG);
67 $| = 1;
68
69 select(STDOUT);
70 umask 0022;  # analysis.json should not be served to users.
71
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); });
75 my $last_move;
76 my $last_text = '';
77 my ($pos_calculating, $pos_calculating_second_engine);
78
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");
82 }
83 uciprint($engine, "ucinewgame");
84
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");
89         }
90         uciprint($engine2, "setoption name MultiPV value 500");
91         uciprint($engine2, "ucinewgame");
92 }
93
94 print "Chess engine ready.\n";
95
96 # now talk to FICS
97 my ($t, $ev1);
98 if (defined($remoteglotconf::server)) {
99         $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
100         $t->input_log(\*FICSLOG);
101         $t->open($remoteglotconf::server);
102         $t->print($remoteglotconf::nick);
103         $t->waitfor('/Press return to enter the server/');
104         $t->cmd("");
105
106         # set some options
107         $t->cmd("set shout 0");
108         $t->cmd("set seek 0");
109         $t->cmd("set style 12");
110
111         $ev1 = AnyEvent->io(
112                 fh => fileno($t),
113                 poll => 'r',
114                 cb => sub {    # what callback to execute
115                         while (1) {
116                                 my $line = $t->getline(Timeout => 0, errmode => 'return');
117                                 return if (!defined($line));
118
119                                 chomp $line;
120                                 $line =~ tr/\r//d;
121                                 handle_fics($line);
122                         }
123                 }
124         );
125 }
126 if (defined($remoteglotconf::target)) {
127         if ($remoteglotconf::target =~ /^https?:/) {
128                 fetch_pgn($remoteglotconf::target);
129         } elsif (defined($t)) {
130                 $t->cmd("observe $remoteglotconf::target");
131         }
132 }
133 if (defined($t)) {
134         print "FICS ready.\n";
135 }
136
137 # Engine events have already been set up by Engine.pm.
138 EV::run;
139
140 sub handle_uci {
141         my ($engine, $line, $primary) = @_;
142
143         return if $line =~ /(upper|lower)bound/;
144
145         $line =~ s/  / /g;  # Sometimes needed for Zappa Mexico
146         print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
147
148         # If we've sent a stop command, gobble up lines until we see bestmove.
149         return if ($engine->{'stopping'} && $line !~ /^bestmove/);
150         $engine->{'stopping'} = 0;
151
152         if ($line =~ /^info/) {
153                 my (@infos) = split / /, $line;
154                 shift @infos;
155
156                 parse_infos($engine, @infos);
157         }
158         if ($line =~ /^id/) {
159                 my (@ids) = split / /, $line;
160                 shift @ids;
161
162                 parse_ids($engine, @ids);
163         }
164         output();
165 }
166
167 my $getting_movelist = 0;
168 my $pos_for_movelist = undef;
169 my @uci_movelist = ();
170 my @pretty_movelist = ();
171
172 sub handle_fics {
173         my $line = shift;
174         if ($line =~ /^<12> /) {
175                 handle_position(Position->new($line));
176                 $t->cmd("moves");
177         }
178         if ($line =~ /^Movelist for game /) {
179                 my $pos = $pos_calculating;
180                 if (defined($pos)) {
181                         @uci_movelist = ();
182                         @pretty_movelist = ();
183                         $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
184                         $getting_movelist = 1;
185                 }
186         }
187         if ($getting_movelist &&
188             $line =~ /^\s* \d+\. \s+                     # move number
189                        (\S+) \s+ \( [\d:.]+ \) \s*       # first move, then time
190                        (?: (\S+) \s+ \( [\d:.]+ \) )?    # second move, then time 
191                      /x) {
192                 eval {
193                         my $uci_move;
194                         ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
195                         push @uci_movelist, $uci_move;
196                         push @pretty_movelist, $1;
197
198                         if (defined($2)) {
199                                 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
200                                 push @uci_movelist, $uci_move;
201                                 push @pretty_movelist, $2;
202                         }
203                 };
204                 if ($@) {
205                         warn "Error when getting FICS move history: $@";
206                         $getting_movelist = 0;
207                 }
208         }
209         if ($getting_movelist &&
210             $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
211                 # End of movelist.
212                 if (defined($pos_calculating)) {
213                         if ($pos_calculating->fen() eq $pos_for_movelist->fen()) {
214                                 $pos_calculating->{'history'} = \@pretty_movelist;
215                         }
216                 }
217                 $getting_movelist = 0;
218         }
219         if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
220                 my ($who, $msg) = ($1, $2);
221
222                 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
223
224                 if ($msg =~ /^fics (.*?)$/) {
225                         $t->cmd("tell $who Executing '$1' on FICS.");
226                         $t->cmd($1);
227                 } elsif ($msg =~ /^uci (.*?)$/) {
228                         $t->cmd("tell $who Sending '$1' to the engine.");
229                         print { $engine->{'write'} } "$1\n";
230                 } elsif ($msg =~ /^pgn (.*?)$/) {
231                         my $url = $1;
232                         $t->cmd("tell $who Starting to poll '$url'.");
233                         fetch_pgn($url);
234                 } elsif ($msg =~ /^stoppgn$/) {
235                         $t->cmd("tell $who Stopping poll.");
236                         $stop_pgn_fetch = 1;
237                         $http_timer = undef;
238                 } elsif ($msg =~ /^quit$/) {
239                         $t->cmd("tell $who Bye bye.");
240                         exit;
241                 } else {
242                         $t->cmd("tell $who Couldn't understand '$msg', sorry.");
243                 }
244         }
245         #print "FICS: [$line]\n";
246 }
247
248 # Starts periodic fetching of PGNs from the given URL.
249 sub fetch_pgn {
250         my ($url) = @_;
251         AnyEvent::HTTP::http_get($url, sub {
252                 handle_pgn(@_, $url);
253         });
254 }
255
256 my ($last_pgn_white, $last_pgn_black);
257 my @last_pgn_uci_moves = ();
258 my $pgn_hysteresis_counter = 0;
259
260 sub handle_pgn {
261         my ($body, $header, $url) = @_;
262
263         if ($stop_pgn_fetch) {
264                 $stop_pgn_fetch = 0;
265                 $http_timer = undef;
266                 return;
267         }
268
269         my $pgn = Chess::PGN::Parse->new(undef, $body);
270         if (!defined($pgn)) {
271                 warn "Error in parsing PGN from $url [body='$body']\n";
272         } elsif (!$pgn->read_game()) {
273                 warn "Error in reading PGN game from $url [body='$body']\n";
274         } elsif ($body !~ /^\[/) {
275                 warn "Malformed PGN from $url [body='$body']\n";
276         } else {
277                 eval {
278                         # Skip to the right game.
279                         while (defined($remoteglotconf::pgn_filter) &&
280                                !&$remoteglotconf::pgn_filter($pgn)) {
281                                 $pgn->read_game() or die "Out of games during filtering";
282                         }
283
284                         $pgn->parse_game({ save_comments => 'yes' });
285                         my $white = $pgn->white;
286                         my $black = $pgn->black;
287                         $white =~ s/,.*//;  # Remove first name.
288                         $black =~ s/,.*//;  # Remove first name.
289                         my $tags = $pgn->tags();
290                         my $pos;
291                         if (exists($tags->{'FEN'})) {
292                                 $pos = Position->from_fen($tags->{'FEN'});
293                                 $pos->{'last_move'} = 'none';
294                                 $pos->{'player_w'} = $white;
295                                 $pos->{'player_b'} = $black;
296                                 $pos->{'start_fen'} = $tags->{'FEN'};
297                         } else {
298                                 $pos = Position->start_pos($white, $black);
299                         }
300                         if (exists($tags->{'Variant'}) &&
301                             $tags->{'Variant'} =~ /960|fischer/i) {
302                                 $pos->{'chess960'} = 1;
303                         } else {
304                                 $pos->{'chess960'} = 0;
305                         }
306                         my $moves = $pgn->moves;
307                         my @uci_moves = ();
308                         my @repretty_moves = ();
309                         for my $move (@$moves) {
310                                 my ($npos, $uci_move) = $pos->make_pretty_move($move);
311                                 push @uci_moves, $uci_move;
312
313                                 # Re-prettyprint the move.
314                                 my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($uci_move);
315                                 my ($pretty, undef) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
316                                 push @repretty_moves, $pretty;
317                                 $pos = $npos;
318                         }
319                         if ($pgn->result eq '1-0' || $pgn->result eq '1/2-1/2' || $pgn->result eq '0-1') {
320                                 $pos->{'result'} = $pgn->result;
321                         }
322                         $pos->{'history'} = \@repretty_moves;
323
324                         extract_clock($pgn, $pos);
325
326                         # Sometimes, PGNs lose a move or two for a short while,
327                         # or people push out new ones non-atomically. 
328                         # Thus, if we PGN doesn't change names but becomes
329                         # shorter, we mistrust it for a few seconds.
330                         my $trust_pgn = 1;
331                         if (defined($last_pgn_white) && defined($last_pgn_black) &&
332                             $last_pgn_white eq $pgn->white &&
333                             $last_pgn_black eq $pgn->black &&
334                             scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
335                                 if (++$pgn_hysteresis_counter < 3) {
336                                         $trust_pgn = 0; 
337                                 }
338                         }
339                         if ($trust_pgn) {
340                                 $last_pgn_white = $pgn->white;
341                                 $last_pgn_black = $pgn->black;
342                                 @last_pgn_uci_moves = @uci_moves;
343                                 $pgn_hysteresis_counter = 0;
344                                 handle_position($pos);
345                         }
346                 };
347                 if ($@) {
348                         warn "Error in parsing moves from $url: $@\n";
349                 }
350         }
351         
352         $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
353                 fetch_pgn($url);
354         });
355 }
356
357 sub handle_position {
358         my ($pos) = @_;
359         find_clock_start($pos, $pos_calculating);
360                 
361         # If we're already chewing on this and there's nothing else in the queue,
362         # ignore it.
363         if (defined($pos_calculating) && $pos->fen() eq $pos_calculating->fen()) {
364                 $pos_calculating->{'result'} = $pos->{'result'};
365                 for my $key ('white_clock', 'black_clock', 'white_clock_target', 'black_clock_target') {
366                         $pos_calculating->{$key} //= $pos->{$key};
367                 }
368                 return;
369         }
370
371         # If we're already thinking on something, stop and wait for the engine
372         # to approve.
373         if (defined($pos_calculating)) {
374                 # Store the final data we have for this position in the history,
375                 # with the precise clock information we just got from the new
376                 # position. (Historic positions store the clock at the end of
377                 # the position.)
378                 #
379                 # Do not output anything new to the main analysis; that's
380                 # going to be obsolete really soon.
381                 $pos_calculating->{'white_clock'} = $pos->{'white_clock'};
382                 $pos_calculating->{'black_clock'} = $pos->{'black_clock'};
383                 delete $pos_calculating->{'white_clock_target'};
384                 delete $pos_calculating->{'black_clock_target'};
385                 output_json(1);
386
387                 # Ask the engine to stop; we will throw away its data until it
388                 # sends us "bestmove", signaling the end of it.
389                 $engine->{'stopping'} = 1;
390                 uciprint($engine, "stop");
391         }
392
393         # It's wrong to just give the FEN (the move history is useful,
394         # and per the UCI spec, we should really have sent "ucinewgame"),
395         # but it's easier, and it works around a Stockfish repetition issue.
396         if ($engine->{'chess960'} != $pos->{'chess960'}) {
397                 uciprint($engine, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
398                 $engine->{'chess960'} = $pos->{'chess960'};
399         }
400         uciprint($engine, "position fen " . $pos->fen());
401         uciprint($engine, "go infinite");
402         $pos_calculating = $pos;
403
404         if (defined($engine2)) {
405                 if (defined($pos_calculating_second_engine)) {
406                         $engine2->{'stopping'} = 1;
407                         uciprint($engine2, "stop");
408                 }
409                 if ($engine2->{'chess960'} != $pos->{'chess960'}) {
410                         uciprint($engine2, "setoption name UCI_Chess960 value " . ($pos->{'chess960'} ? 'true' : 'false'));
411                         $engine2->{'chess960'} = $pos->{'chess960'};
412                 }
413                 uciprint($engine2, "position fen " . $pos->fen());
414                 uciprint($engine2, "go infinite");
415                 $pos_calculating_second_engine = $pos;
416                 $engine2->{'info'} = {};
417         }
418
419         $engine->{'info'} = {};
420         $last_move = time;
421
422         schedule_tb_lookup();
423
424         # 
425         # Output a command every move to note that we're
426         # still paying attention -- this is a good tradeoff,
427         # since if no move has happened in the last half
428         # hour, the analysis/relay has most likely stopped
429         # and we should stop hogging server resources.
430         #
431         if (defined($t)) {
432                 $t->cmd("date");
433         }
434 }
435
436 sub parse_infos {
437         my ($engine, @x) = @_;
438         my $mpv = '';
439
440         my $info = $engine->{'info'};
441
442         # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
443         for my $i (0..$#x - 1) {
444                 if ($x[$i] eq 'multipv') {
445                         $mpv = $x[$i + 1];
446                         next;
447                 }
448         }
449
450         while (scalar @x > 0) {
451                 if ($x[0] eq 'multipv') {
452                         # Dealt with above
453                         shift @x;
454                         shift @x;
455                         next;
456                 }
457                 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
458                         my $key = shift @x;
459                         my $value = shift @x;
460                         $info->{$key} = $value;
461                         next;
462                 }
463                 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
464                     $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
465                     $x[0] eq 'tbhits') {
466                         my $key = shift @x;
467                         my $value = shift @x;
468                         $info->{$key . $mpv} = $value;
469                         next;
470                 }
471                 if ($x[0] eq 'score') {
472                         shift @x;
473
474                         delete $info->{'score_cp' . $mpv};
475                         delete $info->{'score_mate' . $mpv};
476
477                         while ($x[0] eq 'cp' || $x[0] eq 'mate') {
478                                 if ($x[0] eq 'cp') {
479                                         shift @x;
480                                         $info->{'score_cp' . $mpv} = shift @x;
481                                 } elsif ($x[0] eq 'mate') {
482                                         shift @x;
483                                         $info->{'score_mate' . $mpv} = shift @x;
484                                 } else {
485                                         shift @x;
486                                 }
487                         }
488                         next;
489                 }
490                 if ($x[0] eq 'pv') {
491                         $info->{'pv' . $mpv} = [ @x[1..$#x] ];
492                         last;
493                 }
494                 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
495                         last;
496                 }
497
498                 #print "unknown info '$x[0]', trying to recover...\n";
499                 #shift @x;
500                 die "Unknown info '" . join(',', @x) . "'";
501
502         }
503 }
504
505 sub parse_ids {
506         my ($engine, @x) = @_;
507
508         while (scalar @x > 0) {
509                 if ($x[0] eq 'name') {
510                         my $value = join(' ', @x);
511                         $engine->{'id'}{'author'} = $value;
512                         last;
513                 }
514
515                 # unknown
516                 shift @x;
517         }
518 }
519
520 sub prettyprint_pv_no_cache {
521         my ($board, @pvs) = @_;
522
523         if (scalar @pvs == 0 || !defined($pvs[0])) {
524                 return ();
525         }
526
527         my $pv = shift @pvs;
528         my ($from_row, $from_col, $to_row, $to_col, $promo) = parse_uci_move($pv);
529         my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
530         return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
531 }
532
533 sub prettyprint_pv {
534         my ($pos, @pvs) = @_;
535
536         my $cachekey = join('', @pvs);
537         if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
538                 return @{$pos->{'prettyprint_cache'}{$cachekey}};
539         } else {
540                 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
541                 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
542                 return @res;
543         }
544 }
545
546 my %tbprobe_cache = ();
547
548 sub complete_using_tbprobe {
549         my ($pos, $info, $mpv) = @_;
550
551         # We need Fathom installed to do standalone TB probes.
552         return if (!defined($remoteglotconf::fathom_cmdline));
553
554         # If we already have a mate, don't bother; in some cases, it would even be
555         # better than a tablebase score.
556         return if defined($info->{'score_mate' . $mpv});
557
558         # If we have a draw or near-draw score, there's also not much interesting
559         # we could add from a tablebase. We only really want mates.
560         return if ($info->{'score_cp' . $mpv} >= -12250 && $info->{'score_cp' . $mpv} <= 12250);
561
562         # Run through the PV until we are at a 6-man position.
563         # TODO: We could in theory only have 5-man data.
564         my @pv = @{$info->{'pv' . $mpv}};
565         my $key = $pos->fen() . " " . join('', @pv);
566         my @moves = ();
567         if (exists($tbprobe_cache{$key})) {
568                 @moves = @{$tbprobe_cache{$key}};
569         } else {
570                 if ($mpv ne '') {
571                         # Force doing at least one move of the PV.
572                         my $move = shift @pv;
573                         push @moves, $move;
574                         $pos = $pos->make_move(parse_uci_move($move));
575                 }
576
577                 while ($pos->num_pieces() > 6 && $#pv > -1) {
578                         my $move = shift @pv;
579                         push @moves, $move;
580                         $pos = $pos->make_move(parse_uci_move($move));
581                 }
582
583                 return if ($pos->num_pieces() > 6);
584
585                 my $fen = $pos->fen();
586                 my $pgn_text = `fathom --path=/srv/syzygy "$fen"`;
587                 my $pgn = Chess::PGN::Parse->new(undef, $pgn_text);
588                 return if (!defined($pgn) || !$pgn->read_game() || ($pgn->result ne '0-1' && $pgn->result ne '1-0'));
589                 $pgn->quick_parse_game;
590                 $info->{'pv' . $mpv} = \@moves;
591
592                 # Splice the PV from the tablebase onto what we have so far.
593                 for my $move (@{$pgn->moves}) {
594                         last if $move eq '#';
595                         my $uci_move;
596                         ($pos, $uci_move) = $pos->make_pretty_move($move);
597                         push @moves, $uci_move;
598                 }
599
600                 $tbprobe_cache{$key} = \@moves;
601         }
602
603         $info->{'pv' . $mpv} = \@moves;
604
605         my $matelen = int((1 + scalar @moves) / 2);
606         if ((scalar @moves) % 2 == 0) {
607                 $info->{'score_mate' . $mpv} = -$matelen;
608         } else {
609                 $info->{'score_mate' . $mpv} = $matelen;
610         }
611 }
612
613 sub output {
614         #return;
615
616         return if (!defined($pos_calculating));
617
618         # Don't update too often.
619         my $age = Time::HiRes::tv_interval($latest_update);
620         if ($age < $remoteglotconf::update_max_interval) {
621                 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
622                 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
623                 return;
624         }
625         
626         my $info = $engine->{'info'};
627
628         #
629         # If we have tablebase data from a previous lookup, replace the
630         # engine data with the data from the tablebase.
631         #
632         my $fen = $pos_calculating->fen();
633         if (exists($tb_cache{$fen})) {
634                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
635                         delete $info->{$key . '1'};
636                         delete $info->{$key};
637                 }
638                 $info->{'nodes'} = 0;
639                 $info->{'nps'} = 0;
640                 $info->{'depth'} = 0;
641                 $info->{'seldepth'} = 0;
642                 $info->{'tbhits'} = 0;
643
644                 my $t = $tb_cache{$fen};
645                 my $pv = $t->{'pv'};
646                 my $matelen = int((1 + $t->{'score'}) / 2);
647                 if ($t->{'result'} eq '1/2-1/2') {
648                         $info->{'score_cp'} = 0;
649                 } elsif ($t->{'result'} eq '1-0') {
650                         if ($pos_calculating->{'toplay'} eq 'B') {
651                                 $info->{'score_mate'} = -$matelen;
652                         } else {
653                                 $info->{'score_mate'} = $matelen;
654                         }
655                 } else {
656                         if ($pos_calculating->{'toplay'} eq 'B') {
657                                 $info->{'score_mate'} = $matelen;
658                         } else {
659                                 $info->{'score_mate'} = -$matelen;
660                         }
661                 }
662                 $info->{'pv'} = $pv;
663                 $info->{'tablebase'} = 1;
664         } else {
665                 $info->{'tablebase'} = 0;
666         }
667         
668         #
669         # Some programs _always_ report MultiPV, even with only one PV.
670         # In this case, we simply use that data as if MultiPV was never
671         # specified.
672         #
673         if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
674                 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
675                         if (exists($info->{$key . '1'})) {
676                                 $info->{$key} = $info->{$key . '1'};
677                         } else {
678                                 delete $info->{$key};
679                         }
680                 }
681         }
682         
683         #
684         # Check the PVs first. if they're invalid, just wait, as our data
685         # is most likely out of sync. This isn't a very good solution, as
686         # it can frequently miss stuff, but it's good enough for most users.
687         #
688         eval {
689                 my $dummy;
690                 if (exists($info->{'pv'})) {
691                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
692                 }
693         
694                 my $mpv = 1;
695                 while (exists($info->{'pv' . $mpv})) {
696                         $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
697                         ++$mpv;
698                 }
699         };
700         if ($@) {
701                 $engine->{'info'} = {};
702                 return;
703         }
704
705         # Now do our own Syzygy tablebase probes to convert scores like +123.45 to mate.
706         if (exists($info->{'pv'})) {
707                 complete_using_tbprobe($pos_calculating, $info, '');
708         }
709
710         my $mpv = 1;
711         while (exists($info->{'pv' . $mpv})) {
712                 complete_using_tbprobe($pos_calculating, $info, $mpv);
713                 ++$mpv;
714         }
715
716         output_screen();
717         output_json(0);
718         $latest_update = [Time::HiRes::gettimeofday];
719 }
720
721 sub output_screen {
722         my $info = $engine->{'info'};
723         my $id = $engine->{'id'};
724
725         my $text = 'Analysis';
726         if ($pos_calculating->{'last_move'} ne 'none') {
727                 if ($pos_calculating->{'toplay'} eq 'W') {
728                         $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
729                 } else {
730                         $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
731                 }
732                 if (exists($id->{'name'})) {
733                         $text .= ',';
734                 }
735         }
736
737         if (exists($id->{'name'})) {
738                 $text .= " by $id->{'name'}:\n\n";
739         } else {
740                 $text .= ":\n\n";
741         }
742
743         return unless (exists($pos_calculating->{'board'}));
744                 
745         if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
746                 # multi-PV
747                 my $mpv = 1;
748                 while (exists($info->{'pv' . $mpv})) {
749                         $text .= sprintf "  PV%2u", $mpv;
750                         my $score = short_score($info, $pos_calculating, $mpv);
751                         $text .= "  ($score)" if (defined($score));
752
753                         my $tbhits = '';
754                         if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
755                                 if ($info->{'tbhits' . $mpv} == 1) {
756                                         $tbhits = ", 1 tbhit";
757                                 } else {
758                                         $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
759                                 }
760                         }
761
762                         if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
763                                 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
764                                         $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
765                         }
766
767                         $text .= ":\n";
768                         $text .= "  " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
769                         $text .= "\n";
770                         ++$mpv;
771                 }
772         } else {
773                 # single-PV
774                 my $score = long_score($info, $pos_calculating, '');
775                 $text .= "  $score\n" if defined($score);
776                 $text .=  "  PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
777                 $text .=  "\n";
778
779                 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
780                         $text .= sprintf "  %u nodes, %7u nodes/sec, depth %u ply",
781                                 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
782                 }
783                 if (exists($info->{'seldepth'})) {
784                         $text .= sprintf " (%u selective)", $info->{'seldepth'};
785                 }
786                 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
787                         if ($info->{'tbhits'} == 1) {
788                                 $text .= ", one Syzygy hit";
789                         } else {
790                                 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
791                         }
792                 }
793                 $text .= "\n\n";
794         }
795
796         #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
797
798         my @refutation_lines = ();
799         if (defined($engine2)) {
800                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
801                         my $info = $engine2->{'info'};
802                         last if (!exists($info->{'pv' . $mpv}));
803                         eval {
804                                 complete_using_tbprobe($pos_calculating_second_engine, $info, $mpv);
805                                 my $pv = $info->{'pv' . $mpv};
806                                 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
807                                 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
808                                 if (scalar @pretty_pv > 5) {
809                                         @pretty_pv = @pretty_pv[0..4];
810                                         push @pretty_pv, "...";
811                                 }
812                                 my $key = $pretty_move;
813                                 my $line = sprintf("  %-6s %6s %3s  %s",
814                                         $pretty_move,
815                                         short_score($info, $pos_calculating_second_engine, $mpv),
816                                         "d" . $info->{'depth' . $mpv},
817                                         join(', ', @pretty_pv));
818                                 push @refutation_lines, [ $key, $line ];
819                         };
820                 }
821         }
822
823         if ($#refutation_lines >= 0) {
824                 $text .= "Shallow search of all legal moves:\n\n";
825                 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
826                         $text .= $line->[1] . "\n";
827                 }
828                 $text .= "\n\n";        
829         }       
830
831         if ($last_text ne $text) {
832                 print "\e[H\e[2J"; # clear the screen
833                 print $text;
834                 $last_text = $text;
835         }
836 }
837
838 sub output_json {
839         my $historic_json_only = shift;
840         my $info = $engine->{'info'};
841
842         my $json = {};
843         $json->{'position'} = $pos_calculating->to_json_hash();
844         $json->{'engine'} = $engine->{'id'};
845         if (defined($remoteglotconf::engine_url)) {
846                 $json->{'engine'}{'url'} = $remoteglotconf::engine_url;
847         }
848         if (defined($remoteglotconf::engine_details)) {
849                 $json->{'engine'}{'details'} = $remoteglotconf::engine_details;
850         }
851         my @grpc_backends = ();
852         if (defined($remoteglotconf::engine_grpc_backend)) {
853                 push @grpc_backends, $remoteglotconf::engine_grpc_backend;
854         }
855         if (defined($remoteglotconf::engine2_grpc_backend)) {
856                 push @grpc_backends, $remoteglotconf::engine2_grpc_backend;
857         }
858         $json->{'internal'}{'grpc_backends'} = \@grpc_backends;
859         if (defined($remoteglotconf::move_source)) {
860                 $json->{'move_source'} = $remoteglotconf::move_source;
861         }
862         if (defined($remoteglotconf::move_source_url)) {
863                 $json->{'move_source_url'} = $remoteglotconf::move_source_url;
864         }
865         $json->{'score'} = score_digest($info, $pos_calculating, '');
866         $json->{'using_lomonosov'} = defined($remoteglotconf::tb_serial_key);
867
868         $json->{'nodes'} = $info->{'nodes'};
869         $json->{'nps'} = $info->{'nps'};
870         $json->{'depth'} = $info->{'depth'};
871         $json->{'tbhits'} = $info->{'tbhits'};
872         $json->{'seldepth'} = $info->{'seldepth'};
873         $json->{'tablebase'} = $info->{'tablebase'};
874         $json->{'pv'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
875
876         my %refutation_lines = ();
877         my @refutation_lines = ();
878         if (defined($engine2)) {
879                 for (my $mpv = 1; $mpv < 500; ++$mpv) {
880                         my $info = $engine2->{'info'};
881                         my $pretty_move = "";
882                         my @pretty_pv = ();
883                         last if (!exists($info->{'pv' . $mpv}));
884
885                         eval {
886                                 complete_using_tbprobe($pos_calculating, $info, $mpv);
887                                 my $pv = $info->{'pv' . $mpv};
888                                 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
889                                 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
890                                 $refutation_lines{$pretty_move} = {
891                                         depth => $info->{'depth' . $mpv},
892                                         score => score_digest($info, $pos_calculating, $mpv),
893                                         move => $pretty_move,
894                                         pv => \@pretty_pv,
895                                 };
896                         };
897                 }
898         }
899         $json->{'refutation_lines'} = \%refutation_lines;
900
901         # Piece together historic score information, to the degree we have it.
902         if (!$historic_json_only && exists($pos_calculating->{'history'})) {
903                 my %score_history = ();
904
905                 local $dbh->{AutoCommit} = 0;
906                 my $q = $dbh->prepare('SELECT * FROM scores WHERE id=?');
907                 my $pos;
908                 if (exists($pos_calculating->{'start_fen'})) {
909                         $pos = Position->from_fen($pos_calculating->{'start_fen'});
910                 } else {
911                         $pos = Position->start_pos('white', 'black');
912                 }
913                 $pos->{'chess960'} = $pos_calculating->{'chess960'};
914                 my $halfmove_num = 0;
915                 for my $move (@{$pos_calculating->{'history'}}) {
916                         my $id = id_for_pos($pos, $halfmove_num);
917                         my $ref = $dbh->selectrow_hashref($q, undef, $id);
918                         if (defined($ref)) {
919                                 $score_history{$halfmove_num} = [
920                                         $ref->{'score_type'},
921                                         $ref->{'score_value'}
922                                 ];
923                         }
924                         ++$halfmove_num;
925                         ($pos) = $pos->make_pretty_move($move);
926                 }
927                 $q->finish;
928                 $dbh->commit;
929
930                 # If at any point we are missing 10 consecutive moves,
931                 # truncate the history there. This is so we don't get into
932                 # a situation where we e.g. start analyzing at move 45,
933                 # but we have analysis for 1. e4 from some completely different game
934                 # and thus show a huge hole.
935                 my $consecutive_missing = 0;
936                 my $truncate_until = 0;
937                 for (my $i = $halfmove_num; $i --> 0; ) {
938                         if ($consecutive_missing >= 10) {
939                                 delete $score_history{$i};
940                                 next;
941                         }
942                         if (exists($score_history{$i})) {
943                                 $consecutive_missing = 0;
944                         } else {
945                                 ++$consecutive_missing;
946                         }
947                 }
948
949                 $json->{'score_history'} = \%score_history;
950         }
951
952         # Give out a list of other games going on. (Empty is fine.)
953         # TODO: Don't bother reading our own file, the data will be stale anyway.
954         if (!$historic_json_only) {
955                 my @games = ();
956
957                 my $q = $dbh->prepare('SELECT * FROM current_games ORDER BY priority DESC, id');
958                 $q->execute;
959                 while (my $ref = $q->fetchrow_hashref) {
960                         eval {
961                                 my $other_game_contents = File::Slurp::read_file($ref->{'json_path'});
962                                 my $other_game_json = JSON::XS::decode_json($other_game_contents);
963
964                                 die "Missing position" if (!exists($other_game_json->{'position'}));
965                                 my $white = $other_game_json->{'position'}{'player_w'} // die 'Missing white';
966                                 my $black = $other_game_json->{'position'}{'player_b'} // die 'Missing black';
967
968                                 my $game = {
969                                         id => $ref->{'id'},
970                                         name => "$white–$black",
971                                         url => $ref->{'url'},
972                                         hashurl => $ref->{'hash_url'},
973                                 };
974                                 if (defined($other_game_json->{'position'}{'result'})) {
975                                         $game->{'result'} = $other_game_json->{'position'}{'result'};
976                                 } else {
977                                         $game->{'score'} = $other_game_json->{'score'};
978                                 }
979                                 push @games, $game;
980                         };
981                         if ($@) {
982                                 warn "Could not add external game " . $ref->{'json_path'} . ": $@";
983                         }
984                 }
985
986                 if (scalar @games > 0) {
987                         $json->{'games'} = \@games;
988                 }
989         }
990
991         my $json_enc = JSON::XS->new;
992         $json_enc->canonical(1);
993         my $encoded = $json_enc->encode($json);
994         unless ($historic_json_only || !defined($remoteglotconf::json_output) ||
995                 (defined($last_written_json) && $last_written_json eq $encoded)) {
996                 atomic_set_contents($remoteglotconf::json_output, $encoded);
997                 $last_written_json = $encoded;
998         }
999
1000         if (exists($pos_calculating->{'history'}) &&
1001             defined($remoteglotconf::json_history_dir)) {
1002                 my $id = id_for_pos($pos_calculating);
1003                 my $filename = $remoteglotconf::json_history_dir . "/" . $id . ".json";
1004
1005                 # Overwrite old analysis (assuming it exists at all) if we're
1006                 # using a different engine, or if we've calculated deeper.
1007                 # nodes is used as a tiebreaker. Don't bother about Multi-PV
1008                 # data; it's not that important.
1009                 my ($old_engine, $old_depth, $old_nodes) = get_json_analysis_stats($id);
1010                 my $new_depth = $json->{'depth'} // 0;
1011                 my $new_nodes = $json->{'nodes'} // 0;
1012                 if (!defined($old_engine) ||
1013                     $old_engine ne $json->{'engine'}{'name'} ||
1014                     $new_depth > $old_depth ||
1015                     ($new_depth == $old_depth && $new_nodes >= $old_nodes)) {
1016                         atomic_set_contents($filename, $encoded);
1017                         if (defined($json->{'score'})) {
1018                                 $dbh->do('INSERT INTO scores (id, score_type, score_value, engine, depth, nodes) VALUES (?,?,?,?,?,?) ' .
1019                                          '    ON CONFLICT (id) DO UPDATE SET ' .
1020                                          '        score_type=EXCLUDED.score_type, ' .
1021                                          '        score_value=EXCLUDED.score_value, ' .
1022                                          '        engine=EXCLUDED.engine, ' .
1023                                          '        depth=EXCLUDED.depth, ' .
1024                                          '        nodes=EXCLUDED.nodes',
1025                                         undef,
1026                                         $id, $json->{'score'}[0], $json->{'score'}[1],
1027                                         $json->{'engine'}{'name'}, $new_depth, $new_nodes);
1028                         }
1029                 }
1030         }
1031 }
1032
1033 sub atomic_set_contents {
1034         my ($filename, $contents) = @_;
1035
1036         open my $fh, ">", $filename . ".tmp"
1037                 or return;
1038         print $fh $contents;
1039         close $fh;
1040         rename($filename . ".tmp", $filename);
1041 }
1042
1043 sub id_for_pos {
1044         my ($pos, $halfmove_num) = @_;
1045
1046         $halfmove_num //= scalar @{$pos->{'history'}};
1047         (my $fen = $pos->fen()) =~ tr,/ ,-_,;
1048         return "move$halfmove_num-$fen";
1049 }
1050
1051 sub get_json_analysis_stats {
1052         my $id = shift;
1053         my $ref = $dbh->selectrow_hashref('SELECT * FROM scores WHERE id=?', undef, $id);
1054         if (defined($ref)) {
1055                 return ($ref->{'engine'}, $ref->{'depth'}, $ref->{'nodes'});
1056         } else {
1057                 return ('', 0, 0);
1058         }
1059 }
1060
1061 sub uciprint {
1062         my ($engine, $msg) = @_;
1063         $engine->print($msg);
1064         print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
1065 }
1066
1067 sub short_score {
1068         my ($info, $pos, $mpv) = @_;
1069
1070         my $invert = ($pos->{'toplay'} eq 'B');
1071         if (defined($info->{'score_mate' . $mpv})) {
1072                 if ($invert) {
1073                         return sprintf "M%3d", -$info->{'score_mate' . $mpv};
1074                 } else {
1075                         return sprintf "M%3d", $info->{'score_mate' . $mpv};
1076                 }
1077         } else {
1078                 if (exists($info->{'score_cp' . $mpv})) {
1079                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1080                         if ($score == 0) {
1081                                 if ($info->{'tablebase'}) {
1082                                         return "TB draw";
1083                                 } else {
1084                                         return " 0.00";
1085                                 }
1086                         }
1087                         if ($invert) {
1088                                 $score = -$score;
1089                         }
1090                         return sprintf "%+5.2f", $score;
1091                 }
1092         }
1093
1094         return undef;
1095 }
1096
1097 # Sufficient for computing long_score, short_score, plot_score and
1098 # (with side-to-play information) score_sort_key.
1099 sub score_digest {
1100         my ($info, $pos, $mpv) = @_;
1101
1102         if (defined($info->{'score_mate' . $mpv})) {
1103                 my $mate = $info->{'score_mate' . $mpv};
1104                 if ($pos->{'toplay'} eq 'B') {
1105                         $mate = -$mate;
1106                 }
1107                 return ['m', $mate];
1108         } else {
1109                 if (exists($info->{'score_cp' . $mpv})) {
1110                         my $score = $info->{'score_cp' . $mpv};
1111                         if ($pos->{'toplay'} eq 'B') {
1112                                 $score = -$score;
1113                         }
1114                         if ($score == 0 && $info->{'tablebase'}) {
1115                                 return ['d', undef];
1116                         } else {
1117                                 return ['cp', int($score)];
1118                         }
1119                 }
1120         }
1121
1122         return undef;
1123 }
1124
1125 sub long_score {
1126         my ($info, $pos, $mpv) = @_;
1127
1128         if (defined($info->{'score_mate' . $mpv})) {
1129                 my $mate = $info->{'score_mate' . $mpv};
1130                 if ($pos->{'toplay'} eq 'B') {
1131                         $mate = -$mate;
1132                 }
1133                 if ($mate > 0) {
1134                         return sprintf "White mates in %u", $mate;
1135                 } else {
1136                         return sprintf "Black mates in %u", -$mate;
1137                 }
1138         } else {
1139                 if (exists($info->{'score_cp' . $mpv})) {
1140                         my $score = $info->{'score_cp' . $mpv} * 0.01;
1141                         if ($score == 0) {
1142                                 if ($info->{'tablebase'}) {
1143                                         return "Theoretical draw";
1144                                 } else {
1145                                         return "Score:  0.00";
1146                                 }
1147                         }
1148                         if ($pos->{'toplay'} eq 'B') {
1149                                 $score = -$score;
1150                         }
1151                         return sprintf "Score: %+5.2f", $score;
1152                 }
1153         }
1154
1155         return undef;
1156 }
1157
1158 # For graphs; a single number in centipawns, capped at +/- 500.
1159 sub plot_score {
1160         my ($info, $pos, $mpv) = @_;
1161
1162         my $invert = ($pos->{'toplay'} eq 'B');
1163         if (defined($info->{'score_mate' . $mpv})) {
1164                 my $mate = $info->{'score_mate' . $mpv};
1165                 if ($invert) {
1166                         $mate = -$mate;
1167                 }
1168                 if ($mate > 0) {
1169                         return 500;
1170                 } else {
1171                         return -500;
1172                 }
1173         } else {
1174                 if (exists($info->{'score_cp' . $mpv})) {
1175                         my $score = $info->{'score_cp' . $mpv};
1176                         if ($invert) {
1177                                 $score = -$score;
1178                         }
1179                         $score = 500 if ($score > 500);
1180                         $score = -500 if ($score < -500);
1181                         return int($score);
1182                 }
1183         }
1184
1185         return undef;
1186 }
1187
1188 my %book_cache = ();
1189 sub book_info {
1190         my ($fen, $board, $toplay) = @_;
1191
1192         if (exists($book_cache{$fen})) {
1193                 return $book_cache{$fen};
1194         }
1195
1196         my $ret = `./booklook $fen`;
1197         return "" if ($ret =~ /Not found/ || $ret eq '');
1198
1199         my @moves = ();
1200
1201         for my $m (split /\n/, $ret) {
1202                 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
1203
1204                 my $pmove;
1205                 if ($move eq '')  {
1206                         $pmove = '(current)';
1207                 } else {
1208                         ($pmove) = prettyprint_pv_no_cache($board, $move);
1209                         $pmove .= $annotation;
1210                 }
1211
1212                 my $score;
1213                 if ($toplay eq 'W') {
1214                         $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
1215                 } else {
1216                         $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
1217                 }
1218                 my $n = $win + $draw + $lose;
1219                 
1220                 my $percent;
1221                 if ($n == 0) {
1222                         $percent = "     ";
1223                 } else {
1224                         $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
1225                 }
1226
1227                 push @moves, [ $pmove, $n, $percent, $rating ];
1228         }
1229
1230         @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
1231         
1232         my $text = "Book moves:\n\n              Perf.     N     Rating\n\n";
1233         for my $m (@moves) {
1234                 $text .= sprintf "  %-10s %s   %6u    %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
1235         }
1236
1237         return $text;
1238 }
1239
1240 sub extract_clock {
1241         my ($pgn, $pos) = @_;
1242
1243         # Look for extended PGN clock tags.
1244         my $tags = $pgn->tags;
1245         if (exists($tags->{'WhiteClock'}) && exists($tags->{'BlackClock'})) {
1246                 $pos->{'white_clock'} = hms_to_sec($tags->{'WhiteClock'});
1247                 $pos->{'black_clock'} = hms_to_sec($tags->{'BlackClock'});
1248                 return;
1249         }
1250
1251         # Look for TCEC-style time comments.
1252         my $moves = $pgn->moves;
1253         my $comments = $pgn->comments;
1254         my $last_black_move = int((scalar @$moves) / 2);
1255         my $last_white_move = int((1 + scalar @$moves) / 2);
1256
1257         my $black_key = $last_black_move . "b";
1258         my $white_key = $last_white_move . "w";
1259
1260         if (exists($comments->{$white_key}) &&
1261             exists($comments->{$black_key}) &&
1262             $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/ &&
1263             $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/) {
1264                 $comments->{$white_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1265                 $pos->{'white_clock'} = hms_to_sec($1);
1266                 $comments->{$black_key} =~ /(?:tl=|clk )(\d+:\d+:\d+)/;
1267                 $pos->{'black_clock'} = hms_to_sec($1);
1268                 return;
1269         }
1270
1271         delete $pos->{'white_clock'};
1272         delete $pos->{'black_clock'};
1273 }
1274
1275 sub hms_to_sec {
1276         my $hms = shift;
1277         return undef if (!defined($hms));
1278         $hms =~ /(\d+):(\d+):(\d+)/;
1279         return $1 * 3600 + $2 * 60 + $3;
1280 }
1281
1282 sub find_clock_start {
1283         my ($pos, $prev_pos) = @_;
1284
1285         # If the game is over, the clock is stopped.
1286         if (exists($pos->{'result'}) &&
1287             ($pos->{'result'} eq '1-0' ||
1288              $pos->{'result'} eq '1/2-1/2' ||
1289              $pos->{'result'} eq '0-1')) {
1290                 return;
1291         }
1292
1293         # When we don't have any moves, we assume the clock hasn't started yet.
1294         if ($pos->{'move_num'} == 1 && $pos->{'toplay'} eq 'W') {
1295                 if (defined($remoteglotconf::adjust_clocks_before_move)) {
1296                         &$remoteglotconf::adjust_clocks_before_move(\$pos->{'white_clock'}, \$pos->{'black_clock'}, 1, 'W');
1297                 }
1298                 return;
1299         }
1300
1301         # TODO(sesse): Maybe we can get the number of moves somehow else for FICS games.
1302         # The history is needed for id_for_pos.
1303         if (!exists($pos->{'history'})) {
1304                 return;
1305         }
1306
1307         my $id = id_for_pos($pos);
1308         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);
1309         if (defined($clock_info)) {
1310                 $pos->{'white_clock'} //= $clock_info->{'white_clock'};
1311                 $pos->{'black_clock'} //= $clock_info->{'black_clock'};
1312                 if ($pos->{'toplay'} eq 'W') {
1313                         $pos->{'white_clock_target'} = $clock_info->{'white_clock_target'};
1314                 } else {
1315                         $pos->{'black_clock_target'} = $clock_info->{'black_clock_target'};
1316                 }
1317                 return;
1318         }
1319
1320         # OK, we haven't seen this position before, so we assume the move
1321         # happened right now.
1322
1323         # See if we should do our own clock management (ie., clock information
1324         # is spurious or non-existent).
1325         if (defined($remoteglotconf::adjust_clocks_before_move)) {
1326                 my $wc = $pos->{'white_clock'} // $prev_pos->{'white_clock'};
1327                 my $bc = $pos->{'black_clock'} // $prev_pos->{'black_clock'};
1328                 if (defined($prev_pos->{'white_clock_target'})) {
1329                         $wc = $prev_pos->{'white_clock_target'} - time;
1330                 }
1331                 if (defined($prev_pos->{'black_clock_target'})) {
1332                         $bc = $prev_pos->{'black_clock_target'} - time;
1333                 }
1334                 &$remoteglotconf::adjust_clocks_before_move(\$wc, \$bc, $pos->{'move_num'}, $pos->{'toplay'});
1335                 $pos->{'white_clock'} = $wc;
1336                 $pos->{'black_clock'} = $bc;
1337         }
1338
1339         my $key = ($pos->{'toplay'} eq 'W') ? 'white_clock' : 'black_clock';
1340         if (!exists($pos->{$key})) {
1341                 # No clock information.
1342                 return;
1343         }
1344         my $time_left = $pos->{$key};
1345         my ($white_clock_target, $black_clock_target);
1346         if ($pos->{'toplay'} eq 'W') {
1347                 $white_clock_target = $pos->{'white_clock_target'} = time + $time_left;
1348         } else {
1349                 $black_clock_target = $pos->{'black_clock_target'} = time + $time_left;
1350         }
1351         local $dbh->{AutoCommit} = 0;
1352         $dbh->do('DELETE FROM clock_info WHERE id=?', undef, $id);
1353         $dbh->do('INSERT INTO clock_info (id, white_clock, black_clock, white_clock_target, black_clock_target) VALUES (?, ?, ?, ?, ?)', undef,
1354                 $id, $pos->{'white_clock'}, $pos->{'black_clock'}, $white_clock_target, $black_clock_target);
1355         $dbh->commit;
1356 }
1357
1358 sub schedule_tb_lookup {
1359         return if (!defined($remoteglotconf::tb_serial_key));
1360         my $pos = $pos_calculating;
1361         return if (exists($tb_cache{$pos->fen()}));
1362
1363         # If there's more than seven pieces, there's not going to be an answer,
1364         # so don't bother.
1365         return if ($pos->num_pieces() > 7);
1366
1367         # Max one at a time. If it's still relevant when it returns,
1368         # schedule_tb_lookup() will be called again.
1369         return if ($tb_lookup_running);
1370
1371         $tb_lookup_running = 1;
1372         my $url = 'http://tb7-api.chessok.com:6904/tasks/addtask?auth.login=' .
1373                 $remoteglotconf::tb_serial_key .
1374                 '&auth.password=aquarium&type=0&fen=' . 
1375                 URI::Escape::uri_escape($pos->fen());
1376         print TBLOG "Downloading $url...\n";
1377         AnyEvent::HTTP::http_get($url, sub {
1378                 handle_tb_lookup_return(@_, $pos, $pos->fen());
1379         });
1380 }
1381
1382 sub handle_tb_lookup_return {
1383         my ($body, $header, $pos, $fen) = @_;
1384         print TBLOG "Response for [$fen]:\n";
1385         print TBLOG $header . "\n\n";
1386         print TBLOG $body . "\n\n";
1387         eval {
1388                 my $response = JSON::XS::decode_json($body);
1389                 if ($response->{'ErrorCode'} != 0) {
1390                         die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
1391                 }
1392                 my $state = $response->{'Response'}{'StateString'};
1393                 if ($state eq 'COMPLETE') {
1394                         my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
1395                         if (!defined($pgn) || !$pgn->read_game()) {
1396                                 warn "Error in parsing PGN\n";
1397                         } else {
1398                                 $pgn->quick_parse_game;
1399                                 my $pvpos = $pos;
1400                                 my $moves = $pgn->moves;
1401                                 my @uci_moves = ();
1402                                 for my $move (@$moves) {
1403                                         my $uci_move;
1404                                         ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
1405                                         push @uci_moves, $uci_move;
1406                                 }
1407                                 $tb_cache{$fen} = {
1408                                         result => $pgn->result,
1409                                         pv => \@uci_moves,
1410                                         score => $response->{'Response'}{'Score'},
1411                                 };
1412                                 output();
1413                         }
1414                 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
1415                         # Try again in a second. Note that if we have changed
1416                         # position in the meantime, we might query a completely
1417                         # different position! But that's fine.
1418                 } else {
1419                         die "Unknown response state " . $state;
1420                 }
1421
1422                 # Wait a second before we schedule another one.
1423                 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
1424                         $tb_lookup_running = 0;
1425                         schedule_tb_lookup();
1426                 });
1427         };
1428         if ($@) {
1429                 warn "Error in tablebase lookup: $@";
1430
1431                 # Don't try this one again, but don't block new lookups either.
1432                 $tb_lookup_running = 0;
1433         }
1434 }
1435
1436 sub open_engine {
1437         my ($cmdline, $tag, $cb) = @_;
1438         return undef if (!defined($cmdline));
1439         return Engine->open($cmdline, $tag, $cb);
1440 }
1441
1442 sub col_letter_to_num {
1443         return ord(shift) - ord('a');
1444 }
1445
1446 sub row_letter_to_num {
1447         return 7 - (ord(shift) - ord('1'));
1448 }
1449
1450 sub parse_uci_move {
1451         my $move = shift;
1452         my $from_col = col_letter_to_num(substr($move, 0, 1));
1453         my $from_row = row_letter_to_num(substr($move, 1, 1));
1454         my $to_col   = col_letter_to_num(substr($move, 2, 1));
1455         my $to_row   = row_letter_to_num(substr($move, 3, 1));
1456         my $promo    = substr($move, 4, 1);
1457         return ($from_row, $from_col, $to_row, $to_col, $promo);
1458 }