3 /** @type {window.ChessBoard} @private */
19 /** @type {Array.<Array.<boolean>>} */
20 var occupied_by_arrows = [];
22 var refutation_lines = [];
24 /** @type {!number} @private */
27 /** @type {!string} @private */
30 /** @type {number} @private */
33 /** @type {boolean} @private */
34 var sort_refutation_lines_by_score = true;
36 /** @type {boolean} @private */
37 var truncate_display_history = true;
39 /** @type {!string|undefined} @private */
40 var highlight_from = undefined;
42 /** @type {!string|undefined} @private */
43 var highlight_to = undefined;
45 /** @type {?jQuery} @private */
46 var highlighted_move = null;
48 /** @type {?number} @private */
51 /** The current position on the board, represented as a FEN string.
59 * uci_pv: Array.<string>,
60 * pretty_pv: Array.<string>,
65 /** @type {Array.<DisplayLine>}
68 var display_lines = [];
70 /** @type {?DisplayLine} @private */
71 var current_display_line = null;
73 /** @type {?number} @private */
74 var current_display_move = null;
76 var supports_html5_storage = function() {
78 return 'localStorage' in window && window['localStorage'] !== null;
84 // Make the unique token persistent so people refreshing the page won't count twice.
85 // Of course, you can never fully protect against people deliberately wanting to spam.
86 var get_unique = function() {
87 var use_local_storage = supports_html5_storage();
88 if (use_local_storage && localStorage['unique']) {
89 return localStorage['unique'];
91 var unique = Math.random();
92 if (use_local_storage) {
93 localStorage['unique'] = unique;
98 var request_update = function() {
100 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
101 }).done(function(data, textstatus, xhr) {
102 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
103 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
105 update_num_viewers(num_viewers);
108 setTimeout(function() { request_update(); }, 100);
110 // Wait ten seconds, then try again.
111 setTimeout(function() { request_update(); }, 10000);
115 var clear_arrows = function() {
116 for (var i = 0; i < arrows.length; ++i) {
118 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
119 delete arrows[i].svg;
124 occupied_by_arrows = [];
125 for (var y = 0; y < 8; ++y) {
126 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
130 var redraw_arrows = function() {
131 for (var i = 0; i < arrows.length; ++i) {
132 position_arrow(arrows[i]);
136 /** @param {!number} x
139 var sign = function(x) {
149 /** See if drawing this arrow on the board would cause unduly amount of confusion.
150 * @param {!string} from The square the arrow is from (e.g. e4).
151 * @param {!string} to The square the arrow is to (e.g. e4).
154 var interfering_arrow = function(from, to) {
155 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
156 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
157 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
158 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
160 occupied_by_arrows[from_row][from_col] = true;
162 // Knight move: Just check that we haven't been at the destination before.
163 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
164 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
165 return occupied_by_arrows[to_row][to_col];
168 // Sliding piece: Check if anything except the from-square is seen before.
169 var dx = sign(to_col - from_col);
170 var dy = sign(to_row - from_row);
176 if (occupied_by_arrows[y][x]) {
179 occupied_by_arrows[y][x] = true;
180 } while (x != to_col || y != to_row);
185 /** Find a point along the coordinate system given by the given line,
186 * <t> units forward from the start of the line, <u> units to the right of it.
187 * @param {!number} x1
188 * @param {!number} x2
189 * @param {!number} y1
190 * @param {!number} y2
193 * @return {!string} The point in "x y" form, suitable for SVG paths.
195 var point_from_start = function(x1, y1, x2, y2, t, u) {
199 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
203 var x = x1 + dx * t + dy * u;
204 var y = y1 + dy * t - dx * u;
208 /** Find a point along the coordinate system given by the given line,
209 * <t> units forward from the end of the line, <u> units to the right of it.
210 * @param {!number} x1
211 * @param {!number} x2
212 * @param {!number} y1
213 * @param {!number} y2
216 * @return {!string} The point in "x y" form, suitable for SVG paths.
218 var point_from_end = function(x1, y1, x2, y2, t, u) {
222 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
226 var x = x2 + dx * t + dy * u;
227 var y = y2 + dy * t - dx * u;
231 var position_arrow = function(arrow) {
233 arrow.svg.parentElement.removeChild(arrow.svg);
236 if (current_display_line !== null) {
240 var pos = $(".square-a8").position();
242 var zoom_factor = $("#board").width() / 400.0;
243 var line_width = arrow.line_width * zoom_factor;
244 var arrow_size = arrow.arrow_size * zoom_factor;
246 var square_width = $(".square-a8").width();
247 var from_y = (7 - arrow.from_row + 0.5)*square_width;
248 var to_y = (7 - arrow.to_row + 0.5)*square_width;
249 var from_x = (arrow.from_col + 0.5)*square_width;
250 var to_x = (arrow.to_col + 0.5)*square_width;
252 var SVG_NS = "http://www.w3.org/2000/svg";
253 var XHTML_NS = "http://www.w3.org/1999/xhtml";
254 var svg = document.createElementNS(SVG_NS, "svg");
255 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
256 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
257 svg.setAttribute("style", "position: absolute");
258 svg.setAttribute("position", "absolute");
259 svg.setAttribute("version", "1.1");
260 svg.setAttribute("class", "c1");
261 svg.setAttribute("xmlns", XHTML_NS);
269 var outline = document.createElementNS(SVG_NS, "path");
270 outline.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
271 outline.setAttribute("xmlns", XHTML_NS);
272 outline.setAttribute("stroke", "#666");
273 outline.setAttribute("stroke-width", line_width + 2);
274 outline.setAttribute("fill", "none");
275 svg.appendChild(outline);
277 var path = document.createElementNS(SVG_NS, "path");
278 path.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
279 path.setAttribute("xmlns", XHTML_NS);
280 path.setAttribute("stroke", arrow.fg_color);
281 path.setAttribute("stroke-width", line_width);
282 path.setAttribute("fill", "none");
283 svg.appendChild(path);
285 // Then the arrow head.
286 var head = document.createElementNS(SVG_NS, "path");
287 head.setAttribute("d",
288 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
289 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
290 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
291 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
292 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
293 head.setAttribute("xmlns", XHTML_NS);
294 head.setAttribute("stroke", "#000");
295 head.setAttribute("stroke-width", "1");
296 head.setAttribute("fill", arrow.fg_color);
297 svg.appendChild(head);
299 $(svg).css({ top: pos.top, left: pos.left });
300 document.body.appendChild(svg);
305 * @param {!string} from_square
306 * @param {!string} to_square
307 * @param {!string} fg_color
308 * @param {number} line_width
309 * @param {number} arrow_size
311 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
312 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
313 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
314 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
315 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
323 line_width: line_width,
324 arrow_size: arrow_size,
328 position_arrow(arrow);
332 var compare_by_sort_key = function(refutation_lines, a, b) {
333 var ska = refutation_lines[a]['sort_key'];
334 var skb = refutation_lines[b]['sort_key'];
335 if (ska < skb) return -1;
336 if (ska > skb) return 1;
340 var compare_by_score = function(refutation_lines, a, b) {
341 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
342 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
347 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
348 * sorted by quality, descending.
350 * @param {!Object} data
351 * @param {number} margin The maximum number of centipawns worse than the
352 * best move can be and still be included.
353 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
354 * moves, in score order.
356 var find_nonstupid_moves = function(data, margin) {
357 // First of all, if there are any moves that are more than 0.5 ahead of
358 // the primary move, the refutation lines are probably bunk, so just
360 var best_score = undefined;
361 var pv_score = undefined;
362 for (var move in data['refutation_lines']) {
363 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
364 if (move == data['pv_uci'][0]) {
367 if (best_score === undefined || score > best_score) {
370 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
375 if (best_score - pv_score > 50) {
379 // Now find all moves that are within “margin” of the best score.
380 // The PV move will always be first.
382 for (var move in data['refutation_lines']) {
383 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
384 if (move != data['pv_uci'][0] && best_score - score <= margin) {
388 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
389 moves.unshift(data['pv_uci'][0]);
398 var thousands = function(x) {
399 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
403 * @param {!string} fen
404 * @param {Array.<string>} uci_pv
405 * @param {number} move_num
406 * @param {!string} toplay
407 * @param {number=} opt_limit
408 * @param {boolean=} opt_showlast
410 var add_pv = function(fen, uci_pv, move_num, toplay, opt_limit, opt_showlast) {
411 var hiddenboard = new Chess();
412 hiddenboard.load(fen);
413 for (var i = 0; i < uci_pv.length; ++i) {
414 hiddenboard.move(ucimove_to_chessjs_move(uci_pv[i]));
416 var pretty_pv = hiddenboard.history();
421 pretty_pv: pretty_pv,
422 line_number: display_lines.length
424 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
428 * @param {number} line_num
429 * @param {Array.<string>} pretty_pv
430 * @param {number} move_num
431 * @param {!string} toplay
432 * @param {number=} opt_limit
433 * @param {boolean=} opt_showlast
435 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
438 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
439 // Truncate the PV at the beginning (instead of at the end).
440 // We assume here that toplay is 'W'. We also assume that if
441 // opt_showlast is set, then it is the history, and thus,
442 // the UI should be to expand the history.
443 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
444 i = pretty_pv.length - opt_limit;
449 } else if (toplay == 'B' && pretty_pv.length > 0) {
450 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
451 pv = move_num + '. … ' + move;
456 for ( ; i < pretty_pv.length; ++i) {
457 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
460 if (i > opt_limit && !opt_showlast) {
466 pv += move_num + '. ' + move;
477 var update_highlight = function() {
478 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
479 if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
480 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
481 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
485 var update_history = function() {
486 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
487 $("#history").html("No history");
488 } else if (truncate_display_history) {
489 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
492 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
493 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
498 * @param {!boolean} truncate_history
500 var collapse_history = function(truncate_history) {
501 truncate_display_history = truncate_history;
504 window['collapse_history'] = collapse_history;
506 var update_refutation_lines = function() {
510 if (display_lines.length > 2) {
511 display_lines = [ display_lines[0], display_lines[1] ];
514 var tbl = $("#refutationlines");
518 for (var move in refutation_lines) {
521 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
522 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
523 for (var i = 0; i < moves.length; ++i) {
524 var line = refutation_lines[moves[i]];
526 var tr = document.createElement("tr");
528 var move_td = document.createElement("td");
529 tr.appendChild(move_td);
530 $(move_td).addClass("move");
531 if (line['pv_uci'].length == 0) {
532 $(move_td).text(line['pretty_move']);
534 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
535 $(move_td).html(move);
538 var score_td = document.createElement("td");
539 tr.appendChild(score_td);
540 $(score_td).addClass("score");
541 $(score_td).text(line['pretty_score']);
543 var depth_td = document.createElement("td");
544 tr.appendChild(depth_td);
545 $(depth_td).addClass("depth");
546 $(depth_td).text("d" + line['depth']);
548 var pv_td = document.createElement("td");
549 tr.appendChild(pv_td);
550 $(pv_td).addClass("pv");
551 $(pv_td).html(add_pv(fen, line['pv_uci'], move_num, toplay, 10));
556 // Make one of the links clickable and the other nonclickable.
557 if (sort_refutation_lines_by_score) {
558 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
559 $("#sortbyscore1").html("<strong>Score</strong>");
561 $("#sortbyscore0").html("<strong>Move</strong>");
562 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
567 * @param {Object} data
569 var update_board = function(data) {
574 if (data['position']['player_w'] && data['position']['player_b']) {
575 headline = data['position']['player_w'] + '–' +
576 data['position']['player_b'] + ', analysis';
578 headline = 'Analysis';
581 if (data['position']['last_move'] !== 'none') {
582 if (data['position']['toplay'] == 'W') {
583 last_move = (data['position']['move_num']-1) + '… ';
585 last_move = data['position']['move_num'] + '. ';
587 last_move += data['position']['last_move'];
589 headline += ' after ' + last_move;
594 $("#headline").text(headline);
597 if (data['id'] && data['id']['name'] !== null) {
598 $("#engineid").text(data['id']['name']);
602 if (data['score'] !== null) {
603 $("#score").text(data['score']);
606 var title_elems = [];
607 if (data['short_score'] !== undefined && data['short_score'] !== null) {
608 title_elems.push(data['short_score']);
610 if (last_move !== null) {
611 title_elems.push(last_move);
614 if (title_elems.length != 0) {
615 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
617 document.title = 'analysis.sesse.net';
621 if (data['tablebase'] == 1) {
622 $("#searchstats").text("Tablebase result");
623 } else if (data['nodes'] && data['nps'] && data['depth']) {
624 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
625 if (data['seldepth']) {
626 stats += ' (' + data['seldepth'] + ' selective)';
628 if (data['tbhits'] && data['tbhits'] > 0) {
629 if (data['tbhits'] == 1) {
630 stats += ', one Syzygy hit';
632 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
636 $("#searchstats").text(stats);
638 $("#searchstats").text("");
641 // Update the board itself.
642 fen = data['position']['fen'];
643 update_displayed_line();
645 if (data['position']['last_move_uci']) {
646 highlight_from = data['position']['last_move_uci'].substr(0, 2);
647 highlight_to = data['position']['last_move_uci'].substr(2, 2);
649 highlight_from = highlight_to = undefined;
653 // Print the history.
654 if (data['position']['history']) {
655 add_pv('start', data['position']['history'], 1, 'W', 8, true);
657 display_lines.push(null);
662 $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['position']['move_num'], data['position']['toplay']));
664 // Update the PV arrow.
666 if (data['pv_uci'].length >= 1) {
667 // draw a continuation arrow as long as it's the same piece
668 for (var i = 0; i < data['pv_uci'].length; i += 2) {
669 var from = data['pv_uci'][i].substr(0, 2);
670 var to = data['pv_uci'][i].substr(2,4);
671 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
672 interfering_arrow(from, to)) {
675 create_arrow(from, to, '#f66', 6, 20);
678 var alt_moves = find_nonstupid_moves(data, 30);
679 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
680 create_arrow(alt_moves[i].substr(0, 2),
681 alt_moves[i].substr(2, 2), '#f66', 1, 10);
685 // See if all semi-reasonable moves have only one possible response.
686 if (data['pv_uci'].length >= 2) {
687 var nonstupid_moves = find_nonstupid_moves(data, 300);
688 var response = data['pv_uci'][1];
689 for (var i = 0; i < nonstupid_moves.length; ++i) {
690 if (nonstupid_moves[i] == data['pv_uci'][0]) {
691 // ignore the PV move for refutation lines.
694 if (!data['refutation_lines'] ||
695 !data['refutation_lines'][nonstupid_moves[i]] ||
696 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
697 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
698 // Incomplete PV, abort.
699 response = undefined;
702 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
703 if (response !== this_response) {
704 // Different response depending on lines, abort.
705 response = undefined;
710 if (nonstupid_moves.length > 0 && response !== undefined) {
711 create_arrow(response.substr(0, 2),
712 response.substr(2, 2), '#66f', 6, 20);
716 // Update the refutation lines.
717 fen = data['position']['fen'];
718 move_num = data['position']['move_num'];
719 toplay = data['position']['toplay'];
720 refutation_lines = data['refutation_lines'];
721 update_refutation_lines();
725 * @param {number} num_viewers
727 var update_num_viewers = function(num_viewers) {
728 if (num_viewers === null) {
729 $("#numviewers").text("");
730 } else if (num_viewers == 1) {
731 $("#numviewers").text("You are the only current viewer");
733 $("#numviewers").text(num_viewers + " current viewers");
738 * @param {boolean} sort_by_score
740 var resort_refutation_lines = function(sort_by_score) {
741 sort_refutation_lines_by_score = sort_by_score;
742 update_refutation_lines();
744 window['resort_refutation_lines'] = resort_refutation_lines;
747 * @param {boolean} truncate_history
749 var set_truncate_history = function(truncate_history) {
750 truncate_display_history = truncate_history;
751 update_refutation_lines();
753 window['set_truncate_history'] = set_truncate_history;
756 * @param {number} line_num
757 * @param {number} move_num
759 var show_line = function(line_num, move_num) {
760 if (line_num == -1) {
761 current_display_line = null;
762 current_display_move = null;
764 current_display_line = display_lines[line_num];
765 current_display_move = move_num;
767 update_displayed_line();
771 window['show_line'] = show_line;
773 var prev_move = function() {
774 if (current_display_move > -1) {
775 --current_display_move;
777 update_displayed_line();
779 window['prev_move'] = prev_move;
781 var next_move = function() {
782 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
783 ++current_display_move;
785 update_displayed_line();
787 window['next_move'] = next_move;
789 var update_displayed_line = function() {
790 if (highlighted_move !== null) {
791 highlighted_move.removeClass('highlight');
793 if (current_display_line === null) {
794 $("#linenav").hide();
795 $("#linemsg").show();
800 $("#linenav").show();
801 $("#linemsg").hide();
803 if (current_display_move <= 0) {
804 $("#prevmove").html("Previous");
806 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
808 if (current_display_move == current_display_line.uci_pv.length - 1) {
809 $("#nextmove").html("Next");
811 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
814 var hiddenboard = new Chess();
815 hiddenboard.load(current_display_line.start_fen);
816 for (var i = 0; i <= current_display_move; ++i) {
817 hiddenboard.move(ucimove_to_chessjs_move(current_display_line.uci_pv[i]));
820 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
821 highlighted_move.addClass('highlight');
823 board.position(hiddenboard.fen());
826 var ucimove_to_chessjs_move = function(move) {
827 var source = move.substr(0, 2);
828 var target = move.substr(2, 2);
829 var promo = move.substr(4, 1);
832 return { from: source, to: target };
834 return { from: source, to: target, promotion: promo };
838 var init = function() {
839 unique = get_unique();
842 board = new window.ChessBoard('board', 'start');
845 $(window).resize(function() {
850 $(window).keyup(function(event) {
851 if (event.which == 39) {
853 } else if (event.which == 37) {
858 $(document).ready(init);