Implement If-Modified-Since manually, since browser support is so strange.
[remoteglot] / www / js / remoteglot.js
1 var board = [];
2 var arrows = [];
3 var arrow_targets = [];
4 var occupied_by_arrows = [];
5 var ims = 0;
6 var highlight_from = undefined;
7 var highlight_to = undefined;
8
9 var request_update = function(board, first) {
10         $.ajax({
11                 //url: "http://analysis.sesse.net/analysis.pl?first=" + first
12                 url: "http://analysis.sesse.net:5000/analysis.pl?ims=" + ims
13         }).done(function(data, textstatus, xhr) {
14                 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
15                 update_board(board, data);
16         });
17 }
18
19 var clear_arrows = function() {
20         for (var i = 0; i < arrows.length; ++i) {
21                 jsPlumb.detach(arrows[i].connection1);
22                 jsPlumb.detach(arrows[i].connection2);
23         }
24         arrows = [];
25
26         for (var i = 0; i < arrow_targets.length; ++i) {
27                 document.body.removeChild(arrow_targets[i]);
28         }
29         arrow_targets = [];
30         
31         occupied_by_arrows = [];        
32         for (var y = 0; y < 8; ++y) {
33                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
34         }
35 }
36
37 var redraw_arrows = function() {
38         for (var i = 0; i < arrows.length; ++i) {
39                 position_arrow(arrows[i]);
40         }
41 }
42
43 var sign = function(x) {
44         if (x > 0) {
45                 return 1;
46         } else if (x < 0) {
47                 return -1;
48         } else {
49                 return 0;
50         }
51 }
52
53 // See if drawing this arrow on the board would cause unduly amount of confusion.
54 var interfering_arrow = function(from, to) {
55         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
56         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
57         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
58         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
59
60         occupied_by_arrows[from_row][from_col] = true;
61
62         // Knight move: Just check that we haven't been at the destination before.
63         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
64             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
65                 return occupied_by_arrows[to_row][to_col];
66         }
67
68         // Sliding piece: Check if anything except the from-square is seen before.
69         var dx = sign(to_col - from_col);
70         var dy = sign(to_row - from_row);
71         var x = from_col;
72         var y = from_row;
73         do {
74                 x += dx;
75                 y += dy;
76                 if (occupied_by_arrows[y][x]) {
77                         return true;
78                 }
79                 occupied_by_arrows[y][x] = true;
80         } while (x != to_col || y != to_row);
81
82         return false;
83 }
84
85 var add_target = function() {
86         var elem = document.createElement("div");
87         $(elem).addClass("window");
88         elem.id = "target" + arrow_targets.length;
89         document.body.appendChild(elem);        
90         arrow_targets.push(elem);
91         return elem.id;
92 }
93         
94 var position_arrow = function(arrow) {
95         var zoom_factor = $("#board").width() / 400.0;
96         var line_width = arrow.line_width * zoom_factor;
97         var arrow_size = arrow.arrow_size * zoom_factor;
98
99         var square_width = Math.floor(($("#board").width() - 1) / 8);
100         var from_y = (7 - arrow.from_row + 0.5)*square_width + 1;
101         var to_y = (7 - arrow.to_row + 0.5)*square_width + 1;
102         var from_x = (arrow.from_col + 0.5)*square_width + 1;
103         var to_x = (arrow.to_col + 0.5)*square_width + 1;
104
105         var dx = to_x - from_x;
106         var dy = to_y - from_y;
107         var len = Math.sqrt(dx * dx + dy * dy);
108         dx /= len;
109         dy /= len;
110         var pos = $("#board").position();
111         $("#" + arrow.s1).css({ top: pos.top + from_y + (0.5 * arrow_size) * dy, left: pos.left + from_x + (0.5 * arrow_size) * dx });
112         $("#" + arrow.d1).css({ top: pos.top + to_y - (0.5 * arrow_size) * dy, left: pos.left + to_x - (0.5 * arrow_size) * dx });
113         $("#" + arrow.s1v).css({ top: pos.top + from_y - 0 * dy, left: pos.left + from_x - 0 * dx });
114         $("#" + arrow.d1v).css({ top: pos.top + to_y + 0 * dy, left: pos.left + to_x + 0 * dx });
115
116         if (arrow.connection1) {
117                 jsPlumb.detach(arrow.connection1);
118         }
119         if (arrow.connection2) {
120                 jsPlumb.detach(arrow.connection2);
121         }
122         arrow.connection1 = jsPlumb.connect({
123                 source: arrow.s1,
124                 target: arrow.d1,
125                 connector:["Straight"],
126                 cssClass:"c1",
127                 endpoint:"Blank",
128                 endpointClass:"c1Endpoint",                                                                                                        
129                 anchor:"Continuous",
130                 paintStyle:{ 
131                         lineWidth:line_width,
132                         strokeStyle:arrow.fg_color,
133                         outlineWidth:1,
134                         outlineColor:"#666",
135                         opacity:"60%"
136                 }
137         });
138         arrow.connection2 = jsPlumb.connect({
139                 source: arrow.s1v,
140                 target: arrow.d1v,
141                 connector:["Straight"],
142                 cssClass:"vir",
143                 endpoint:"Blank",
144                 endpointClass:"c1Endpoint",                                                                                                        
145                 anchor:"Continuous",
146                 paintStyle:{ 
147                         lineWidth:0,
148                         strokeStyle:arrow.fg_color,
149                         outlineWidth:0,
150                         outlineColor:"#666",
151                 },
152                 overlays : [
153                         ["Arrow", {
154                                 cssClass:"l1arrow",
155                                 location:1.0,
156                                 width: arrow_size,
157                                 length: arrow_size,
158                                 paintStyle: { 
159                                         lineWidth:line_width,
160                                         strokeStyle:"#000",
161                                 },
162                         }]
163                 ]
164         });
165 }
166
167 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
168         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
169         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
170         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
171         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
172
173         // Create arrow.
174         var arrow = {
175                 s1: add_target(),
176                 d1: add_target(),
177                 s1v: add_target(),
178                 d1v: add_target(),
179                 from_col: from_col,
180                 from_row: from_row,
181                 to_col: to_col,
182                 to_row: to_row,
183                 line_width: line_width,
184                 arrow_size: arrow_size, 
185                 fg_color: fg_color
186         };
187
188         position_arrow(arrow);
189         arrows.push(arrow);
190 }
191
192 // Fake multi-PV using the refutation lines. Find all “relevant” moves,
193 // sorted by quality, descending.
194 var find_nonstupid_moves = function(data, margin) {
195         // First of all, if there are any moves that are more than 0.5 ahead of
196         // the primary move, the refutation lines are probably bunk, so just
197         // kill them all. 
198         var best_score = undefined;
199         var pv_score = undefined;
200         for (var move in data.refutation_lines) {
201                 var score = data.refutation_lines[move].score_sort_key;
202                 if (move == data.pv_uci[0]) {
203                         pv_score = score;
204                 }
205                 if (best_score === undefined || score > best_score) {
206                         best_score = score;
207                 }
208                 if (!(data.refutation_lines[move].depth >= 8)) {
209                         return [];
210                 }
211         }
212
213         if (best_score - pv_score > 50) {
214                 return [];
215         }
216
217         // Now find all moves that are within “margin” of the best score.
218         // The PV move will always be first.
219         var moves = [];
220         for (var move in data.refutation_lines) {
221                 var score = data.refutation_lines[move].score_sort_key;
222                 if (move != data.pv_uci[0] && best_score - score <= margin) {
223                         moves.push(move);
224                 }
225         }
226         moves = moves.sort(function(a, b) { return data.refutation_lines[b].score_sort_key - data.refutation_lines[a].score_sort_key; });
227         moves.unshift(data.pv_uci[0]);
228
229         return moves;
230 }
231
232 var thousands = function(x) {
233         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
234 }
235
236 var print_pv = function(pretty_pv, move_num, toplay, limit) {
237         var pv = '';
238         var i = 0;
239         if (toplay == 'B') {
240                 pv = move_num + '. … ' + pretty_pv[0];
241                 toplay = 'W';
242                 ++i;    
243         }
244         ++move_num;
245         for ( ; i < pretty_pv.length; ++i) {
246                 if (toplay == 'W') {
247                         if (i > limit) {
248                                 return pv + ' (…)';
249                         }
250                         if (pv != '') {
251                                 pv += ' ';
252                         }
253                         pv += move_num + '. ' + pretty_pv[i];
254                         ++move_num;
255                         toplay = 'B';
256                 } else {
257                         pv += ' ' + pretty_pv[i];
258                         toplay = 'W';
259                 }
260         }
261         return pv;
262 }
263
264 var compare_by_sort_key = function(data, a, b) {
265         var ska = data.refutation_lines[a].sort_key;
266         var skb = data.refutation_lines[b].sort_key;
267         if (ska < skb) return -1;
268         if (ska > skb) return 1;
269         return 0;
270 };
271         
272 var update_highlight = function()  {
273         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
274         if (highlight_from !== undefined && highlight_to !== undefined) {
275                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
276                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
277         }
278 }
279
280 var update_board = function(board, data) {
281         // The headline.
282         var headline = 'Analysis';
283         if (data.position.last_move !== 'none') {
284                 headline += ' after ' + data.position.move_num + '. ';
285                 if (data.position.toplay == 'W') {
286                         headline += '… ';
287                 }
288                 headline += data.position.last_move;
289         }
290
291         $("#headline").text(headline);
292
293         // The score.
294         if (data.score !== null) {
295                 $("#score").text(data.score);
296         }
297
298         // The search stats.
299         if (data.nodes && data.nps && data.depth) {
300                 var stats = thousands(data.nodes) + ' nodes, ' + thousands(data.nps) + ' nodes/sec, depth ' + data.depth + ' ply';
301                 if (data.seldepth) {
302                         stats += ' (' + data.seldepth + ' selective)';
303                 }
304                 if (data.tbhits && data.tbhits > 0) {
305                         if (data.tbhits == 1) {
306                                 stats += ', one Nalimov hit';
307                         } else {
308                                 stats += ', ' + data.tbhits + ' Nalimov hits';
309                         }
310                 }
311                 
312
313                 $("#searchstats").text(stats);
314         }
315
316         // Update the board itself.
317         board.position(data.position.fen);
318
319         if (data.position.last_move_uci) {
320                 highlight_from = data.position.last_move_uci.substr(0, 2);
321                 highlight_to = data.position.last_move_uci.substr(2, 4);
322         } else {
323                 highlight_from = highlight_to = undefined;
324         }
325         update_highlight();
326
327         // Print the PV.
328         var pv = print_pv(data.pv_pretty, data.position.move_num, data.position.toplay);
329         $("#pv").text(pv);
330
331         // Update the PV arrow.
332         clear_arrows();
333         if (data.pv_uci.length >= 1) {
334                 // draw a continuation arrow as long as it's the same piece
335                 for (var i = 0; i < data.pv_uci.length; i += 2) {
336                         var from = data.pv_uci[i].substr(0, 2);
337                         var to = data.pv_uci[i].substr(2,4);
338                         if ((i >= 2 && from != data.pv_uci[i - 2].substr(2, 4)) ||
339                              interfering_arrow(from, to)) {
340                                 break;
341                         }
342                         create_arrow(from, to, '#f66', 6, 20);
343                 }
344
345                 var alt_moves = find_nonstupid_moves(data, 30);
346                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
347                         create_arrow(alt_moves[i].substr(0, 2),
348                                      alt_moves[i].substr(2, 4), '#f66', 1, 10);
349                 }
350         }
351
352         // See if all semi-reasonable moves have only one possible response.
353         if (data.pv_uci.length >= 2) {
354                 var nonstupid_moves = find_nonstupid_moves(data, 300);
355                 var response = data.pv_uci[1];
356                 for (var i = 0; i < nonstupid_moves.length; ++i) {
357                         if (nonstupid_moves[i] == data.pv_uci[0]) {
358                                 // ignore the PV move for refutation lines.
359                                 continue;
360                         }
361                         if (!data.refutation_lines ||
362                             !data.refutation_lines[nonstupid_moves[i]] ||
363                             !data.refutation_lines[nonstupid_moves[i]].pv_uci ||
364                             data.refutation_lines[nonstupid_moves[i]].pv_uci.length < 1) {
365                                 // Incomplete PV, abort.
366                                 response = undefined;
367                                 break;
368                         }
369                         var this_response = data.refutation_lines[nonstupid_moves[i]].pv_uci[1];
370                         if (response !== this_response) {
371                                 // Different response depending on lines, abort.
372                                 response = undefined;
373                                 break;
374                         }
375                 }
376
377                 if (nonstupid_moves.length > 0 && response !== undefined) {
378                         create_arrow(response.substr(0, 2),
379                                      response.substr(2, 4), '#66f', 6, 20);
380                 }
381         }
382
383         // Show the refutation lines.
384         var tbl = $("#refutationlines");
385         tbl.empty();
386
387         moves = [];
388         for (var move in data.refutation_lines) {
389                 moves.push(move);
390         }
391         moves = moves.sort(function(a, b) { return compare_by_sort_key(data, a, b) });
392         for (var i = 0; i < moves.length; ++i) {
393                 var line = data.refutation_lines[moves[i]];
394
395                 var tr = document.createElement("tr");
396
397                 var move_td = document.createElement("td");
398                 tr.appendChild(move_td);
399                 $(move_td).addClass("move");
400                 $(move_td).text(line.pretty_move);
401
402                 var score_td = document.createElement("td");
403                 tr.appendChild(score_td);
404                 $(score_td).addClass("score");
405                 $(score_td).text(line.pretty_score);
406
407                 var depth_td = document.createElement("td");
408                 tr.appendChild(depth_td);
409                 $(depth_td).addClass("depth");
410                 $(depth_td).text("d" + line.depth);
411
412                 var pv_td = document.createElement("td");
413                 tr.appendChild(pv_td);
414                 $(pv_td).addClass("pv");
415                 $(pv_td).text(print_pv(line.pv_pretty, data.position.move_num, data.position.toplay, 10));
416
417                 tbl.append(tr);
418         }
419
420         // Next update.
421         setTimeout(function() { request_update(board, 0); }, 100);
422 }
423
424 var init = function() {
425         // Create board.
426         board = new ChessBoard('board', 'start');
427
428         request_update(board, 1);
429         $(window).resize(function() {
430                 board.resize();
431                 update_highlight();
432                 redraw_arrows();
433         });
434 };
435 $(document).ready(init);