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