chiark / gitweb /
script: rectsel_started_on_whynot
[otter.git] / templates / script.ts
1 // -*- JavaScript -*-
2
3 // Copyright 2020-2021 Ian Jackson and contributors to Otter
4 // SPDX-License-Identifier: AGPL-3.0-or-later
5 // There is NO WARRANTY.
6
7 // elemnts for a piece
8 //
9 // In svg toplevel
10 //
11 //   uelem
12 //      #use{}
13 //      <use id="use{}", href="#piece{}" x= y= >
14 //         .piece   piece id (static)
15 //      container to allow quick movement and hang stuff off
16 //
17 //   delem
18 //      #defs{}
19 //      <def id="defs{}">
20 //
21 // And in each delem
22 //
23 //   pelem
24 //   #piece{}
25 //         .dragraise   dragged more than this ?  raise to top!
26 //         .special     enum RenderSpecial
27 //      <g id="piece{}" >
28 //      currently-displayed version of the piece
29 //      to allow addition/removal of selected indication
30 //      contains 1 or 3 subelements:
31 //      one is straight from server and not modified
32 //      one is possible <use href="#select{}" >
33 //      one is possible <use href="#halo{}" >
34 //
35 //   #select{}
36 //      generated by server, referenced by JS in pelem for selection
37 //
38 //   #def.{}.stuff
39 //      generated by server, reserved for Piece trait impl
40
41 type PieceId = string;
42 type PlayerId = string;
43 type Pos = [number, number];
44 type Rect = [Pos, Pos];
45 type ClientSeq = number;
46 type Generation = number;
47 type UoKind = 'Client' | "Global"| "Piece" | "ClientExtra" | "GlobalExtra";
48 type WhatResponseToClientOp = "Predictable" | "Unpredictable" | "UpdateSvg";
49 type HeldUsRaising = "NotYet" | "Lowered" | "Raised"
50 type Timestamp = number; // unix time_t, will break in 285My
51 type Layout = 'Portrait' | 'Landscape';
52 type PieceMoveable = "No" | "IfWresting" | "Yes";
53 type CompassAngle = number;
54 type FaceId = number;
55
56 type UoDescription = {
57   kind: UoKind;
58   wrc: WhatResponseToClientOp,
59   def_key: string,
60   opname: string,
61   desc: string,
62 }
63
64 type UoRecord = UoDescription & {
65   targets: PieceId[] | null,
66 }
67
68 type ZCoord = string;
69
70 // On load, starts from SessionPieceLoadJson (Rust-only)
71 // On update, updated field-by-field from PreparedPieceState (Rust&JS)
72 type PieceInfo = {
73   held : PlayerId | null,
74   cseq_main : number | null,
75   cseq_loose: number | null,
76   cseq_updatesvg : number | null,
77   z : ZCoord,
78   zg : Generation,
79   angle: CompassAngle,
80   pinned: boolean,
81   moveable: PieceMoveable,
82   rotateable: boolean,
83   multigrab: boolean,
84   desc: string,
85   uos : UoDescription[],
86   uelem : SVGGraphicsElement,
87   delem : SVGGraphicsElement,
88   pelem : SVGGraphicsElement,
89   queued_moves : number,
90   last_seen_moved : DOMHighResTimeStamp | null, // non-0 means halo'd
91   held_us_inoccult: boolean,
92   held_us_raising: HeldUsRaising,
93   bbox: Rect,
94   drag_delta: number,
95   special: SpecialRendering | null,
96 }
97
98 type SpecialRendering = {
99   kind: string,
100   stop: SpecialRenderingCallback,
101 }
102
103 let wasm : InitOutput;
104
105 var pieces : { [piece: string]: PieceInfo } = Object.create(null);
106
107 type MessageHandler = (op: Object) => void;
108 type PieceHandler = (piece: PieceId, p: PieceInfo, info: Object) => void;
109 type PieceErrorHandler = (piece: PieceId, p: PieceInfo, m: PieceOpError)
110   => boolean;
111 type SpecialRenderingCallback =
112   (piece: PieceId, p: PieceInfo, s: SpecialRendering) => void;
113 interface DispatchTable<H> { [key: string]: H };
114
115 var otter_debug: boolean;
116
117 // from header
118 var movehist_len_i: number;
119 var movehist_len_max: number;
120 var movehist_lens: number[];
121
122 // todo turn all var into let
123 // todo any exceptions should have otter in them or something
124 var globalinfo_elem : HTMLElement;
125 var layout: Layout;
126 var held_surround_colour: string;
127 var general_timeout : number = 10000;
128 var messages : DispatchTable<MessageHandler> = Object();
129 var special_renderings : DispatchTable<SpecialRenderingCallback> = Object();
130 var pieceops : DispatchTable<PieceHandler> = Object();
131 var update_error_handlers : DispatchTable<MessageHandler> = Object();
132 var piece_error_handlers : DispatchTable<PieceErrorHandler> = Object();
133 var our_dnd_type = "text/puvnex-game-server-dummy";
134 var api_queue : [string, Object][] = [];
135 var api_posting = false;
136 var us : PlayerId;
137 var gen : Generation = 0;
138 var cseq : ClientSeq = 0;
139 var ctoken : string;
140 var uo_map : { [k: string]: UoRecord | null } = Object.create(null);
141 var keyops_local : { [opname: string]: (uo: UoRecord) => void } = Object();
142 var last_log_ts: wasm_bindgen.TimestampAbbreviator;
143 var last_zoom_factor : number = 1.0;
144 var firefox_bug_zoom_factor_compensation : number = 1.0;
145 var test_update_hook : () => void;
146
147 var svg_ns : string;
148 var space : SVGGraphicsElement;
149 var pieces_marker : SVGGraphicsElement;
150 var defs_marker : SVGGraphicsElement;
151 var movehist_start: SVGGraphicsElement;
152 var movehist_end: SVGGraphicsElement;
153 var rectsel_path: SVGGraphicsElement;
154 var log_elem : HTMLElement;
155 var logscroll_elem : HTMLElement;
156 var status_node : HTMLElement;
157 var uos_node : HTMLElement;
158 var zoom_val : HTMLInputElement;
159 var zoom_btn : HTMLInputElement;
160 var links_elem : HTMLElement;
161 var was_wresting: boolean;
162 var wresting: boolean;
163 var occregions: wasm_bindgen.RegionList;
164 let special_count: number | null;
165
166 var movehist_gen: number = 0;
167 const MOVEHIST_ENDS = 2.5;
168 const SPECIAL_MULTI_DELTA_EACH = 3;
169 const SPECIAL_MULTI_DELTA_MAX = 18;
170
171 type PaneName = string;
172 const pane_keys : { [key: string]: PaneName } = {
173   "H" : "help",
174   "U" : "players",
175   "B" : "bundles",
176 };
177
178 const uo_kind_prec : { [kind: string]: number } = {
179   'GlobalExtra' :  50,
180   'Client'      :  70,
181   'Global'      : 100,
182   'Piece'       : 200,
183   'ClientExtra' : 500,
184 }
185
186 type PlayerInfo = {
187   dasharray : string,
188   nick: string,
189 }
190 var players : { [player: string]: PlayerInfo };
191
192 type MovementRecord = { // for yellow halo, unrelasted to movehist
193   piece: PieceId,
194   p: PieceInfo,
195   this_motion: DOMHighResTimeStamp,
196 }
197 var movements : MovementRecord[] = [];
198
199 function xhr_post_then(url : string, data: string,
200                        good : (xhr: XMLHttpRequest) => void) {
201   var xhr : XMLHttpRequest = new XMLHttpRequest();
202   xhr.onreadystatechange = function(){
203     if (xhr.readyState != XMLHttpRequest.DONE) { return; }
204     if (xhr.status != 200) { xhr_report_error(xhr); }
205     else { good(xhr); }
206   };
207   xhr.timeout = general_timeout;
208   xhr.open('POST',url);
209   xhr.setRequestHeader('Content-Type','application/json');
210   xhr.send(data);
211 }
212
213 function xhr_report_error(xhr: XMLHttpRequest) {
214   json_report_error({
215     statusText : xhr.statusText,
216     responseText : xhr.responseText,
217   });
218 }
219
220 function json_report_error(error_for_json: Object) {
221   let error_message = JSON.stringify(error_for_json);
222   string_report_error(error_message);
223 }
224
225 function string_report_error(error_message: String) {
226   string_report_error_raw('Error (reloading may help?): ' + error_message)
227 }
228 function string_report_error_raw(error_message: String) {
229   let errornode = document.getElementById('error')!;
230   errornode.textContent += '\n' + error_message;
231   console.error("ERROR reported via log", error_message);
232   // todo want to fix this for at least basic game reconfigs, auto-reload?
233 }
234
235 function api_immediate(meth: string, data: Object) {
236   api_queue.push([meth, data]);
237   api_check();
238 }
239 function api_delay(meth: string, data: Object) {
240   if (api_queue.length==0) window.setTimeout(api_check, 10);
241   api_queue.push([meth, data]);
242 }
243 function api_check() {
244   if (api_posting) { return; }
245   if (!api_queue.length) { test_update_hook(); return; }
246   do {
247     var [meth, data] = api_queue.shift()!;
248     if (meth != 'm') break;
249     let piece = (data as any).piece;
250     let p = pieces[piece];
251     if (p == null) break;
252     p.queued_moves--;
253     if (p.queued_moves == 0) break;
254   } while (api_queue.length);
255   api_posting = true;
256   xhr_post_then('/_/api/'+meth, JSON.stringify(data), api_posted);
257 }
258 function api_posted() {
259   api_posting = false;
260   api_check();
261 }
262
263 function api_piece_x(f: (meth: string, payload: Object) => void,
264                      loose: boolean,
265                      meth: string,
266                      piece: PieceId, p: PieceInfo,
267                      op: Object) {
268   clear_halo(piece,p);
269   cseq += 1;
270   if (loose) {
271     p.cseq_loose = cseq;
272   } else {
273     p.cseq_main = cseq;
274     p.cseq_loose = null;
275   }
276   f(meth, {
277     ctoken : ctoken,
278     piece : piece,
279     gen : gen,
280     cseq : cseq,
281     op : op,
282     loose: loose,
283   })
284 }
285 function api_piece(meth: string,
286                    piece: PieceId, p: PieceInfo,
287                    op: Object) {
288   api_piece_x(api_immediate, false,meth, piece, p, op);
289 }
290
291 function svg_element(id: string): SVGGraphicsElement | null {
292   let elem = document.getElementById(id);
293   return elem as unknown as (SVGGraphicsElement | null);
294 }
295 function piece_element(base: string, piece: PieceId): SVGGraphicsElement | null
296 {
297   return svg_element(base+piece);
298 }
299
300 function piece_moveable(p: PieceInfo) {
301   return p.moveable == 'Yes' || p.moveable == 'IfWresting' && wresting;
302 }
303 function treat_as_pinned(p: { pinned: boolean }): boolean {
304   return p.pinned && !wresting;
305 }
306 function pinned_message_for_log(p: PieceInfo): string {
307   return 'That piece ('+p.desc+') is pinned to the table.';
308 }
309
310 // ----- key handling -----
311
312 function recompute_keybindings() {
313   uo_map = Object.create(null);
314   let all_targets = [];
315   for (let piece of Object.keys(pieces)) {
316     let p = pieces[piece];
317     if (p.held != us) continue;
318     all_targets.push(piece);
319     for (var uo of p.uos) {
320       let currently = uo_map[uo.def_key];
321       if (currently === null) continue;
322       if (currently !== undefined) {
323         if (currently.opname != uo.opname) {
324           uo_map[uo.def_key] = null;
325           continue;
326         }
327       } else {
328         currently = {
329           targets: [],
330           ...uo
331         };
332         uo_map[uo.def_key] = currently;
333       }
334       currently.desc = currently.desc < uo.desc ? currently.desc : uo.desc;
335       currently.targets!.push(piece);
336     }
337   }
338   all_targets.sort(pieceid_z_cmp);
339   let add_uo = function(targets: PieceId[] | null, uo: UoDescription) {
340     uo_map[uo.def_key] = {
341       targets: targets,
342       ...uo
343     };
344   };
345   if (all_targets.length) {
346     let got_rotateable = false;
347     for (let t of all_targets) {
348       if (pieces[t]!.rotateable)
349         got_rotateable = true;
350     }
351     if (got_rotateable) {
352       add_uo(all_targets, {
353         def_key: 'l',
354         kind: 'Client',
355         wrc: 'Predictable',
356         opname: "left",
357         desc: "rotate left",
358       });
359       add_uo(all_targets, {
360         def_key: 'r',
361         kind: 'Client',
362         wrc: 'Predictable',
363         opname: "right",
364         desc: "rotate right",
365       });
366     }
367     add_uo(all_targets, {
368       def_key: 'b',
369       kind: 'Client',
370       wrc: 'Predictable',
371       opname: "lower",
372       desc: "send to bottom (below other pieces)",
373     });
374     add_uo(all_targets, {
375       def_key: 't',
376       kind: 'Client',
377       wrc: 'Predictable',
378       opname: "raise",
379       desc: "raise to top",
380     });
381   }
382   if (all_targets.length) {
383     let got = 0;
384     for (let t of all_targets) {
385       got |= 1 << Number(pieces[t]!.pinned);
386     }
387     if (got == 1) {
388       add_uo(all_targets, {
389         def_key: 'P',
390         kind: 'ClientExtra',
391         opname: 'pin',
392         desc: 'Pin to table',
393         wrc: 'Predictable',
394       });
395     } else if (got == 2) {
396       add_uo(all_targets, {
397         def_key: 'P',
398         kind: 'ClientExtra',
399         opname: 'unpin',
400         desc: 'Unpin from table',
401         wrc: 'Predictable',
402       });
403     }
404   }
405   add_uo(null, {
406     def_key: wresting ? 'W SPC' /* won't match, handle ad-hoc */ : 'W',
407     kind: 'ClientExtra',
408     opname: 'wrest',
409     desc: wresting ? 'Exit wresting mode' : 'Enter wresting mode',
410     wrc: 'Predictable',
411   });
412   if (special_count != null) {
413     let desc;
414     if (special_count == 0) {
415       desc = 'select bottommost';
416     } else {
417       desc = `select ${special_count}`;
418     }
419     desc = `cancel <strong style="color:purple">${desc}</strong>`;
420     add_uo(null, {
421       def_key: 'SPC', // won't match key event; we handle this ad-hoc
422       kind: 'ClientExtra',
423       opname: 'cancel-special',
424       desc: desc,
425       wrc: 'Predictable',
426     });
427   }
428   add_uo(null, {
429     def_key: 'h',
430     kind: 'ClientExtra',
431     opname: 'motion-hint-history',
432     desc: 'Recent history display',
433     wrc: 'Predictable',
434   });
435   var uo_keys = Object.keys(uo_map);
436   uo_keys.sort(function (ak,bk) {
437     let a = uo_map[ak];
438     let b = uo_map[bk];
439     if (a==null || b==null) return (
440       ( (!!a) as any ) -
441       ( (!!b) as any )
442     );
443     return uo_kind_prec[a.kind] - uo_kind_prec[b.kind]
444       || ak.localeCompare(bk);
445   });
446   let mid_elem = null;
447   for (let celem = uos_node.firstElementChild;
448        celem != null;
449        celem = nextelem) {
450     var nextelem = celem.nextElementSibling;
451     let cid = celem.getAttribute("id");
452     if (cid == "uos-mid") mid_elem = celem;
453     else if (celem.getAttribute("class") == 'uos-mid') { }
454     else celem.remove();
455   }
456   for (var kk of uo_keys) {
457     let uo = uo_map[kk];
458     if (!uo) continue;
459     let prec = uo_kind_prec[uo.kind];
460     let ent = document.createElement('div');
461     ent.innerHTML = '<b>' + kk + '</b> ' + uo.desc;
462     if (prec < 400) {
463       ent.setAttribute('class','uokey-l');
464       uos_node.insertBefore(ent, mid_elem);
465     } else {
466       ent.setAttribute('class','uokey-r');
467       uos_node.appendChild(ent);
468     }
469   }
470 }
471
472 function some_keydown(e: KeyboardEvent) {
473   // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
474   // says to do this, something to do with CJK composition.
475   // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
476   // says that keyCode is deprecated
477   // my tsc says this isComposing thing doesn't exist.  wat.
478   if ((e as any).isComposing /* || e.keyCode === 229 */) return;
479   if (e.ctrlKey || e.altKey || e.metaKey) return;
480   if (e.target) {
481     // someone else is dealing with it ?
482     let tag = (e.target as HTMLElement).tagName;
483     if (tag == 'INPUT') return;
484   }
485
486   let y = function() { e.preventDefault(); e.stopPropagation(); }
487
488   let pane = pane_keys[e.key];
489   if (pane) {
490     y();
491     return pane_switch(pane);
492   }
493
494   let special_count_key = parseInt(e.key);
495   if (isFinite(special_count_key)) {
496     y();
497     if (special_count == null) special_count = 0;
498     special_count *= 10;
499     special_count += special_count_key;
500     special_count %= 100000;
501     mousecursor_etc_reupdate();
502     return;
503   }
504   if (e.key == ' ' || (e.key == 'W' && wresting)) {
505     y();
506     special_count = null;
507     wresting = false;
508     mousecursor_etc_reupdate();
509     return;
510   }
511   if (e.key == 'Backspace') {
512     if (special_count == null) {
513       wresting = false;
514     } else if (special_count >= 10) {
515       special_count = Math.round(special_count / 10 - .45);
516     } else {
517       special_count = null;
518     }
519     mousecursor_etc_reupdate();
520     return;
521   }
522
523   let uo = uo_map[e.key];
524   if (uo === undefined || uo === null) return;
525
526   y();
527   console.log('KEY UO', e, uo);
528   if (uo.kind == 'Client' || uo.kind == 'ClientExtra') {
529     let f = keyops_local[uo.opname];
530     f(uo);
531     return;
532   }
533   if (!(uo.kind == 'Global' || uo.kind == 'GlobalExtra' || uo.kind == 'Piece'))
534     throw 'bad kind '+uo.kind;
535
536   for (var piece of uo.targets!) {
537     let p = pieces[piece]!;
538     api_piece('k', piece, p, { opname: uo.opname, wrc: uo.wrc });
539     if (uo.wrc == 'UpdateSvg') {
540       // No UpdateSvg is loose, so no need to check p.cseq_loose
541       p.cseq_updatesvg = p.cseq_main;
542       redisplay_ancillaries(piece,p);
543     }
544   }
545 }
546
547 function pane_switch(newpane: PaneName) {
548   let new_e;
549   for (;;) {
550     new_e = document.getElementById('pane_' + newpane)!;
551     let style = new_e.getAttribute('style');
552     if (style || newpane == 'help') break;
553     newpane = 'help';
554   }
555   for (let old_e = new_e.parentElement!.firstElementChild;
556        old_e;
557        old_e = old_e.nextElementSibling) {
558     old_e.setAttribute('style','display: none;');
559   }
560   new_e.removeAttribute('style');
561 }
562
563 function mousecursor_etc_reupdate() {
564   let style_elem = document.getElementById("space-cursor-style")!;
565   let style_text;
566   let svg;
567   let xy;
568   let path = 'stroke-linecap="square" d="M -10 -10 10 10 M 10 -10 -10 10"';
569
570   document.getElementById('wresting-warning')!.innerHTML = !wresting ? "" :
571     " <strong>(wresting mode!)</strong>";
572
573   if (wresting != was_wresting) {
574     ungrab_all();
575     was_wresting = wresting;
576   }
577   
578   if (wresting) {
579     let text;
580     if (special_count == null) {
581       text = "WREST";
582     } else if (special_count == 0) {
583       text = "W v";
584     } else {
585       text = "W " + special_count;
586     }
587     xy = '60 15';
588     svg =
589 `<svg xmlns="http://www.w3.org/2000/svg"
590      viewBox="-60 -15 120 60" width="120" height="60">
591   <g transform="translate(0 0)">
592     <path stroke-width="8" stroke="black" ${path}/>
593     <path stroke-width="4" stroke="#cc0" ${path}/>
594  <text x="0" y="40" fill="black" stroke="#cc0" stroke-width="1.7" text-align="center" text-anchor="middle"
595  font-family="sans-serif" font-size="30">${text}</text>
596   </g></svg>`;
597   } else if (special_count == null) {
598   } else {
599     if (special_count != 0) {
600       let text_len = special_count.toString().length;
601       let text_x = text_len <= 3 ? 0 : -15;
602       let text_size = text_len <= 3 ? 50 : 45 * (4/text_len);
603       xy = '15 50';
604       svg = 
605 `<svg xmlns="http://www.w3.org/2000/svg"
606      viewBox="-15 0 120 65" width="120" height="65">
607   <g transform="translate(0 50)">
608     <path stroke-width="8" stroke="#fcf" ${path}/>
609     <path stroke-width="4" stroke="purple" ${path}/>
610     <text x="${text_x}" y="0" fill="purple" stroke="#fcf" stroke-width="2"
611        font-family="sans-serif" font-size="${text_size}">${special_count}</text>
612   </g></svg>`;
613     } else {
614       let path = 'stroke-linecap="square" d="M -10 -10 0 0 10 -10 M 0 0 0 -20"';
615       xy = '15 30';
616       svg =
617 `<svg xmlns="http://www.w3.org/2000/svg"
618      viewBox="-15 -25 30 30" width="30" height="30">
619   <g transform="translate(0 0)">
620     <path stroke-width="8" stroke="#fcf" ${path}/>
621     <path stroke-width="4" stroke="purple" ${path}/>
622   </g></svg>`;
623     }
624   }
625   // Empirically, setting this to '' and then back to the SVG data
626   // seems to cause Firefox to update it more promptly.
627   style_elem.innerHTML = '';
628   if (svg !== undefined) {
629     let svg_data = btoa(svg);
630     style_text =
631 `svg[id=space] {
632   cursor: url(data:image/svg+xml;base64,${svg_data}) ${xy}, auto;
633 }`;
634     style_elem.innerHTML = style_text;
635   }
636   recompute_keybindings();
637 }
638
639 keyops_local['left' ] = function (uo: UoRecord) { rotate_targets(uo, +1); }
640 keyops_local['right'] = function (uo: UoRecord) { rotate_targets(uo, -1); }
641
642 function rotate_targets(uo: UoRecord, dangle: number): boolean {
643   for (let piece of uo.targets!) {
644     let p = pieces[piece]!;
645     if (!p.rotateable) continue;
646     p.angle += dangle + 8;
647     p.angle %= 8;
648     let transform = wasm_bindgen.angle_transform(p.angle);
649     p.pelem.setAttributeNS(null,'transform',transform);
650     api_piece('rotate', piece,p, p.angle);
651   }
652   recompute_keybindings();
653   return true;
654 }
655
656 // ----- lower -----
657
658 type LowerTodoItem = {
659   piece: PieceId,
660   p: PieceInfo,
661   heavy: boolean,
662 };
663
664 type LowerTodoList = { [piece: string]: LowerTodoItem };
665
666 keyops_local['lower'] = function (uo: UoRecord) { lower_targets(uo); }
667
668 function lower_heavy(p: PieceInfo): boolean {
669   return wresting || p.pinned || p.moveable == "No";
670 }
671
672 function lower_targets(uo: UoRecord): boolean {
673   let targets_todo : LowerTodoList = Object.create(null);
674
675   for (let piece of uo.targets!) {
676     let p = pieces[piece]!;
677     let heavy = lower_heavy(p);
678     targets_todo[piece] = { p, piece, heavy, };
679   }
680   let problem = lower_pieces(targets_todo);
681   if (problem !== null) {
682     add_log_message('Cannot lower: ' + problem);
683     return false;
684   }
685   return true;
686 }
687
688 function lower_pieces(targets_todo: LowerTodoList):
689  string | null
690 {
691   // This is a bit subtle.  We don't want to lower below heavy pieces
692   // (unless we are heavy too, or the user is wresting).  But maybe
693   // the heavy pieces aren't already at the bottom.  For now we will
694   // declare that all heavy pieces "should" be below all light
695   // ones.  Not as an invariant, but as a thing we will do here to try
696   // to make a sensible result.  We implement this as follows: if we
697   // find heavy pieces above light pieces, we move those heavy
698   // pieces to the bottom too, just below us, preserving their
699   // relative order.
700   //
701   // Disregarding heavy targets:
702   //
703   // Z     <some stuff not including any light targets>
704   // Z
705   //       topmost light target           *
706   // B (
707   // B     light non-target
708   // B |   light target                   *
709   // B |   heavy non-target, mis-stacked  *
710   // B )*
711   // B
712   //       bottommost light non-target
713   //        if that is below topmost light target
714   //            <- tomove_light: insert targets from * here           Q ->
715   //            <- tomove_misstacked: insert non-targets from * here  Q ->
716   //            <- heavy non-targets with clashing Z Coords           X ->
717   // A
718   // A     heavy non-targets (nomove_heavy)
719   //            <- tomove_heavy: insert all heavy targets here        P ->
720   //
721   // When wresting, treat all targets as heavy.
722
723   type Entry = {
724     piece: PieceId,
725     p: PieceInfo,
726   };
727   // bottom of the stack order first
728   let tomove_light       : Entry[] = [];
729   let tomove_misstacked  : Entry[] = [];
730   let nomove_heavy       : Entry[] = [];
731   let tomove_heavy       : Entry[] = [];
732
733                                                     //  A      B      Z
734   let q_z_top : ZCoord | null = null;               //  null   some   some
735   let n_targets_todo_light = 0;                     //                0
736
737   let any_targets = false;
738   for (const piece of Object.keys(targets_todo)) {
739     any_targets = true;
740     let p = targets_todo[piece];
741     if (!p.heavy) n_targets_todo_light++;
742   }
743   if (!any_targets) return 'Nothing to lower!';
744
745   let walk = pieces_marker;
746   for (;;) { // starting at the bottom of the stack order
747     if (Object.keys(targets_todo).length == 0 &&
748        q_z_top !== null) {
749       // no targets left, state Z, we can stop now
750       console.log('LOWER STATE Z FINISHED');
751       break;
752     }
753
754     let new_walk = walk.nextElementSibling;
755     if (new_walk == null) {
756       console.log('LOWER WALK NO SIBLING!');
757       break;
758     }
759     walk = new_walk as SVGGraphicsElement;
760     let piece = walk.dataset.piece;
761     if (piece == null) {
762       console.log('LOWER WALK REACHED TOP');
763       break;
764     }
765
766     let p = pieces[piece]!;
767     let todo = targets_todo[piece];
768     if (todo) {
769       let xst = '';
770       if (q_z_top === null && !todo.heavy) {
771         q_z_top = p.z;
772         xst = 'STATE -> B';
773       }
774       console.log('LOWER WALK', piece, 'TODO', todo.heavy ? "H" : "_", xst);
775       delete targets_todo[piece];
776       if (!todo.heavy) n_targets_todo_light--;
777       (todo.heavy ? tomove_heavy : tomove_light).push(todo);
778       continue;
779     }
780
781     let p_heavy = lower_heavy(p);
782     if (q_z_top === null) { // state A
783       if (!p_heavy) {
784         console.log('LOWER WALK', piece, 'STATE A -> Z');
785         q_z_top = p.z;
786       } else {
787         console.log('LOWER WALK', piece, 'STATE A');
788         nomove_heavy.push({ p, piece });
789       }
790       continue;
791     }
792
793     // state B
794     if (p_heavy) {
795       console.log('LOWER WALK', piece, 'STATE B MIS-STACKED');
796       tomove_misstacked.push({ p, piece });
797     } else {
798       console.log('LOWER WALK', piece, 'STATE B');
799     }
800   }
801
802   if (q_z_top === null) {
803     // Somehow we didn't find the top of Q, so we didn't meet any
804     // targets.  (In the walk loop, we always set q_z_top if todo.)
805     q_z_top =
806       tomove_misstacked.length ? tomove_misstacked[0].p.z :
807       tomove_light     .length ? tomove_light     [0].p.z :
808                                  tomove_heavy     [0].p.z;
809   }
810
811   while (nomove_heavy.length &&
812          (tomove_light.length || tomove_misstacked.length) &&
813          nomove_heavy[nomove_heavy.length-1].p.z == q_z_top) {
814     // Yowzer.  We have to reset the Z coordinates on these heavy
815     // pieces, whose Z coordinate is the same as the stuff we are not
816     // touching, because otherwise there is no gap.
817     //
818     // Treating them as misstacked instead is sufficient, provided
819     // we put them at the front (bottom end) of the misstacked list.
820     //
821     // This is X in the chart.
822     //
823     let restack = nomove_heavy.pop()!;
824     console.log('LOWER CLASHING Z - RESTACKING', restack);
825     tomove_misstacked.unshift(restack);
826   }
827
828   type PlanEntry = {
829     content: Entry[], // bottom to top
830     z_top: ZCoord,
831     z_bot: ZCoord | null,
832   };
833
834   let plan : PlanEntry[] = [];
835
836   console.log('LOWER PARTQ X', tomove_misstacked);
837   console.log('LOWER PARTQ L', tomove_light);
838   console.log('LOWER PARTP H', tomove_heavy);
839   let partQ = tomove_misstacked.concat(tomove_light);
840   let partP = tomove_heavy;
841
842   if (nomove_heavy.length == 0) {
843     plan.push({
844       content: partP.concat(partQ),
845       z_top: q_z_top,
846       z_bot : null,
847     });
848   } else {
849     plan.push({
850       content: partQ,
851       z_top: q_z_top,
852       z_bot: nomove_heavy[nomove_heavy.length-1].p.z,
853     }, {
854       content: partP,
855       z_top: nomove_heavy[0].p.z,
856       z_bot: null,
857     });
858   }
859
860   console.log('LOWER PLAN', plan);
861
862   for (const pe of plan) {
863     for (const e of pe.content) {
864       if (e.p.held != null && e.p.held != us) {
865         return "lowering would disturb a piece held by another player";
866       }
867     }
868   }
869
870   for (const pe of plan) {
871     let z_top = pe.z_top;
872     let z_bot = pe.z_bot;
873     if (! pe.content.length) continue;
874     if (z_bot == null) {
875       let first_z = pe.content[0].p.z;
876       if (z_top >= first_z)
877         z_top = first_z;
878     }
879     let zrange = wasm_bindgen.range(z_bot, z_top, pe.content.length);
880     console.log('LOQER PLAN PE',
881                 pe, z_bot, z_top, pe.content.length, zrange.debug());
882     for (const e of pe.content) {
883       let p = e.p;
884       p.held_us_raising = "Lowered";
885       piece_set_zlevel(e.piece, p, (oldtop_piece) => {
886         let z = zrange.next();
887         p.z = z;
888         api_piece("setz", e.piece, e.p, { z });
889       });
890     }
891   }
892   return null;
893 }
894
895 keyops_local['wrest'] = function (uo: UoRecord) {
896   wresting = !wresting;
897   mousecursor_etc_reupdate();
898 }
899
900 keyops_local['motion-hint-history'] = function (uo: UoRecord) {
901   movehist_len_i ++;
902   movehist_len_i %= movehist_lens.length;
903   movehist_revisible();
904 }
905
906 keyops_local['pin'  ] = function (uo) {
907   if (!lower_targets(uo)) return;
908   pin_unpin(uo, true);
909 }
910 keyops_local['unpin'] = function (uo) {
911   pin_unpin(uo, false);
912 }
913
914 function pin_unpin(uo: UoRecord, newpin: boolean) {
915   for (let piece of uo.targets!) {
916     let p = pieces[piece]!;
917     p.pinned = newpin;
918     api_piece('pin', piece,p, newpin);
919     redisplay_ancillaries(piece,p);
920   }
921   recompute_keybindings();
922 }
923
924 // ----- raising -----
925
926 keyops_local['raise'] = function (uo: UoRecord) { raise_targets(uo); }
927
928 function raise_targets(uo: UoRecord) {
929   let any = false;
930   for (let piece of uo.targets!) {
931     let p = pieces[piece]!;
932     if (p.pinned || !piece_moveable(p)) continue;
933     any = true;
934     piece_raise(piece, p, "NotYet");
935   }
936   if (!any) { 
937     add_log_message('No pieces could be raised.');
938   }
939 }
940
941 function piece_raise(piece: PieceId, p: PieceInfo,
942                      new_held_us_raising: HeldUsRaising,
943   implement: (piece: PieceId, p: PieceInfo, z: ZCoord) => void
944   = function(piece: PieceId, p: PieceInfo, z: ZCoord) {
945     api_piece("setz", piece,p, { z: z });
946   })
947 {
948   p.held_us_raising = new_held_us_raising;
949   piece_set_zlevel(piece,p, (oldtop_piece) => {
950     let oldtop_p = pieces[oldtop_piece]!;
951     let z = wasm_bindgen.increment(oldtop_p.z);
952     p.z = z;
953     implement(piece,p,z);
954   });
955 }
956
957 // ----- clicking/dragging pieces -----
958
959 type DragInfo = {
960   piece : PieceId,
961   dox : number,
962   doy : number,
963 }
964
965 enum DRAGGING { // bitmask
966   NO           = 0x00,
967   MAYBE_GRAB   = 0x01,
968   MAYBE_UNGRAB = 0x02,
969   YES          = 0x04,
970   RAISED       = 0x08,
971 };
972
973 var drag_pieces : DragInfo[] = [];
974 var dragging = DRAGGING.NO;
975 var dcx : number | null;
976 var dcy : number | null;
977
978 const DRAGTHRESH = 5;
979
980 let rectsel_start: Pos | null;
981 let rectsel_shifted: boolean | null;
982 let rectsel_started_on_whynot: string | null;
983 const RECTSELTHRESH = 5;
984
985 function piece_xy(p: PieceInfo): Pos {
986   return [ parseFloat(p.uelem.getAttributeNS(null,"x")!),
987            parseFloat(p.uelem.getAttributeNS(null,"y")!) ];
988 }
989
990 function drag_start_prepare(new_dragging: DRAGGING) {
991   dragging = new_dragging;
992
993   let spos_map = Object.create(null);
994   for (let piece of Object.keys(pieces)) {
995     let p = pieces[piece]!;
996     if (p.held != us) continue;
997     let spos = piece_xy(p);
998     let sposk = `${spos[0]} ${spos[1]}`;
999     if (spos_map[sposk] === undefined) spos_map[sposk] = [spos, []];
1000     spos_map[sposk][1].push([spos, piece,p]);
1001   }
1002
1003   for (let sposk of Object.keys(spos_map)) {
1004     let [[dox, doy], ents] = spos_map[sposk];
1005     for (let i=0; i<ents.length; i++) {
1006       let [p, piece] = ents[i];
1007       let delta = (-(ents.length-1)/2 + i) * SPECIAL_MULTI_DELTA_EACH;
1008       p.drag_delta = Math.min(Math.max(delta, -SPECIAL_MULTI_DELTA_MAX),
1009                                               +SPECIAL_MULTI_DELTA_MAX);
1010       drag_pieces.push({
1011         piece: piece,
1012         dox: dox + p.drag_delta,
1013         doy: doy,
1014       });
1015     }
1016   }
1017 }
1018
1019 function some_mousedown(e : MouseEvent) {
1020   console.log('mousedown', e, e.clientX, e.clientY, e.target);
1021
1022   if (e.button != 0) { return }
1023   if (e.altKey) { return }
1024   if (e.metaKey) { return }
1025   if (e.ctrlKey) {
1026     return;
1027   } else {
1028     drag_mousedown(e, e.shiftKey);
1029   }
1030 }
1031
1032 type MouseFindClicked = null | {
1033   clicked: PieceId[],
1034   held: PlayerId | null,
1035   pinned: boolean,
1036   multigrab?: number,
1037 };
1038
1039 type PieceSet = { [piece: string]: true };
1040
1041 function grab_clicked(clicked: PieceId[], loose: boolean,
1042                       multigrab: number | undefined) {
1043   for (let piece of clicked) {
1044     let p = pieces[piece]!;
1045     set_grab_us(piece,p);
1046     if (multigrab === undefined) {
1047       api_piece_x(api_immediate, loose,
1048                   wresting ? 'wrest' : 'grab', piece,p, { });
1049     } else {
1050       piece_raise(piece,p, 'Raised', function(piece,p,z) {
1051         api_piece_x(api_immediate, loose, 'multigrab',
1052                     piece,p, { n: multigrab, z: z });
1053       })
1054     }
1055   }
1056 }
1057 function ungrab_clicked(clicked: PieceId[]) {
1058   let todo: [PieceId, PieceInfo][] = [];
1059   for (let tpiece of clicked) {
1060     let tp = pieces[tpiece]!;
1061     todo.push([tpiece, tp]);
1062   }
1063   do_ungrab_n(todo);
1064 }
1065
1066 function mouse_clicked_one(piece: PieceId, p: PieceInfo): MouseFindClicked {
1067   let held = p.held;
1068   let pinned = p.pinned;
1069   return { clicked: [piece], held, pinned };
1070 }
1071
1072 function mouse_find_predicate(
1073   wanted: number | null,
1074   allow_for_deselect: boolean,
1075   note_already: PieceSet | null,
1076   predicate: (p: PieceInfo) => boolean
1077 ): MouseFindClicked {
1078   let clicked: PieceId[];
1079   let held: string | null;
1080   let pinned = false;
1081   let already_count = 0;
1082
1083   clicked = [];
1084   let uelem = defs_marker;
1085   while (wanted == null || (clicked.length + already_count) < wanted) {
1086     let i = clicked.length;
1087     uelem = uelem.previousElementSibling as any;
1088     if (uelem == pieces_marker) {
1089       if (wanted != null) {
1090         add_log_message(`Not enough pieces!  Stopped after ${i}.`);
1091         return null;
1092       }
1093       break;
1094     }
1095     let piece = uelem.dataset.piece!;
1096
1097     function is_already() {
1098       if (note_already != null) {
1099         already_count++;
1100         note_already[piece] = true;
1101       }
1102     }
1103
1104     let p = pieces[piece];
1105     if (treat_as_pinned(p)) continue;
1106     if (p.held && p.held != us && !wresting) continue;
1107     if (i > 0 && !piece_moveable(p))
1108       continue;
1109     if (!predicate(p)) {
1110       continue;
1111     }
1112     if (p.pinned) pinned = true;
1113
1114     if (i == 0) {
1115       held = p.held;
1116       if (held == us && !allow_for_deselect) held = null;
1117     }
1118     if (held! == us) {
1119       // user is going to be deselecting
1120       if (p.held != us) {
1121         // skip ones we don't have
1122         is_already();
1123         continue;
1124       }
1125     } else { // user is going to be selecting
1126       if (p.held == us) {
1127         is_already();
1128         continue; // skip ones we have already
1129       } else if (p.held == null) {
1130       } else {
1131         held = p.held; // wrestish
1132       }
1133     }
1134     clicked.push(piece);
1135   }
1136   if (clicked.length == 0) return null;
1137   else return { clicked, held: held!, pinned: pinned! };
1138 }
1139
1140 function mouse_find_lowest(e: MouseEvent) {
1141   let clickpos = mouseevent_pos(e);
1142   let uelem = pieces_marker;
1143   for (;;) {
1144     uelem = uelem.nextElementSibling as any;
1145     if (uelem == defs_marker) break;
1146     let piece = uelem.dataset.piece!;
1147     let p = pieces[piece]!;
1148     if (p_bbox_contains(p, clickpos)) {
1149       return mouse_clicked_one(piece, p);
1150     }
1151   }
1152   return null;
1153 }
1154
1155 function mouse_find_clicked(e: MouseEvent,
1156                             target: SVGGraphicsElement, piece: PieceId,
1157                             count_allow_for_deselect: boolean,
1158                             note_already: PieceSet | null,
1159                             ): MouseFindClicked
1160 {
1161   let p = pieces[piece]!;
1162   if (special_count == null) {
1163     return mouse_clicked_one(piece, p);
1164   } else if (special_count == 0) {
1165     return mouse_find_lowest(e);
1166   } else { // special_count > 0
1167     if (p.multigrab && !wresting) {
1168       let clicked = mouse_clicked_one(piece, p);
1169       if (clicked) clicked.multigrab = special_count;
1170       return clicked;
1171     } else {
1172       if (special_count > 99) {
1173         add_log_message(
1174           `Refusing to try to select ${special_count} pieces (max is 99)`);
1175         return null;
1176       }
1177       let clickpos = mouseevent_pos(e);
1178       return mouse_find_predicate(
1179         special_count, count_allow_for_deselect, note_already,
1180         function(p) { return p_bbox_contains(p, clickpos); }
1181       )
1182     }
1183   }
1184 }
1185
1186 function drag_mousedown(e : MouseEvent, shifted: boolean) {
1187   let target = e.target as SVGGraphicsElement; // we check this just now!
1188   let piece: PieceId | undefined = target.dataset.piece;
1189
1190   rectsel_started_on_whynot = null;
1191
1192   if (piece) {
1193     let p = pieces[piece]!;
1194
1195     if (treat_as_pinned(p!)) {
1196       rectsel_started_on_whynot = pinned_message_for_log(p!);
1197       piece = undefined;
1198     }
1199   }
1200
1201   if (!piece) {
1202     rectsel_start = mouseevent_pos(e);
1203     rectsel_shifted = shifted;
1204     window.addEventListener('mousemove', rectsel_mousemove, true);
1205     window.addEventListener('mouseup',   rectsel_mouseup,   true);
1206     return;
1207   }
1208
1209   let note_already = shifted ? null : Object.create(null);
1210
1211   let c = mouse_find_clicked(e, target, piece, false, note_already);
1212   if (c == null) return;
1213   let clicked = c.clicked;
1214   let held = c.held;
1215   let multigrab = c.multigrab;
1216
1217   special_count = null;
1218   mousecursor_etc_reupdate();
1219   drag_cancel();
1220
1221   drag_pieces = [];
1222   if (held == us) {
1223     if (shifted) {
1224       ungrab_clicked(clicked);
1225       return;
1226     }
1227     drag_start_prepare(DRAGGING.MAYBE_UNGRAB);
1228   } else if (held == null || wresting) {
1229     if (!shifted) {
1230       ungrab_all_except(note_already);
1231     }
1232     if (treat_as_pinned(c)) {
1233       add_log_message(pinned_message_for_log(pieces[c.clicked[0]!]!));
1234       return;
1235     }
1236     grab_clicked(clicked, !wresting, multigrab);
1237     drag_start_prepare(DRAGGING.MAYBE_GRAB);
1238   } else {
1239     add_log_message('That piece is held by another player.');
1240     return;
1241   }
1242   dcx = e.clientX;
1243   dcy = e.clientY;
1244
1245   window.addEventListener('mousemove', drag_mousemove, true);
1246   window.addEventListener('mouseup',   drag_mouseup,   true);
1247 }
1248
1249 function mouseevent_pos(e: MouseEvent): Pos {
1250   let ctm = space.getScreenCTM()!;
1251   let px = (e.clientX - ctm.e)/(ctm.a * firefox_bug_zoom_factor_compensation);
1252   let py = (e.clientY - ctm.f)/(ctm.d * firefox_bug_zoom_factor_compensation);
1253   let pos: Pos = [px, py];
1254   console.log('mouseevent_pos', pos);
1255   return pos;
1256 }
1257
1258 function p_bbox_contains(p: PieceInfo, test: Pos) {
1259   let ctr = piece_xy(p);
1260   for (let i of [0,1]) {
1261     let offset = test[i] - ctr[i];
1262     if (offset < p.bbox[0][i] || offset > p.bbox[1][i])
1263       return false;
1264   }
1265   return true;
1266 }
1267
1268 function do_ungrab_n(todo: [PieceId, PieceInfo][]) {
1269   function sort_with(a: [PieceId, PieceInfo],
1270                      b: [PieceId, PieceInfo]): number {
1271     return piece_z_cmp(a[1], b[1]);
1272   }
1273   todo.sort(sort_with);
1274   for (let [tpiece, tp] of todo) {
1275     do_ungrab_1(tpiece, tp);
1276   }
1277 }
1278 function ungrab_all_except(dont: PieceSet | null) {
1279   let todo: [PieceId, PieceInfo][] =  [];
1280   for (let tpiece of Object.keys(pieces)) {
1281     if (dont && dont[tpiece]) continue;
1282     let tp = pieces[tpiece]!;
1283     if (tp.held == us) {
1284       todo.push([tpiece, tp]);
1285     }
1286   }
1287   do_ungrab_n(todo);
1288 }
1289 function ungrab_all() {
1290   ungrab_all_except(null);
1291 }
1292
1293 function set_grab_us(piece: PieceId, p: PieceInfo) {
1294   p.held = us;
1295   p.held_us_raising = "NotYet";
1296   p.drag_delta = 0;
1297   redisplay_ancillaries(piece,p);
1298   recompute_keybindings();
1299 }
1300 function do_ungrab_1(piece: PieceId, p: PieceInfo) {
1301   let autoraise = p.held_us_raising == "Raised";
1302   p.held = null;
1303   p.held_us_raising = "NotYet";
1304   p.drag_delta = 0;
1305   redisplay_ancillaries(piece,p);
1306   recompute_keybindings();
1307   api_piece('ungrab', piece,p, { autoraise });
1308 }
1309
1310 function clear_halo(piece: PieceId, p: PieceInfo) {
1311   let was = p.last_seen_moved;
1312   p.last_seen_moved = null;
1313   if (was) redisplay_ancillaries(piece,p);
1314 }
1315
1316 function ancillary_node(piece: PieceId, stroke: string): SVGGraphicsElement {
1317   var nelem = document.createElementNS(svg_ns,'use');
1318   nelem.setAttributeNS(null,'href','#surround'+piece);
1319   nelem.setAttributeNS(null,'stroke',stroke);
1320   nelem.setAttributeNS(null,'fill','none');
1321   return nelem as any;
1322 }
1323
1324 function redisplay_ancillaries(piece: PieceId, p: PieceInfo) {
1325   let href = '#surround'+piece;
1326   console.log('REDISPLAY ANCILLARIES',href);
1327
1328   for (let celem = p.pelem.firstElementChild;
1329        celem != null;
1330        celem = nextelem) {
1331     var nextelem = celem.nextElementSibling
1332     let thref = celem.getAttributeNS(null,"href");
1333     if (thref == href) {
1334       celem.remove();
1335     }
1336   }
1337
1338   let halo_colour = null;
1339   if (p.cseq_updatesvg != null) {
1340     halo_colour = 'purple';
1341   } else if (p.last_seen_moved != null) {
1342     halo_colour = 'yellow';
1343   } else if (p.held != null && p.pinned) {
1344     halo_colour = '#8cf';
1345   }
1346   if (halo_colour != null) {
1347     let nelem = ancillary_node(piece, halo_colour);
1348     if (p.held != null) {
1349       // value 2ps is also in src/pieces.rs SELECT_STROKE_WIDTH
1350       nelem.setAttributeNS(null,'stroke-width','2px');
1351     }
1352     p.pelem.prepend(nelem);
1353   } 
1354   if (p.held != null) {
1355     let da = null;
1356     if (p.held != us) {
1357       da = players[p.held!]!.dasharray;
1358     } else {
1359       let [px, py] = piece_xy(p);
1360       let inoccult = occregions.contains_pos(px, py);
1361       p.held_us_inoccult = inoccult;
1362       if (inoccult) {
1363         da = "0.9 0.6"; // dotted dasharray
1364       }
1365     }
1366     let nelem = ancillary_node(piece, held_surround_colour);
1367     if (da !== null) {
1368       nelem.setAttributeNS(null,'stroke-dasharray',da);
1369     }
1370     p.pelem.appendChild(nelem);
1371   }
1372 }
1373
1374 function drag_mousemove(e: MouseEvent) {
1375   var ctm = space.getScreenCTM()!;
1376   var ddx = (e.clientX - dcx!)/(ctm.a * firefox_bug_zoom_factor_compensation);
1377   var ddy = (e.clientY - dcy!)/(ctm.d * firefox_bug_zoom_factor_compensation);
1378   var ddr2 = ddx*ddx + ddy*ddy;
1379   if (!(dragging & DRAGGING.YES)) {
1380     if (ddr2 > DRAGTHRESH) {
1381       for (let dp of drag_pieces) {
1382         let tpiece = dp.piece;
1383         let tp = pieces[tpiece]!;
1384         if (tp.moveable == "Yes") {
1385           continue;
1386         } else if (tp.moveable == "IfWresting") {
1387           if (wresting) continue;
1388           add_log_message(
1389             `That piece (${tp.desc}) can only be moved when Wresting.`);
1390         } else {
1391           add_log_message(
1392             `That piece (${tp.desc}) cannot be moved at the moment.`);
1393         }
1394         return ddr2;
1395       }
1396       dragging |= DRAGGING.YES;
1397     }
1398   }
1399   //console.log('mousemove', ddx, ddy, dragging);
1400   if (dragging & DRAGGING.YES) {
1401     console.log('DRAG PIECES',drag_pieces);
1402     for (let dp of drag_pieces) {
1403       console.log('DRAG PIECES PIECE',dp);
1404       let tpiece = dp.piece;
1405       let tp = pieces[tpiece]!;
1406       var x = Math.round(dp.dox + ddx);
1407       var y = Math.round(dp.doy + ddy);
1408       let need_redisplay_ancillaries = (
1409         tp.held == us &&
1410         occregions.contains_pos(x,y) != tp.held_us_inoccult
1411       );
1412       piece_set_pos_core(tp, x, y);
1413       tp.queued_moves++;
1414       api_piece_x(api_delay, false, 'm', tpiece,tp, [x, y] );
1415       if (need_redisplay_ancillaries) redisplay_ancillaries(tpiece, tp);
1416     }
1417     if (!(dragging & DRAGGING.RAISED)) {
1418       sort_drag_pieces();
1419       for (let dp of drag_pieces) {
1420         let piece = dp.piece;
1421         let p = pieces[piece]!;
1422         if (p.held_us_raising == "Lowered") continue;
1423         let dragraise = +p.pelem.dataset.dragraise!;
1424         if (dragraise > 0 && ddr2 >= dragraise*dragraise) {
1425           dragging |= DRAGGING.RAISED;
1426           console.log('CHECK RAISE ', dragraise, dragraise*dragraise, ddr2);
1427           piece_raise(piece,p,"Raised");
1428         }
1429       }
1430     }
1431   }
1432   return ddr2;
1433 }
1434 function sort_drag_pieces() {
1435   function sort_with(a: DragInfo, b: DragInfo): number {
1436     return pieceid_z_cmp(a.piece,
1437                          b.piece);
1438   }
1439   drag_pieces.sort(sort_with);
1440 }
1441
1442 function drag_mouseup(e: MouseEvent) {
1443   console.log('mouseup', dragging);
1444   let ddr2 : number = drag_mousemove(e);
1445   drag_end();
1446 }
1447
1448 function drag_end() {
1449   if (dragging == DRAGGING.MAYBE_UNGRAB ||
1450       (dragging & ~DRAGGING.RAISED) == (DRAGGING.MAYBE_GRAB | DRAGGING.YES)) {
1451     sort_drag_pieces();
1452     for (let dp of drag_pieces) {
1453       let piece = dp.piece;
1454       let p = pieces[piece]!;
1455       do_ungrab_1(piece,p);
1456     }
1457   }
1458   drag_cancel();
1459 }
1460
1461 function drag_cancel() {
1462   window.removeEventListener('mousemove', drag_mousemove, true);
1463   window.removeEventListener('mouseup',   drag_mouseup,   true);
1464   dragging = DRAGGING.NO;
1465   drag_pieces = [];
1466 }
1467
1468 function rectsel_nontrivial_pos2(e: MouseEvent): Pos | null {
1469   let pos2 = mouseevent_pos(e);
1470   let d2 = 0;
1471   for (let i of [0,1]) {
1472     let d = pos2[i] - rectsel_start![i];
1473     d2 += d*d;
1474   }
1475   return d2 > RECTSELTHRESH*RECTSELTHRESH ? pos2 : null;
1476 }
1477
1478 function rectsel_mousemove(e: MouseEvent) {
1479   let pos2 = rectsel_nontrivial_pos2(e);
1480   let path;
1481   if (pos2 == null) {
1482     path = "";
1483   } else {
1484     let pos1 = rectsel_start!;
1485     path = `M ${ pos1 [0]} ${ pos1 [1] }
1486               ${ pos2 [0]} ${ pos1 [1] }
1487             M ${ pos1 [0]} ${ pos2 [1] }
1488               ${ pos2 [0]} ${ pos2 [1] }
1489             M ${ pos1 [0]} ${ pos1 [1] }
1490               ${ pos1 [0]} ${ pos2 [1] }
1491             M ${ pos2 [0]} ${ pos1 [1] }
1492               ${ pos2 [0]} ${ pos2 [1] }`;
1493   }
1494   rectsel_path.firstElementChild!.setAttributeNS(null,'d',path);
1495 }
1496
1497 function rectsel_mouseup(e: MouseEvent) {
1498   console.log('rectsel mouseup');
1499   window.removeEventListener('mousemove', rectsel_mousemove, true);
1500   window.removeEventListener('mouseup',   rectsel_mouseup,   true);
1501   rectsel_path.firstElementChild!.setAttributeNS(null,'d','');
1502   let pos2 = rectsel_nontrivial_pos2(e);
1503
1504   if (pos2 == null) {
1505     // clicked not on an unpinned piece, and didn't drag
1506     if (rectsel_started_on_whynot) {
1507       add_log_message(rectsel_started_on_whynot);
1508     }
1509     special_count = null;
1510     mousecursor_etc_reupdate();
1511     // we'll bail in a moment, after possibly unselecting things
1512   }
1513
1514   let note_already = Object.create(null);
1515   let c = null;
1516
1517   if (pos2 != null) {
1518     if (special_count != null && special_count == 0) {
1519       add_log_message(`Cannot drag-select lowest.`);
1520       return;
1521     }
1522     let tl = [0,0];
1523     let br = [0,0];
1524     for (let i of [0,1]) {
1525       tl[i] = Math.min(rectsel_start![i], pos2[i]);
1526       br[i] = Math.max(rectsel_start![i], pos2[i]);
1527     }
1528     c = mouse_find_predicate(
1529       special_count, rectsel_shifted!, note_already,
1530       function(p: PieceInfo) {
1531         let pp = piece_xy(p);
1532         for (let i of [0,1]) {
1533           if (pp[i] < tl[i] || pp[i] > br[i]) return false;
1534         }
1535         return true;
1536       }
1537     );
1538   }
1539
1540   if (!c) {
1541     // clicked not on a piece, didn't end up selecting anything
1542     // either because drag region had nothing in it, or special
1543     // failed, or some such.
1544     if (!rectsel_shifted) {
1545       let mr;
1546       while (mr = movements.pop()) {
1547         mr.p.last_seen_moved = null;
1548         redisplay_ancillaries(mr.piece, mr.p);
1549       }
1550       ungrab_all();
1551     }
1552     return;
1553   }
1554
1555   // did the special
1556   special_count = null;
1557   mousecursor_etc_reupdate();
1558
1559   if (rectsel_shifted && c.held == us) {
1560     ungrab_clicked(c.clicked);
1561     return;
1562   } else {
1563     if (!rectsel_shifted) {
1564       ungrab_all_except(note_already);
1565     }
1566     grab_clicked(c.clicked, false, undefined);
1567   }
1568 }
1569
1570 // ----- general -----
1571
1572 type PlayersUpdate = { new_info_pane: string };
1573
1574 messages.SetPlayer = <MessageHandler>function
1575 (j: { player: string, data: PlayerInfo } & PlayersUpdate) {
1576   players[j.player] = j.data;
1577   player_info_pane_set(j);
1578 }
1579
1580 messages.RemovePlayer = <MessageHandler>function
1581 (j: { player: string } & PlayersUpdate ) {
1582   delete players[j.player];
1583   player_info_pane_set(j);
1584 }
1585
1586 function player_info_pane_set(j: PlayersUpdate) {
1587   document.getElementById('player_list')!
1588     .innerHTML = j.new_info_pane;
1589 }
1590
1591 messages.UpdateBundles = <MessageHandler>function
1592 (j: { new_info_pane: string }) {
1593   document.getElementById('bundle_list')!
1594     .innerHTML = j.new_info_pane;
1595 }
1596
1597 messages.SetTableSize = <MessageHandler>function
1598 ([x, y]: [number, number]) {
1599   function set_attrs(elem: Element, l: [string,string][]) {
1600     for (let a of l) {
1601       elem.setAttributeNS(null,a[0],a[1]);
1602     }
1603   }
1604   let rect = document.getElementById('table_rect')!;
1605   set_attrs(space, wasm_bindgen.space_table_attrs(x, y));
1606   set_attrs(rect,  wasm_bindgen.space_table_attrs(x, y));
1607 }
1608
1609 messages.SetTableColour = <MessageHandler>function
1610 (c: string) {
1611   let rect = document.getElementById('table_rect')!;
1612   rect.setAttributeNS(null, 'fill', c);
1613 }
1614
1615 messages.SetLinks = <MessageHandler>function
1616 (msg: string) {
1617   if (msg.length != 0 && layout == 'Portrait') {
1618     msg += " |";
1619   }
1620   links_elem.innerHTML = msg
1621 }
1622
1623 // ---------- movehist ----------
1624
1625 type MoveHistEnt = {
1626   held: PlayerId,
1627   posx: [MoveHistPosx, MoveHistPosx],
1628   diff: { 'Moved': { d: number } },
1629 }
1630 type MoveHistPosx = {
1631   pos: Pos,
1632   angle: CompassAngle,
1633   facehint: FaceId | null,
1634 }
1635
1636 messages.MoveHistEnt = <MessageHandler>movehist_record;
1637 messages.MoveHistClear = <MessageHandler>function() {
1638   movehist_revisible_custmax(0);
1639 }
1640
1641 function movehist_record(ent: MoveHistEnt) {
1642   let old_pos = ent.posx[0].pos;
1643   let new_pos = ent.posx[1].pos;
1644
1645   movehist_gen++;
1646   movehist_gen %= (movehist_len_max * 2);
1647   let meid = 'motionhint-marker-' + movehist_gen;
1648
1649   let moved = ent.diff['Moved'];
1650   if (moved) {
1651     let d = moved.d;
1652     let ends = [];
1653     for (let end of [0,1]) {
1654       let s = (!end ? MOVEHIST_ENDS : d - MOVEHIST_ENDS) / d;
1655       ends.push([ (1-s) * old_pos[0] + s * new_pos[0],
1656                   (1-s) * old_pos[1] + s * new_pos[1] ]);
1657     }
1658     let g = document.createElementNS(svg_ns,'g');
1659     let sz = 4;
1660     let pi = players[ent.held];
1661     let nick = pi ? pi.nick : '';
1662     // todo: would be nice to place text variously along arrow, rotated
1663     let svg = `
1664       <marker id="${meid}" viewBox="2 0 ${sz} ${sz}" 
1665         refX="${sz}" refY="${sz/2}"
1666         markerWidth="${sz + 2}" markerHeight="${sz}"
1667         stroke="yellow" fill="none"
1668         orient="auto-start-reverse" stroke-linejoin="miter">
1669         <path d="M 0 0 L ${sz} ${sz/2} L 0 ${sz}" />
1670       </marker>
1671       <line x1="${ends[0][0].toString()}"
1672             y1="${ends[0][1].toString()}"
1673             x2="${ends[1][0].toString()}"
1674             y2="${ends[1][1].toString()}"
1675             stroke="yellow"
1676             stroke-width="1" pointer-events="none"
1677             marker-end="url(#${meid})" />
1678       <text x="${((ends[0][0] + ends[1][0]) / 2).toString()}"
1679             y="${((ends[0][1] + ends[1][1]) / 2).toString()}"
1680             font-size="5" pointer-events="none"
1681             stroke-width="0.1">${nick}</text>
1682     `;
1683     g.innerHTML = svg;
1684     space.insertBefore(g, movehist_end);
1685     movehist_revisible();
1686   }
1687 }
1688
1689 function movehist_revisible() { 
1690   movehist_revisible_custmax(movehist_len_max);
1691 }
1692
1693 function movehist_revisible_custmax(len_max: number) {
1694   let n = movehist_lens[movehist_len_i];
1695   let i = 0;
1696   let node = movehist_end;
1697   while (i < len_max) {
1698     i++; // i now eg 1..10
1699     node = node.previousElementSibling! as SVGGraphicsElement;
1700     if (node == movehist_start)
1701       return;
1702     let prop = i > n ? 0 : (n-i+1)/n;
1703     let stroke = (prop * 1.0).toString();
1704     let marker = node.firstElementChild!;
1705     marker.setAttributeNS(null,'stroke-width',stroke);
1706     let line = marker.nextElementSibling!;
1707     line.setAttributeNS(null,'stroke-width',stroke);
1708     let text = line.nextElementSibling!;
1709     if (!prop) {
1710       text.setAttributeNS(null,'stroke','none');
1711       text.setAttributeNS(null,'fill','none');
1712     } else {
1713       text.setAttributeNS(null,'fill','yellow');
1714       text.setAttributeNS(null,'stroke','orange');
1715     }
1716   }
1717   for (;;) {
1718     let del = node.previousElementSibling!;
1719     if (del == movehist_start)
1720       return;
1721     del.remove();
1722   }
1723 }  
1724
1725 // ----- logs -----
1726
1727 messages.Log = <MessageHandler>function
1728 (j: { when: string, logent: { html: string } }) {
1729   add_timestamped_log_message(j.when, j.logent.html);
1730 }
1731
1732 function add_log_message(msg_html: string) {
1733   add_timestamped_log_message('', msg_html);
1734 }
1735
1736 function add_timestamped_log_message(ts_html: string, msg_html: string) {
1737   var lastent = log_elem.lastElementChild;
1738   var in_scrollback =
1739     lastent == null ||
1740     // inspired by
1741     //   https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling/21627295#21627295
1742     // rejected
1743       //   https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
1744       (() => {
1745         let le_top = lastent.getBoundingClientRect()!.top;
1746         let le_bot = lastent.getBoundingClientRect()!.bottom;
1747         let ld_bot = logscroll_elem.getBoundingClientRect()!.bottom;
1748         console.log("ADD_LOG_MESSAGE bboxes: le t b, bb",
1749                     le_top, le_bot, ld_bot);
1750         return 0.5 * (le_bot + le_top) > ld_bot;
1751       })();
1752
1753   console.log('ADD LOG MESSAGE ',in_scrollback, layout, msg_html);
1754
1755   var ne : HTMLElement;
1756
1757   function add_thing(elemname: string, cl: string, html: string) {
1758     var ie = document.createElement(elemname);
1759     ie.innerHTML = html;
1760     ie.setAttribute("class", cl);
1761     ne.appendChild(ie);
1762   }
1763
1764   if (layout == 'Portrait') {
1765     ne = document.createElement('tr');
1766     add_thing('td', 'logmsg', msg_html);
1767     add_thing('td', 'logts',  ts_html);
1768   } else if (layout == 'Landscape') {
1769     ts_html = last_log_ts.update(ts_html);
1770     ne = document.createElement('div');
1771     add_thing('span', 'logts',  ts_html);
1772     ne.appendChild(document.createElement('br'));
1773     add_thing('span', 'logmsg', msg_html);
1774     ne.appendChild(document.createElement('br'));
1775   } else {
1776     throw 'bad layout ' + layout;
1777   }
1778   log_elem.appendChild(ne);
1779
1780   if (!in_scrollback) {
1781     logscroll_elem.scrollTop = logscroll_elem.scrollHeight;
1782   }
1783 }
1784
1785 // ----- zoom -----
1786
1787 function zoom_pct (): number | undefined {
1788   let str = zoom_val.value;
1789   let val = parseFloat(str);
1790   if (isNaN(val)) {
1791     return undefined;
1792   } else {
1793     return val;
1794   }
1795 }
1796
1797 function zoom_enable() {
1798   zoom_btn.disabled = (zoom_pct() === undefined);
1799 }
1800
1801 function zoom_activate() {
1802   let pct = zoom_pct();
1803   if (pct !== undefined) {
1804     let fact = pct * 0.01;
1805     let last_ctm_a = space.getScreenCTM()!.a;
1806     (document.getElementsByTagName('body')[0] as HTMLElement)
1807       .style.transform = 'scale('+fact+','+fact+')';
1808     if (fact != last_zoom_factor) {
1809       if (last_ctm_a == space.getScreenCTM()!.a) {
1810         console.log('FIREFOX GETSCREENCTM BUG');
1811         firefox_bug_zoom_factor_compensation = fact;
1812       } else {
1813         console.log('No firefox getscreenctm bug');
1814         firefox_bug_zoom_factor_compensation = 1.0;
1815       }
1816       last_zoom_factor = fact;
1817     }
1818   }
1819   zoom_btn.disabled = true;
1820 }
1821
1822 // ----- test counter, startup -----
1823
1824 type TransmitUpdateEntry_Piece = {
1825   piece: PieceId,
1826   op: Object,
1827 };
1828 type ErrorTransmitUpdateEntry_Piece = TransmitUpdateEntry_Piece & {
1829   cseq: ClientSeq | null,
1830 };
1831
1832 function handle_piece_update(j: TransmitUpdateEntry_Piece) {
1833   console.log('PIECE UPDATE ',j)
1834   var piece = j.piece;
1835   var m = j.op as { [k: string]: Object };
1836   var k = Object.keys(m)[0];
1837   let p = pieces[piece];
1838   pieceops[k](piece,p, m[k]);
1839 };
1840
1841 messages.Piece = <MessageHandler>handle_piece_update;
1842
1843 type PreparedPieceState = {
1844   pos: Pos,
1845   svg: string,
1846   desc: string,
1847   held: PlayerId | null,
1848   z: ZCoord,
1849   zg: Generation,
1850   pinned: boolean,
1851   angle: number,
1852   uos: UoDescription[],
1853   moveable: PieceMoveable,
1854   rotateable: boolean,
1855   multigrab: boolean,
1856   occregion: string | null,
1857   bbox: Rect,
1858 }
1859
1860 pieceops.ModifyQuiet = <PieceHandler>function
1861 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1862   console.log('PIECE UPDATE MODIFY QUIET ',piece,info)
1863   piece_modify(piece, p, info);
1864 }
1865
1866 pieceops.Modify = <PieceHandler>function
1867 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1868   console.log('PIECE UPDATE MODIFY LOuD ',piece,info)
1869   piece_note_moved(piece,p);
1870   piece_modify(piece, p, info);
1871 }
1872
1873 pieceops.InsertQuiet = <PieceHandler>(insert_piece as any);
1874 pieceops.Insert = <PieceHandler>function
1875 (piece: PieceId, xp: any, info: PreparedPieceState) {
1876   let p = insert_piece(piece,xp,info);
1877   piece_note_moved(piece,p);
1878 }
1879
1880 function insert_piece(piece: PieceId, xp: any,
1881                       info: PreparedPieceState): PieceInfo
1882 {
1883   console.log('PIECE UPDATE INSERT ',piece,info)
1884   let delem = document.createElementNS(svg_ns,'defs');
1885   delem.setAttributeNS(null,'id','defs'+piece);
1886   delem.innerHTML = info.svg;
1887   defs_marker.insertAdjacentElement('afterend', delem);
1888   let pelem = piece_element('piece',piece);
1889   let uelem = document.createElementNS(svg_ns,'use');
1890   uelem.setAttributeNS(null,'id',"use"+piece);
1891   uelem.setAttributeNS(null,'href',"#piece"+piece);
1892   uelem.setAttributeNS(null,'data-piece',piece);
1893   let p = {
1894     uelem: uelem,
1895     pelem: pelem,
1896     delem: delem,
1897   } as any as PieceInfo; // fudge this, piece_modify_core will fix it
1898   pieces[piece] = p;
1899   p.uos = info.uos;
1900   p.queued_moves = 0;
1901   piece_resolve_special(piece, p);
1902   piece_modify_core(piece, p, info);
1903   return p;
1904 }
1905
1906 pieceops.Delete = <PieceHandler>function
1907 (piece: PieceId, p: PieceInfo, info: {}) {
1908   console.log('PIECE UPDATE DELETE ', piece)
1909   piece_stop_special(piece, p);
1910   p.uelem.remove();
1911   p.delem.remove();
1912   delete pieces[piece];
1913   if (p.held == us) {
1914     recompute_keybindings();
1915   }
1916 }
1917
1918 piece_error_handlers.PosOffTable = <PieceErrorHandler>function()
1919 { return true ; }
1920 piece_error_handlers.Conflict = <PieceErrorHandler>function()
1921 { return true ; }
1922
1923 function piece_modify_image(piece: PieceId, p: PieceInfo,
1924                             info: PreparedPieceImage) {
1925   p.delem.innerHTML = info.svg;
1926   p.pelem= piece_element('piece',piece)!;
1927   p.uos = info.uos;
1928   p.bbox = info.bbox;
1929   p.desc = info.desc;
1930   piece_resolve_special(piece, p);
1931 }
1932
1933 function piece_resolve_special(piece: PieceId, p: PieceInfo) {
1934   let new_special =
1935       p.pelem.dataset.special ?
1936       JSON.parse(p.pelem.dataset.special) : null;
1937   let new_special_kind = new_special ? new_special.kind : '';
1938   let old_special_kind = p  .special ? p  .special.kind : '';
1939
1940   if (new_special_kind != old_special_kind) {
1941     piece_stop_special(piece, p);
1942   }
1943   if (new_special) {
1944     console.log('SPECIAL START', new_special);
1945     new_special.stop = function() { };
1946     p.special = new_special;
1947     special_renderings[new_special_kind](piece, p, new_special);
1948   }
1949 }
1950
1951 function piece_stop_special(piece: PieceId, p: PieceInfo) {
1952   let s = p.special;
1953   p.special = null;
1954   if (s) {
1955     console.log('SPECIAL STOP', s);
1956     s.stop(piece, p, s);
1957   }
1958 }
1959
1960 function piece_modify(piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1961   piece_modify_image(piece, p, info);
1962   piece_modify_core(piece, p, info);
1963 }
1964                        
1965 function piece_set_pos_core(p: PieceInfo, x: number, y: number) {
1966   p.uelem.setAttributeNS(null, "x", x+"");
1967   p.uelem.setAttributeNS(null, "y", y+"");
1968 }
1969
1970 function piece_modify_core(piece: PieceId, p: PieceInfo,
1971                            info: PreparedPieceState) {
1972   p.uelem.setAttributeNS(null, "x", info.pos[0]+"");
1973   p.uelem.setAttributeNS(null, "y", info.pos[1]+"");
1974   p.held = info.held;
1975   p.held_us_raising = "NotYet";
1976   p.pinned = info.pinned;
1977   p.moveable = info.moveable;
1978   p.rotateable = info.rotateable;
1979   p.multigrab = info.multigrab;
1980   p.angle = info.angle;
1981   p.bbox = info.bbox;
1982   piece_set_zlevel_from(piece,p,info);
1983   let occregions_changed = occregion_update(piece, p, info);
1984   piece_checkconflict_nrda(piece,p);
1985   redisplay_ancillaries(piece,p);
1986   if (occregions_changed) redisplay_held_ancillaries();
1987   recompute_keybindings();
1988   console.log('MODIFY DONE');
1989 }
1990 function occregion_update(piece: PieceId, p: PieceInfo,
1991                           info: PreparedPieceState) {
1992   let occregions_changed = (
1993     info.occregion != null
1994       ? occregions.insert(piece, info.occregion)
1995       : occregions.remove(piece)
1996   );
1997   return occregions_changed;
1998 }
1999 function redisplay_held_ancillaries() {
2000   for (let piece of Object.keys(pieces)) {
2001     let p = pieces[piece];
2002     if (p.held != us) continue;
2003     redisplay_ancillaries(piece,p);
2004   }
2005 }
2006
2007 type PreparedPieceImage = {
2008   svg: string,
2009   desc: string,
2010   uos: UoDescription[],
2011   bbox: Rect,
2012 }
2013
2014 type TransmitUpdateEntry_Image = {
2015   piece: PieceId,
2016   im: PreparedPieceImage,
2017 };
2018
2019 messages.Image = <MessageHandler>function(j: TransmitUpdateEntry_Image) {
2020   console.log('IMAGE UPDATE ',j)
2021   var piece = j.piece;
2022   let p = pieces[piece]!;
2023   piece_modify_image(piece, p, j.im);
2024   redisplay_ancillaries(piece,p);
2025   recompute_keybindings();
2026   console.log('IMAGE DONE');
2027 }
2028
2029 function piece_set_zlevel(piece: PieceId, p: PieceInfo,
2030                           modify : (oldtop_piece: PieceId) => void) {
2031   // Calls modify, which should set .z and/or .gz, and/or
2032   // make any necessary API call.
2033   //
2034   // Then moves uelem to the right place in the DOM.  This is done
2035   // by assuming that uelem ought to go at the end, so this is
2036   // O(new depth), which is right (since the UI for inserting
2037   // an object is itself O(new depth) UI operations to prepare.
2038
2039   let oldtop_elem = (defs_marker.previousElementSibling! as
2040                      unknown as SVGGraphicsElement);
2041   let oldtop_piece = oldtop_elem.dataset.piece!;
2042   modify(oldtop_piece);
2043
2044   let ins_before = defs_marker
2045   let earlier_elem;
2046   for (; ; ins_before = earlier_elem) {
2047     earlier_elem = (ins_before.previousElementSibling! as
2048                    unknown as SVGGraphicsElement);
2049     if (earlier_elem == pieces_marker) break;
2050     if (earlier_elem == p.uelem) continue;
2051     let earlier_p = pieces[earlier_elem.dataset.piece!]!;
2052     if (!piece_z_before(p, earlier_p)) break;
2053   }
2054   if (ins_before != p.uelem)
2055     space.insertBefore(p.uelem, ins_before);
2056
2057   check_z_order();
2058 }
2059
2060 function check_z_order() {
2061   if (!otter_debug) return;
2062   let s = pieces_marker;
2063   let last_z = "";
2064   for (;;) {
2065     s = s.nextElementSibling as SVGGraphicsElement;
2066     if (s == defs_marker) break;
2067     let piece = s.dataset.piece!;
2068     let z = pieces[piece].z;
2069     if (z < last_z) {
2070       json_report_error(['Z ORDER INCONSISTENCY!', piece, z, last_z]);
2071     }
2072     last_z = z;
2073   }
2074 }
2075
2076 function piece_note_moved(piece: PieceId, p: PieceInfo) {
2077   let now = performance.now();
2078
2079   let need_redisplay = p.last_seen_moved == null;
2080   p.last_seen_moved = now;
2081   if (need_redisplay) redisplay_ancillaries(piece,p);
2082
2083   let cutoff = now-1000.;
2084   while (movements.length > 0 && movements[0].this_motion < cutoff) {
2085     let mr = movements.shift()!;
2086     if (mr.p.last_seen_moved != null &&
2087         mr.p.last_seen_moved < cutoff) {
2088       mr.p.last_seen_moved = null;
2089       redisplay_ancillaries(mr.piece,mr.p);
2090     }
2091   }
2092
2093   movements.push({ piece: piece, p: p, this_motion: now });
2094 }
2095
2096 function piece_z_cmp(a: PieceInfo, b: PieceInfo) {
2097   if (a.z  < b.z ) return -1;
2098   if (a.z  > b.z ) return +1;
2099   if (a.zg < b.zg) return -1;
2100   if (a.zg > b.zg) return +1;
2101   return 0;
2102 }
2103
2104 function piece_z_before(a: PieceInfo, b: PieceInfo) {
2105   return piece_z_cmp(a,
2106                      b) < 0;
2107 }
2108
2109 function pieceid_z_cmp(a: PieceId, b: PieceId) {
2110   return piece_z_cmp(pieces[a]!,
2111                      pieces[b]!);
2112 }
2113
2114 pieceops.Move = <PieceHandler>function
2115 (piece,p, info: Pos ) {
2116   piece_checkconflict_nrda(piece,p);
2117   piece_note_moved(piece, p);
2118   piece_set_pos_core(p, info[0], info[1]);
2119 }
2120
2121 pieceops.MoveQuiet = <PieceHandler>function
2122 (piece,p, info: Pos ) {
2123   piece_checkconflict_nrda(piece,p);
2124   piece_set_pos_core(p, info[0], info[1]);
2125 }
2126
2127 pieceops.SetZLevel = <PieceHandler>function
2128 (piece,p, info: { z: ZCoord, zg: Generation }) {
2129   piece_note_moved(piece,p);
2130   piece_set_zlevel_from(piece,p,info);
2131 }
2132
2133 pieceops.SetZLevelQuiet = <PieceHandler>function
2134 (piece,p, info: { z: ZCoord, zg: Generation }) {
2135   piece_set_zlevel_from(piece,p,info);
2136 }
2137
2138 function piece_set_zlevel_from(piece: PieceId, p: PieceInfo,
2139                                info: { z: ZCoord, zg: Generation }) {
2140   piece_set_zlevel(piece,p, (oldtop_piece)=>{
2141     p.z  = info.z;
2142     p.zg = info.zg;
2143   });
2144 }
2145
2146 messages.Recorded = <MessageHandler>function
2147 (j: { piece: PieceId, cseq: ClientSeq,
2148       zg: Generation|null, svg: string | null, desc: string | null } ) {
2149   let piece = j.piece;
2150   let p = pieces[piece]!;
2151   piece_recorded_cseq(p, j);
2152   if (p.cseq_updatesvg != null && j.cseq >= p.cseq_updatesvg) {
2153     p.cseq_updatesvg = null;
2154     redisplay_ancillaries(piece,p);
2155   }
2156   if (j.svg != null) {
2157     p.delem.innerHTML = j.svg;
2158     p.pelem= piece_element('piece',piece)!;
2159     piece_resolve_special(piece, p);
2160     redisplay_ancillaries(piece,p);
2161   }
2162   if (j.zg != null) {
2163     var zg_new = j.zg; // type narrowing doesn't propagate :-/
2164     piece_set_zlevel(piece,p, (oldtop_piece: PieceId)=>{
2165       p.zg = zg_new;
2166     });
2167   }
2168   if (j.desc != null) {
2169     p.desc = j.desc;
2170   }
2171 }
2172
2173 function piece_recorded_cseq(p: PieceInfo, j: { cseq: ClientSeq }) {
2174   if (p.cseq_main  != null && j.cseq >= p.cseq_main ) { p.cseq_main  = null; }
2175   if (p.cseq_loose != null && j.cseq >= p.cseq_loose) { p.cseq_loose = null; }
2176 }
2177
2178 messages.RecordedUnpredictable = <MessageHandler>function
2179 (j: { piece: PieceId, cseq: ClientSeq, ns: PreparedPieceState } ) {
2180   let piece = j.piece;
2181   let p = pieces[piece]!;
2182   piece_recorded_cseq(p, j);
2183   piece_modify(piece, p, j.ns);
2184 }
2185
2186 messages.Error = <MessageHandler>function
2187 (m: any) {
2188   console.log('ERROR UPDATE ', m);
2189   var k = Object.keys(m)[0];
2190   update_error_handlers[k](m[k]);
2191 }
2192
2193 type PieceOpError = {
2194   error: string,
2195   error_msg: string,
2196   state: ErrorTransmitUpdateEntry_Piece,
2197 };
2198
2199 update_error_handlers.PieceOpError = <MessageHandler>function
2200 (m: PieceOpError) {
2201   let piece = m.state.piece;
2202   let cseq = m.state.cseq;
2203   let p = pieces[piece];
2204   console.log('ERROR UPDATE PIECE ', piece, cseq, m, m.error_msg, p);
2205   if (p == null) return; // who can say!
2206   if (m.error != 'Conflict') {
2207     // Our gen was high enough we we sent this, that it ought to have
2208     // worked.  Report it as a problem, then.
2209     add_log_message('Problem manipulating piece: ' + m.error_msg);
2210     // Mark aus as having no outstanding requests, and cancel any drag.
2211     piece_checkconflict_nrda(piece, p, true);
2212   }
2213   handle_piece_update(m.state);
2214 }
2215
2216 function piece_checkconflict_nrda(piece: PieceId, p: PieceInfo,
2217                                   already_logged: boolean = false) {
2218   // Our state machine for cseq:
2219   //
2220   // When we send an update (api_piece_x) we always set cseq.  If the
2221   // update is loose we also set cseq_beforeloose.  Whenever we
2222   // clear cseq we clear cseq_beforeloose too.
2223   //
2224   // The result is that if cseq_beforeloose is non-null precisely if
2225   // the last op we sent was loose.
2226   //
2227   // We track separately the last loose, and the last non-loose,
2228   // outstanding API request.  (We discard our idea of the last
2229   // loose request if we follow it with a non-loose one.)
2230   //
2231   // So
2232   //     cseq_main > cseq_loose         one loose request then some non-loose
2233   //     cseq_main, no cseq_loose       just non-loose requests
2234   //     no cseq_main, but cseq_loose   just one loose request
2235   //     neither                        no outstanding requests
2236   //
2237   // If our only outstanding update is loose, we ignore a detected
2238   // conflict.  We expect the server to send us a proper
2239   // (non-Conflict) error later.
2240   if (p.cseq_main != null || p.cseq_loose != null) {
2241     if (drag_pieces.some(function(dp) { return dp.piece == piece; })) {
2242       console.log('drag end due to conflict');
2243       drag_end();
2244     }
2245   }
2246   if (p.cseq_main != null) {
2247     if (!already_logged)
2248       add_log_message('Conflict! - simultaneous update');
2249   }
2250   p.cseq_main = null;
2251   p.cseq_loose = null;
2252 }
2253
2254 function test_swap_stack() {
2255   let old_bot = pieces_marker.nextElementSibling!;
2256   let container = old_bot.parentElement!;
2257   container.insertBefore(old_bot, defs_marker);
2258   window.setTimeout(test_swap_stack, 1000);
2259 }
2260
2261 function startup() {
2262   console.log('STARTUP');
2263   console.log(wasm_bindgen.setup("OK"));
2264
2265   var body = document.getElementById("main-body")!;
2266   zoom_btn = document.getElementById("zoom-btn") as any;
2267   zoom_val = document.getElementById("zoom-val") as any;
2268   links_elem = document.getElementById("links") as any;
2269   ctoken = body.dataset.ctoken!;
2270   us = body.dataset.us!;
2271   gen = +body.dataset.gen!;
2272   let sse_url_prefix = body.dataset.sseUrlPrefix!;
2273   status_node = document.getElementById('status')!;
2274   status_node.innerHTML = 'js-done';
2275   log_elem = document.getElementById("log")!;
2276   logscroll_elem = document.getElementById("logscroll") || log_elem;
2277   let dataload = JSON.parse(body.dataset.load!);
2278   held_surround_colour = dataload.held_surround_colour!;
2279   players = dataload.players!;
2280   delete body.dataset.load;
2281   uos_node = document.getElementById("uos")!;
2282   occregions = wasm_bindgen.empty_region_list();
2283
2284   space = svg_element('space')!;
2285   pieces_marker = svg_element("pieces_marker")!;
2286   defs_marker = svg_element("defs_marker")!;
2287   movehist_start = svg_element('movehist_marker')!;
2288   movehist_end = svg_element('movehist_end')!;
2289   rectsel_path = svg_element('rectsel_path')!;
2290   svg_ns = space.getAttribute('xmlns')!;
2291
2292   for (let uelem = pieces_marker.nextElementSibling! as SVGGraphicsElement;
2293        uelem != defs_marker;
2294        uelem = uelem.nextElementSibling! as SVGGraphicsElement) {
2295     let piece = uelem.dataset.piece!;
2296     let p = JSON.parse(uelem.dataset.info!);
2297     p.uelem = uelem;
2298     p.delem = piece_element('defs',piece);
2299     p.pelem = piece_element('piece',piece);
2300     p.queued_moves = 0;
2301     occregion_update(piece, p, p); delete p.occregion;
2302     delete uelem.dataset.info;
2303     pieces[piece] = p;
2304     piece_resolve_special(piece,p);
2305     redisplay_ancillaries(piece,p);
2306   }
2307
2308   if (test_update_hook == null) test_update_hook = function() { };
2309   test_update_hook();
2310
2311   last_log_ts = wasm_bindgen.timestamp_abbreviator(dataload.last_log_ts);
2312
2313   for (let ent of dataload.movehist.hist) {
2314     movehist_record(ent);
2315   }
2316
2317   var es = new EventSource(
2318     sse_url_prefix + "/_/updates?ctoken="+ctoken+'&gen='+gen
2319   );
2320   es.onmessage = function(event) {
2321     console.log('GOTEVE', event.data);
2322     var k;
2323     var m;
2324     try {
2325       var [tgen, ms] = JSON.parse(event.data);
2326       for (m of ms) {
2327         k = Object.keys(m)[0];
2328         messages[k](m[k]);
2329       }
2330       gen = tgen;
2331       test_update_hook();
2332     } catch (exc) {
2333       var s = exc.toString();
2334       string_report_error('exception handling update '
2335                           + k + ': ' + JSON.stringify(m) + ': ' + s);
2336     }
2337   }
2338   es.addEventListener('commsworking', function(event) {
2339     console.log('GOTDATA', (event as any).data);
2340     status_node.innerHTML = (event as any).data;
2341   });
2342   es.addEventListener('player-gone', function(event) {
2343     console.log('PLAYER-GONE', event);
2344     status_node.innerHTML = (event as any).data;
2345     add_log_message('<strong>You are no longer in the game</strong>');
2346     space.removeEventListener('mousedown', some_mousedown);
2347     document.removeEventListener('keydown', some_keydown);
2348     es.close();
2349   });
2350   es.addEventListener('updates-expired', function(event) {
2351     console.log('UPDATES-EXPIRED', event);
2352     string_report_error('connection to server interrupted too long');
2353   });
2354   es.onerror = function(e) {
2355     let info = {
2356       updates_error : e,
2357       updates_event_source : es,
2358       updates_event_source_ready : es.readyState,
2359       update_oe : (e as any).className,
2360     };
2361     if (es.readyState == 2) {
2362       json_report_error({
2363         reason: "TOTAL SSE FAILURE",
2364         info: info,
2365       })
2366     } else {
2367       console.log('SSE error event', info);
2368     }
2369   }
2370   recompute_keybindings();
2371   space.addEventListener('mousedown', some_mousedown);
2372   space.addEventListener('dragstart', function (e) {
2373     e.preventDefault();
2374     e.stopPropagation();
2375   }, true);
2376   document.addEventListener('keydown',   some_keydown);
2377   check_z_order();
2378 }
2379
2380 type DieSpecialRendering = SpecialRendering & {
2381   cd_path: SVGPathElement,
2382   loaded_ts: DOMHighResTimeStamp,
2383   loaded_remprop: number,
2384   total_ms: number,
2385   radius: number,
2386   anim_id: number | null,
2387 };
2388 special_renderings['Die'] = function(piece: PieceId, p: PieceInfo,
2389                                      s: DieSpecialRendering) {
2390   let cd_path = document.getElementById('def.'+piece+'.die.cd');
2391   if (!cd_path) return;
2392
2393   s.cd_path = cd_path as any as SVGPathElement;
2394   s.loaded_ts = performance.now();
2395   s.loaded_remprop = parseFloat(cd_path.dataset.remprop!)!;
2396   s.total_ms       = parseFloat(cd_path.dataset.total_ms!)!;
2397   s.radius         = parseFloat(cd_path.dataset.radius!)!;
2398
2399   s.stop = die_rendering_stop as any;
2400   die_request_animation(piece, p, s);
2401 } as any;
2402 function die_request_animation(piece: PieceId, p: PieceInfo,
2403                                s: DieSpecialRendering) {
2404   s.anim_id = window.requestAnimationFrame(
2405     function(ts) { die_render_frame(piece, p, s, ts) }
2406   );
2407 }
2408 function die_render_frame(piece: PieceId, p: PieceInfo,
2409                           s: DieSpecialRendering, ts: DOMHighResTimeStamp) {
2410   s.anim_id = null;
2411   let remprop = s.loaded_remprop - (ts - s.loaded_ts) / s.total_ms;
2412   //console.log('DIE RENDER', piece, s, remprop);
2413   if (remprop <= 0) {
2414     console.log('DIE COMPLETE', piece, s, remprop);
2415     let to_remove: Element = s.cd_path;
2416     for (;;) {
2417       let previous = to_remove.previousElementSibling!;
2418       // see dice/overlya-template-extractor
2419       if (to_remove.tagName == 'text') break;
2420       to_remove.remove();
2421       to_remove = previous;
2422     }
2423   } else {
2424     let path_d = wasm_bindgen.die_cooldown_path(s.radius, remprop);
2425     s.cd_path.setAttributeNS(null, "d", path_d);
2426     die_request_animation(piece, p, s);
2427   }
2428 }
2429 function die_rendering_stop(piece: PieceId, p: PieceInfo,
2430                             s: DieSpecialRendering) {
2431   let anim_id = s.anim_id;
2432   if (anim_id == null) return;
2433   s.anim_id = null;
2434   window.cancelAnimationFrame(anim_id);
2435 }    
2436
2437 declare var wasm_input : any;
2438 var wasm_promise : Promise<any>;;
2439
2440 function doload(){
2441   console.log('DOLOAD');
2442   globalinfo_elem = document.getElementById('global-info')!;
2443   layout = globalinfo_elem!.dataset!.layout! as any;
2444   var elem = document.getElementById('loading_token')!;
2445   var ptoken = elem.dataset.ptoken;
2446   xhr_post_then('/_/session/' + layout, 
2447                 JSON.stringify({ ptoken : ptoken }),
2448                 loaded);
2449
2450   wasm_promise = wasm_input
2451     .then(wasm_bindgen);
2452 }
2453
2454 function loaded(xhr: XMLHttpRequest){
2455   console.log('LOADED');
2456   var body = document.getElementById('loading_body')!;
2457   wasm_promise.then((got_wasm) => {
2458     wasm = got_wasm;
2459     body.outerHTML = xhr.response;
2460     try {
2461       startup();
2462     } catch (exc) {
2463       let s = exc.toString();
2464       string_report_error_raw('Exception on load, unrecoverable: ' + s);
2465     }
2466   });
2467 }
2468
2469 // todo scroll of log messages to bottom did not always work somehow
2470 //    think I have fixed this with approximation
2471
2472 //@@notest
2473 doload();