Support navigating in the PVs.
[remoteglot] / www / js / remoteglot.js
1 var board = null;
2 var hiddenboard = null;
3 var arrows = [];
4 var arrow_targets = [];
5 var occupied_by_arrows = [];
6 var refutation_lines = [];
7 var move_num = 1;
8 var toplay = 'W';
9 var ims = 0;
10 var sort_refutation_lines_by_score = 0;
11 var highlight_from = undefined;
12 var highlight_to = undefined;
13 var unique = Math.random();
14
15 var fen = null;
16 var display_lines = [];
17 var current_display_line = null;
18 var current_display_move = null;
19
20 var request_update = function(board) {
21         $.ajax({
22                 url: "http://analysis.sesse.net/analysis.pl?ims=" + ims + "&unique=" + unique
23                 //url: "http://analysis.sesse.net:5000/analysis.pl?ims=" + ims + "&unique=" + unique
24         }).done(function(data, textstatus, xhr) {
25                 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
26                 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
27                 update_board(board, data, num_viewers);
28         }).fail(function() {
29                 // Wait ten seconds, then try again.
30                 setTimeout(function() { request_update(board); }, 10000);
31         });
32 }
33
34 var clear_arrows = function() {
35         for (var i = 0; i < arrows.length; ++i) {
36                 jsPlumb.detach(arrows[i].connection1);
37                 jsPlumb.detach(arrows[i].connection2);
38         }
39         arrows = [];
40
41         for (var i = 0; i < arrow_targets.length; ++i) {
42                 document.body.removeChild(arrow_targets[i]);
43         }
44         arrow_targets = [];
45         
46         occupied_by_arrows = [];        
47         for (var y = 0; y < 8; ++y) {
48                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
49         }
50 }
51
52 var redraw_arrows = function() {
53         for (var i = 0; i < arrows.length; ++i) {
54                 position_arrow(arrows[i]);
55         }
56 }
57
58 var sign = function(x) {
59         if (x > 0) {
60                 return 1;
61         } else if (x < 0) {
62                 return -1;
63         } else {
64                 return 0;
65         }
66 }
67
68 // See if drawing this arrow on the board would cause unduly amount of confusion.
69 var interfering_arrow = function(from, to) {
70         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
71         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
72         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
73         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
74
75         occupied_by_arrows[from_row][from_col] = true;
76
77         // Knight move: Just check that we haven't been at the destination before.
78         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
79             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
80                 return occupied_by_arrows[to_row][to_col];
81         }
82
83         // Sliding piece: Check if anything except the from-square is seen before.
84         var dx = sign(to_col - from_col);
85         var dy = sign(to_row - from_row);
86         var x = from_col;
87         var y = from_row;
88         do {
89                 x += dx;
90                 y += dy;
91                 if (occupied_by_arrows[y][x]) {
92                         return true;
93                 }
94                 occupied_by_arrows[y][x] = true;
95         } while (x != to_col || y != to_row);
96
97         return false;
98 }
99
100 var add_target = function() {
101         var elem = document.createElement("div");
102         $(elem).addClass("window");
103         elem.id = "target" + arrow_targets.length;
104         document.body.appendChild(elem);        
105         arrow_targets.push(elem);
106         return elem.id;
107 }
108         
109 var position_arrow = function(arrow) {
110         var zoom_factor = $("#board").width() / 400.0;
111         var line_width = arrow.line_width * zoom_factor;
112         var arrow_size = arrow.arrow_size * zoom_factor;
113
114         var square_width = $(".square-a8").width();
115         var from_y = (7 - arrow.from_row + 0.5)*square_width;
116         var to_y = (7 - arrow.to_row + 0.5)*square_width;
117         var from_x = (arrow.from_col + 0.5)*square_width;
118         var to_x = (arrow.to_col + 0.5)*square_width;
119
120         var dx = to_x - from_x;
121         var dy = to_y - from_y;
122         var len = Math.sqrt(dx * dx + dy * dy);
123         dx /= len;
124         dy /= len;
125         var pos = $(".square-a8").position();
126         $("#" + arrow.s1).css({ top: pos.top + from_y + (0.5 * arrow_size) * dy, left: pos.left + from_x + (0.5 * arrow_size) * dx });
127         $("#" + arrow.d1).css({ top: pos.top + to_y - (0.5 * arrow_size) * dy, left: pos.left + to_x - (0.5 * arrow_size) * dx });
128         $("#" + arrow.s1v).css({ top: pos.top + from_y - 0 * dy, left: pos.left + from_x - 0 * dx });
129         $("#" + arrow.d1v).css({ top: pos.top + to_y + 0 * dy, left: pos.left + to_x + 0 * dx });
130
131         if (arrow.connection1) {
132                 jsPlumb.detach(arrow.connection1);
133         }
134         if (arrow.connection2) {
135                 jsPlumb.detach(arrow.connection2);
136         }
137         if (current_display_line !== null) {
138                 delete arrow.connection1;
139                 delete arrow.connection2;
140                 return;
141         }
142         arrow.connection1 = jsPlumb.connect({
143                 source: arrow.s1,
144                 target: arrow.d1,
145                 connector:["Straight"],
146                 cssClass:"c1",
147                 endpoint:"Blank",
148                 endpointClass:"c1Endpoint",                                                                                                        
149                 anchor:"Continuous",
150                 paintStyle:{ 
151                         lineWidth:line_width,
152                         strokeStyle:arrow.fg_color,
153                         outlineWidth:1,
154                         outlineColor:"#666",
155                         opacity:"60%"
156                 }
157         });
158         arrow.connection2 = jsPlumb.connect({
159                 source: arrow.s1v,
160                 target: arrow.d1v,
161                 connector:["Straight"],
162                 cssClass:"vir",
163                 endpoint:"Blank",
164                 endpointClass:"c1Endpoint",                                                                                                        
165                 anchor:"Continuous",
166                 paintStyle:{ 
167                         lineWidth:0,
168                         strokeStyle:arrow.fg_color,
169                         outlineWidth:0,
170                         outlineColor:"#666",
171                 },
172                 overlays : [
173                         ["Arrow", {
174                                 cssClass:"l1arrow",
175                                 location:1.0,
176                                 width: arrow_size,
177                                 length: arrow_size,
178                                 paintStyle: { 
179                                         lineWidth:line_width,
180                                         strokeStyle:"#000",
181                                 },
182                         }]
183                 ]
184         });
185 }
186
187 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
188         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
189         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
190         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
191         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
192
193         // Create arrow.
194         var arrow = {
195                 s1: add_target(),
196                 d1: add_target(),
197                 s1v: add_target(),
198                 d1v: add_target(),
199                 from_col: from_col,
200                 from_row: from_row,
201                 to_col: to_col,
202                 to_row: to_row,
203                 line_width: line_width,
204                 arrow_size: arrow_size, 
205                 fg_color: fg_color
206         };
207
208         position_arrow(arrow);
209         arrows.push(arrow);
210 }
211
212 var compare_by_sort_key = function(refutation_lines, toplay, a, b) {
213         var ska = refutation_lines[a].sort_key;
214         var skb = refutation_lines[b].sort_key;
215         if (ska < skb) return -1;
216         if (ska > skb) return 1;
217         return 0;
218 };
219         
220 var compare_by_score = function(refutation_lines, toplay, a, b) {
221         var sa = parseInt(refutation_lines[b].score_sort_key);
222         var sb = parseInt(refutation_lines[a].score_sort_key);
223         if (toplay == 'B') {
224                 return sb - sa;
225         } else {
226                 return sa - sb;
227         }
228 }
229
230 // Fake multi-PV using the refutation lines. Find all “relevant” moves,
231 // sorted by quality, descending.
232 var find_nonstupid_moves = function(data, margin) {
233         // First of all, if there are any moves that are more than 0.5 ahead of
234         // the primary move, the refutation lines are probably bunk, so just
235         // kill them all. 
236         var best_score = undefined;
237         var pv_score = undefined;
238         for (var move in data.refutation_lines) {
239                 var score = parseInt(data.refutation_lines[move].score_sort_key);
240                 if (move == data.pv_uci[0]) {
241                         pv_score = score;
242                 }
243                 if (best_score === undefined || score > best_score) {
244                         best_score = score;
245                 }
246                 if (!(data.refutation_lines[move].depth >= 8)) {
247                         return [];
248                 }
249         }
250
251         if (best_score - pv_score > 50) {
252                 return [];
253         }
254
255         // Now find all moves that are within “margin” of the best score.
256         // The PV move will always be first.
257         var moves = [];
258         for (var move in data.refutation_lines) {
259                 var score = parseInt(data.refutation_lines[move].score_sort_key);
260                 if (move != data.pv_uci[0] && best_score - score <= margin) {
261                         moves.push(move);
262                 }
263         }
264         moves = moves.sort(function(a, b) { return compare_by_score(data.refutation_lines, a, b) });
265         moves.unshift(data.pv_uci[0]);
266
267         return moves;
268 }
269
270 var thousands = function(x) {
271         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
272 }
273
274 var print_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, limit) {
275         display_lines.push({
276                 start_fen: fen,
277                 uci_pv: uci_pv,
278                 pretty_pv: pretty_pv 
279         });
280
281         var pv = '';
282         var i = 0;
283         if (toplay == 'B') {
284                 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
285                 pv = move_num + '. … ' + move;
286                 toplay = 'W';
287                 ++i;    
288         }
289         ++move_num;
290         for ( ; i < pretty_pv.length; ++i) {
291                 var move = "<a class=\"move\" href=\"javascript:show_line(" + (display_lines.length - 1) + ", " + i + ");\">" + pretty_pv[i] + "</a>";
292
293                 if (toplay == 'W') {
294                         if (i > limit) {
295                                 return pv + ' (…)';
296                         }
297                         if (pv != '') {
298                                 pv += ' ';
299                         }
300                         pv += move_num + '. ' + move;
301                         ++move_num;
302                         toplay = 'B';
303                 } else {
304                         pv += ' ' + move;
305                         toplay = 'W';
306                 }
307         }
308         return pv;
309 }
310
311 var update_highlight = function()  {
312         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
313         if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
314                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
315                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
316         }
317 }
318
319 var update_refutation_lines = function(board) {
320         var tbl = $("#refutationlines");
321         tbl.empty();
322
323         moves = [];
324         for (var move in refutation_lines) {
325                 moves.push(move);
326         }
327         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
328         moves = moves.sort(function(a, b) { return compare(refutation_lines, toplay, a, b) });
329         for (var i = 0; i < moves.length; ++i) {
330                 var line = refutation_lines[moves[i]];
331
332                 var tr = document.createElement("tr");
333
334                 var move_td = document.createElement("td");
335                 tr.appendChild(move_td);
336                 $(move_td).addClass("move");
337                 if (line.pv_uci.length == 0) {
338                         $(move_td).text(line.pretty_move);
339                 } else {
340                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line.pretty_move + "</a>";
341                         $(move_td).html(move);
342                 }
343
344                 var score_td = document.createElement("td");
345                 tr.appendChild(score_td);
346                 $(score_td).addClass("score");
347                 $(score_td).text(line.pretty_score);
348
349                 var depth_td = document.createElement("td");
350                 tr.appendChild(depth_td);
351                 $(depth_td).addClass("depth");
352                 $(depth_td).text("d" + line.depth);
353
354                 var pv_td = document.createElement("td");
355                 tr.appendChild(pv_td);
356                 $(pv_td).addClass("pv");
357                 $(pv_td).html(print_pv(fen, line.pv_uci, line.pv_pretty, move_num, toplay, 10));
358
359                 tbl.append(tr);
360         }
361
362         // Make one of the links clickable and the other nonclickable.
363         if (sort_refutation_lines_by_score) {
364                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(0)\">Move</a>");
365                 $("#sortbyscore1").html("<strong>Score</strong>");
366         } else {
367                 $("#sortbyscore0").html("<strong>Move</strong>");
368                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(1)\">Score</a>");
369         }
370 }
371
372 var update_board = function(board, data, num_viewers) {
373         // The headline.
374         var headline = 'Analysis';
375         if (data.position.last_move !== 'none') {
376                 headline += ' after ' + data.position.move_num + '. ';
377                 if (data.position.toplay == 'W') {
378                         headline += '… ';
379                 }
380                 headline += data.position.last_move;
381         }
382
383         $("#headline").text(headline);
384
385         if (num_viewers === null) {
386                 $("#numviewers").text("");
387         } else if (num_viewers == 1) {
388                 $("#numviewers").text("You are the only current viewer");
389         } else {
390                 $("#numviewers").text(num_viewers + " current viewers");
391         }
392
393         // The score.
394         if (data.score !== null) {
395                 $("#score").text(data.score);
396         }
397
398         // The search stats.
399         if (data.nodes && data.nps && data.depth) {
400                 var stats = thousands(data.nodes) + ' nodes, ' + thousands(data.nps) + ' nodes/sec, depth ' + data.depth + ' ply';
401                 if (data.seldepth) {
402                         stats += ' (' + data.seldepth + ' selective)';
403                 }
404                 if (data.tbhits && data.tbhits > 0) {
405                         if (data.tbhits == 1) {
406                                 stats += ', one Nalimov hit';
407                         } else {
408                                 stats += ', ' + data.tbhits + ' Nalimov hits';
409                         }
410                 }
411                 
412
413                 $("#searchstats").text(stats);
414         }
415
416         // Update the board itself.
417         fen = data.position.fen;
418         update_displayed_line();
419
420         if (data.position.last_move_uci) {
421                 highlight_from = data.position.last_move_uci.substr(0, 2);
422                 highlight_to = data.position.last_move_uci.substr(2, 4);
423         } else {
424                 highlight_from = highlight_to = undefined;
425         }
426         update_highlight();
427
428         // Print the PV.
429         $("#pv").html(print_pv(data.position.fen, data.pv_uci, data.pv_pretty, data.position.move_num, data.position.toplay));
430
431         // Update the PV arrow.
432         clear_arrows();
433         if (data.pv_uci.length >= 1) {
434                 // draw a continuation arrow as long as it's the same piece
435                 for (var i = 0; i < data.pv_uci.length; i += 2) {
436                         var from = data.pv_uci[i].substr(0, 2);
437                         var to = data.pv_uci[i].substr(2,4);
438                         if ((i >= 2 && from != data.pv_uci[i - 2].substr(2, 4)) ||
439                              interfering_arrow(from, to)) {
440                                 break;
441                         }
442                         create_arrow(from, to, '#f66', 6, 20);
443                 }
444
445                 var alt_moves = find_nonstupid_moves(data, 30);
446                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
447                         create_arrow(alt_moves[i].substr(0, 2),
448                                      alt_moves[i].substr(2, 4), '#f66', 1, 10);
449                 }
450         }
451
452         // See if all semi-reasonable moves have only one possible response.
453         if (data.pv_uci.length >= 2) {
454                 var nonstupid_moves = find_nonstupid_moves(data, 300);
455                 var response = data.pv_uci[1];
456                 for (var i = 0; i < nonstupid_moves.length; ++i) {
457                         if (nonstupid_moves[i] == data.pv_uci[0]) {
458                                 // ignore the PV move for refutation lines.
459                                 continue;
460                         }
461                         if (!data.refutation_lines ||
462                             !data.refutation_lines[nonstupid_moves[i]] ||
463                             !data.refutation_lines[nonstupid_moves[i]].pv_uci ||
464                             data.refutation_lines[nonstupid_moves[i]].pv_uci.length < 1) {
465                                 // Incomplete PV, abort.
466                                 response = undefined;
467                                 break;
468                         }
469                         var this_response = data.refutation_lines[nonstupid_moves[i]].pv_uci[1];
470                         if (response !== this_response) {
471                                 // Different response depending on lines, abort.
472                                 response = undefined;
473                                 break;
474                         }
475                 }
476
477                 if (nonstupid_moves.length > 0 && response !== undefined) {
478                         create_arrow(response.substr(0, 2),
479                                      response.substr(2, 4), '#66f', 6, 20);
480                 }
481         }
482
483         // Update the refutation lines.
484         fen = data.position.fen;
485         move_num = data.position.move_num;
486         toplay = data.position.toplay;
487         refutation_lines = data.refutation_lines;
488         update_refutation_lines(board);
489
490         // Next update.
491         setTimeout(function() { request_update(board); }, 100);
492 }
493
494 var resort_refutation_lines = function(sort_by_score) {
495         sort_refutation_lines_by_score = sort_by_score;
496         update_refutation_lines(board);
497 }
498
499 var show_line = function(line_num, move_num) {
500         if (line_num == -1) {
501                 current_display_line = null;
502                 current_display_move = null;
503         } else {
504                 current_display_line = display_lines[line_num];
505                 current_display_move = move_num;
506         }
507         update_displayed_line();
508         update_highlight();
509         redraw_arrows();
510 }
511
512 var prev_move = function() {
513         --current_display_move;
514         update_displayed_line();
515 }
516
517 var next_move = function() {
518         ++current_display_move;
519         update_displayed_line();
520 }
521
522 var update_displayed_line = function() {
523         if (current_display_line === null) {
524                 $("#linenav").hide();
525                 $("#linemsg").show();
526                 board.position(fen);
527                 return;
528         }
529
530         $("#linenav").show();
531         $("#linemsg").hide();
532
533         if (current_display_move == 0) {
534                 $("#prevmove").html("Previous");
535         } else {
536                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
537         }
538         if (current_display_move == current_display_line.uci_pv.length - 1) {
539                 $("#nextmove").html("Next");
540         } else {
541                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
542         }
543
544         hiddenboard.position(current_display_line.start_fen, false);
545         for (var i = 0; i <= current_display_move; ++i) {
546                 var move = current_display_line.uci_pv[i];
547                 move = move.substr(0, 2) + "-" + move.substr(2, 4);
548                 hiddenboard.move(move, false);
549         }
550         board.position(hiddenboard.position());
551 }
552
553 var init = function() {
554         // Create board.
555         board = new ChessBoard('board', 'start');
556         hiddenboard = new ChessBoard('hiddenboard', 'start');
557
558         request_update(board);
559         $(window).resize(function() {
560                 board.resize();
561                 update_highlight();
562                 redraw_arrows();
563         });
564 };
565 $(document).ready(init);