3 // Copyright 2020-2021 Ian Jackson and contributors to Otter
4 // SPDX-License-Identifier: AGPL-3.0-or-later
5 // There is NO WARRANTY.
13 // <use id="use{}", href="#piece{}" x= y= >
14 // .piece piece id (static)
15 // container to allow quick movement and hang stuff off
25 // .dragraise dragged more than this ? raise to top!
26 // .special enum RenderSpecial
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{}" >
36 // generated by server, referenced by JS in pelem for selection
39 // generated by server, reserved for Piece trait impl
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;
56 type UoDescription = {
58 wrc: WhatResponseToClientOp,
64 type UoRecord = UoDescription & {
65 targets: PieceId[] | null,
70 // On load, starts from SessionPieceLoadJson (Rust-only)
71 // On update, updated field-by-field from PreparedPieceState (Rust&JS)
73 held : PlayerId | null,
74 cseq_main : number | null,
75 cseq_loose: number | null,
76 cseq_updatesvg : number | null,
81 moveable: PieceMoveable,
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,
95 special: SpecialRendering | null,
98 type SpecialRendering = {
100 stop: SpecialRenderingCallback,
103 let wasm : InitOutput;
105 var pieces : { [piece: string]: PieceInfo } = Object.create(null);
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)
111 type SpecialRenderingCallback =
112 (piece: PieceId, p: PieceInfo, s: SpecialRendering) => void;
113 interface DispatchTable<H> { [key: string]: H };
115 var otter_debug: boolean;
118 var movehist_len_i: number;
119 var movehist_len_max: number;
120 var movehist_lens: number[];
122 // todo turn all var into let
123 // todo any exceptions should have otter in them or something
124 var globalinfo_elem : HTMLElement;
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;
137 var gen : Generation = 0;
138 var cseq : ClientSeq = 0;
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;
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;
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;
171 type PaneName = string;
172 const pane_keys : { [key: string]: PaneName } = {
178 const uo_kind_prec : { [kind: string]: number } = {
190 var players : { [player: string]: PlayerInfo };
192 type MovementRecord = { // for yellow halo, unrelasted to movehist
195 this_motion: DOMHighResTimeStamp,
197 var movements : MovementRecord[] = [];
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); }
207 xhr.timeout = general_timeout;
208 xhr.open('POST',url);
209 xhr.setRequestHeader('Content-Type','application/json');
213 function xhr_report_error(xhr: XMLHttpRequest) {
215 statusText : xhr.statusText,
216 responseText : xhr.responseText,
220 function json_report_error(error_for_json: Object) {
221 let error_message = JSON.stringify(error_for_json);
222 string_report_error(error_message);
225 function string_report_error(error_message: String) {
226 string_report_error_raw('Error (reloading may help?): ' + error_message)
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?
235 function api_immediate(meth: string, data: Object) {
236 api_queue.push([meth, data]);
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]);
243 function api_check() {
244 if (api_posting) { return; }
245 if (!api_queue.length) { test_update_hook(); return; }
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;
253 if (p.queued_moves == 0) break;
254 } while (api_queue.length);
256 xhr_post_then('/_/api/'+meth, JSON.stringify(data), api_posted);
258 function api_posted() {
263 function api_piece_x(f: (meth: string, payload: Object) => void,
266 piece: PieceId, p: PieceInfo,
285 function api_piece(meth: string,
286 piece: PieceId, p: PieceInfo,
288 api_piece_x(api_immediate, false,meth, piece, p, op);
291 function svg_element(id: string): SVGGraphicsElement | null {
292 let elem = document.getElementById(id);
293 return elem as unknown as (SVGGraphicsElement | null);
295 function piece_element(base: string, piece: PieceId): SVGGraphicsElement | null
297 return svg_element(base+piece);
300 function piece_moveable(p: PieceInfo) {
301 return p.moveable == 'Yes' || p.moveable == 'IfWresting' && wresting;
303 function treat_as_pinned(p: { pinned: boolean }): boolean {
304 return p.pinned && !wresting;
306 function pinned_message_for_log(p: PieceInfo): string {
307 return 'That piece ('+p.desc+') is pinned to the table.';
310 // ----- key handling -----
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;
332 uo_map[uo.def_key] = currently;
334 currently.desc = currently.desc < uo.desc ? currently.desc : uo.desc;
335 currently.targets!.push(piece);
338 all_targets.sort(pieceid_z_cmp);
339 let add_uo = function(targets: PieceId[] | null, uo: UoDescription) {
340 uo_map[uo.def_key] = {
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;
351 if (got_rotateable) {
352 add_uo(all_targets, {
359 add_uo(all_targets, {
364 desc: "rotate right",
367 add_uo(all_targets, {
372 desc: "send to bottom (below other pieces)",
374 add_uo(all_targets, {
379 desc: "raise to top",
382 if (all_targets.length) {
384 for (let t of all_targets) {
385 got |= 1 << Number(pieces[t]!.pinned);
388 add_uo(all_targets, {
392 desc: 'Pin to table',
395 } else if (got == 2) {
396 add_uo(all_targets, {
400 desc: 'Unpin from table',
406 def_key: wresting ? 'W SPC' /* won't match, handle ad-hoc */ : 'W',
409 desc: wresting ? 'Exit wresting mode' : 'Enter wresting mode',
412 if (special_count != null) {
414 if (special_count == 0) {
415 desc = 'select bottommost';
417 desc = `select ${special_count}`;
419 desc = `cancel <strong style="color:purple">${desc}</strong>`;
421 def_key: 'SPC', // won't match key event; we handle this ad-hoc
423 opname: 'cancel-special',
431 opname: 'motion-hint-history',
432 desc: 'Recent history display',
435 var uo_keys = Object.keys(uo_map);
436 uo_keys.sort(function (ak,bk) {
439 if (a==null || b==null) return (
443 return uo_kind_prec[a.kind] - uo_kind_prec[b.kind]
444 || ak.localeCompare(bk);
447 for (let celem = uos_node.firstElementChild;
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') { }
456 for (var kk of uo_keys) {
459 let prec = uo_kind_prec[uo.kind];
460 let ent = document.createElement('div');
461 ent.innerHTML = '<b>' + kk + '</b> ' + uo.desc;
463 ent.setAttribute('class','uokey-l');
464 uos_node.insertBefore(ent, mid_elem);
466 ent.setAttribute('class','uokey-r');
467 uos_node.appendChild(ent);
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;
481 // someone else is dealing with it ?
482 let tag = (e.target as HTMLElement).tagName;
483 if (tag == 'INPUT') return;
486 let y = function() { e.preventDefault(); e.stopPropagation(); }
488 let pane = pane_keys[e.key];
491 return pane_switch(pane);
494 let special_count_key = parseInt(e.key);
495 if (isFinite(special_count_key)) {
497 if (special_count == null) special_count = 0;
499 special_count += special_count_key;
500 special_count %= 100000;
501 mousecursor_etc_reupdate();
504 if (e.key == ' ' || (e.key == 'W' && wresting)) {
506 special_count = null;
508 mousecursor_etc_reupdate();
511 if (e.key == 'Backspace') {
512 if (special_count == null) {
514 } else if (special_count >= 10) {
515 special_count = Math.round(special_count / 10 - .45);
517 special_count = null;
519 mousecursor_etc_reupdate();
523 let uo = uo_map[e.key];
524 if (uo === undefined || uo === null) return;
527 console.log('KEY UO', e, uo);
528 if (uo.kind == 'Client' || uo.kind == 'ClientExtra') {
529 let f = keyops_local[uo.opname];
533 if (!(uo.kind == 'Global' || uo.kind == 'GlobalExtra' || uo.kind == 'Piece'))
534 throw 'bad kind '+uo.kind;
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);
547 function pane_switch(newpane: PaneName) {
550 new_e = document.getElementById('pane_' + newpane)!;
551 let style = new_e.getAttribute('style');
552 if (style || newpane == 'help') break;
555 for (let old_e = new_e.parentElement!.firstElementChild;
557 old_e = old_e.nextElementSibling) {
558 old_e.setAttribute('style','display: none;');
560 new_e.removeAttribute('style');
563 function mousecursor_etc_reupdate() {
564 let style_elem = document.getElementById("space-cursor-style")!;
568 let path = 'stroke-linecap="square" d="M -10 -10 10 10 M 10 -10 -10 10"';
570 document.getElementById('wresting-warning')!.innerHTML = !wresting ? "" :
571 " <strong>(wresting mode!)</strong>";
573 if (wresting != was_wresting) {
575 was_wresting = wresting;
580 if (special_count == null) {
582 } else if (special_count == 0) {
585 text = "W " + special_count;
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>
597 } else if (special_count == null) {
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);
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>
614 let path = 'stroke-linecap="square" d="M -10 -10 0 0 10 -10 M 0 0 0 -20"';
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}/>
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);
632 cursor: url(data:image/svg+xml;base64,${svg_data}) ${xy}, auto;
634 style_elem.innerHTML = style_text;
636 recompute_keybindings();
639 keyops_local['left' ] = function (uo: UoRecord) { rotate_targets(uo, +1); }
640 keyops_local['right'] = function (uo: UoRecord) { rotate_targets(uo, -1); }
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;
648 let transform = wasm_bindgen.angle_transform(p.angle);
649 p.pelem.setAttributeNS(null,'transform',transform);
650 api_piece('rotate', piece,p, p.angle);
652 recompute_keybindings();
658 type LowerTodoItem = {
664 type LowerTodoList = { [piece: string]: LowerTodoItem };
666 keyops_local['lower'] = function (uo: UoRecord) { lower_targets(uo); }
668 function lower_heavy(p: PieceInfo): boolean {
669 return wresting || p.pinned || p.moveable == "No";
672 function lower_targets(uo: UoRecord): boolean {
673 let targets_todo : LowerTodoList = Object.create(null);
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, };
680 let problem = lower_pieces(targets_todo);
681 if (problem !== null) {
682 add_log_message('Cannot lower: ' + problem);
688 function lower_pieces(targets_todo: LowerTodoList):
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
701 // Disregarding heavy targets:
703 // Z <some stuff not including any light targets>
705 // topmost light target *
707 // B light non-target
708 // B | light target *
709 // B | heavy non-target, mis-stacked *
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 ->
718 // A heavy non-targets (nomove_heavy)
719 // <- tomove_heavy: insert all heavy targets here P ->
721 // When wresting, treat all targets as heavy.
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[] = [];
734 let q_z_top : ZCoord | null = null; // null some some
735 let n_targets_todo_light = 0; // 0
737 let any_targets = false;
738 for (const piece of Object.keys(targets_todo)) {
740 let p = targets_todo[piece];
741 if (!p.heavy) n_targets_todo_light++;
743 if (!any_targets) return 'Nothing to lower!';
745 let walk = pieces_marker;
746 for (;;) { // starting at the bottom of the stack order
747 if (Object.keys(targets_todo).length == 0 &&
749 // no targets left, state Z, we can stop now
750 console.log('LOWER STATE Z FINISHED');
754 let new_walk = walk.nextElementSibling;
755 if (new_walk == null) {
756 console.log('LOWER WALK NO SIBLING!');
759 walk = new_walk as SVGGraphicsElement;
760 let piece = walk.dataset.piece;
762 console.log('LOWER WALK REACHED TOP');
766 let p = pieces[piece]!;
767 let todo = targets_todo[piece];
770 if (q_z_top === null && !todo.heavy) {
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);
781 let p_heavy = lower_heavy(p);
782 if (q_z_top === null) { // state A
784 console.log('LOWER WALK', piece, 'STATE A -> Z');
787 console.log('LOWER WALK', piece, 'STATE A');
788 nomove_heavy.push({ p, piece });
795 console.log('LOWER WALK', piece, 'STATE B MIS-STACKED');
796 tomove_misstacked.push({ p, piece });
798 console.log('LOWER WALK', piece, 'STATE B');
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.)
806 tomove_misstacked.length ? tomove_misstacked[0].p.z :
807 tomove_light .length ? tomove_light [0].p.z :
808 tomove_heavy [0].p.z;
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.
818 // Treating them as misstacked instead is sufficient, provided
819 // we put them at the front (bottom end) of the misstacked list.
821 // This is X in the chart.
823 let restack = nomove_heavy.pop()!;
824 console.log('LOWER CLASHING Z - RESTACKING', restack);
825 tomove_misstacked.unshift(restack);
829 content: Entry[], // bottom to top
831 z_bot: ZCoord | null,
834 let plan : PlanEntry[] = [];
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;
842 if (nomove_heavy.length == 0) {
844 content: partP.concat(partQ),
852 z_bot: nomove_heavy[nomove_heavy.length-1].p.z,
855 z_top: nomove_heavy[0].p.z,
860 console.log('LOWER PLAN', plan);
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";
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;
875 let first_z = pe.content[0].p.z;
876 if (z_top >= first_z)
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) {
884 p.held_us_raising = "Lowered";
885 piece_set_zlevel(e.piece, p, (oldtop_piece) => {
886 let z = zrange.next();
888 api_piece("setz", e.piece, e.p, { z });
895 keyops_local['wrest'] = function (uo: UoRecord) {
896 wresting = !wresting;
897 mousecursor_etc_reupdate();
900 keyops_local['motion-hint-history'] = function (uo: UoRecord) {
902 movehist_len_i %= movehist_lens.length;
903 movehist_revisible();
906 keyops_local['pin' ] = function (uo) {
907 if (!lower_targets(uo)) return;
910 keyops_local['unpin'] = function (uo) {
911 pin_unpin(uo, false);
914 function pin_unpin(uo: UoRecord, newpin: boolean) {
915 for (let piece of uo.targets!) {
916 let p = pieces[piece]!;
918 api_piece('pin', piece,p, newpin);
919 redisplay_ancillaries(piece,p);
921 recompute_keybindings();
924 // ----- raising -----
926 keyops_local['raise'] = function (uo: UoRecord) { raise_targets(uo); }
928 function raise_targets(uo: UoRecord) {
930 for (let piece of uo.targets!) {
931 let p = pieces[piece]!;
932 if (p.pinned || !piece_moveable(p)) continue;
934 piece_raise(piece, p, "NotYet");
937 add_log_message('No pieces could be raised.');
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 });
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);
953 implement(piece,p,z);
957 // ----- clicking/dragging pieces -----
965 enum DRAGGING { // bitmask
973 var drag_pieces : DragInfo[] = [];
974 var dragging = DRAGGING.NO;
975 var dcx : number | null;
976 var dcy : number | null;
978 const DRAGTHRESH = 5;
980 let rectsel_start: Pos | null;
981 let rectsel_shifted: boolean | null;
982 let rectsel_started_on_pinned: PieceInfo | null;
983 const RECTSELTHRESH = 5;
985 function piece_xy(p: PieceInfo): Pos {
986 return [ parseFloat(p.uelem.getAttributeNS(null,"x")!),
987 parseFloat(p.uelem.getAttributeNS(null,"y")!) ];
990 function drag_start_prepare(new_dragging: DRAGGING) {
991 dragging = new_dragging;
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]);
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);
1012 dox: dox + p.drag_delta,
1019 function some_mousedown(e : MouseEvent) {
1020 console.log('mousedown', e, e.clientX, e.clientY, e.target);
1022 if (e.button != 0) { return }
1023 if (e.altKey) { return }
1024 if (e.metaKey) { return }
1028 drag_mousedown(e, e.shiftKey);
1032 type MouseFindClicked = null | {
1034 held: PlayerId | null,
1039 type PieceSet = { [piece: string]: true };
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, { });
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 });
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]);
1066 function mouse_clicked_one(piece: PieceId, p: PieceInfo): MouseFindClicked {
1068 let pinned = p.pinned;
1069 return { clicked: [piece], held, pinned };
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;
1081 let already_count = 0;
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}.`);
1095 let piece = uelem.dataset.piece!;
1097 function is_already() {
1098 if (note_already != null) {
1100 note_already[piece] = true;
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))
1109 if (!predicate(p)) {
1112 if (p.pinned) pinned = true;
1116 if (held == us && !allow_for_deselect) held = null;
1119 // user is going to be deselecting
1121 // skip ones we don't have
1125 } else { // user is going to be selecting
1128 continue; // skip ones we have already
1129 } else if (p.held == null) {
1131 held = p.held; // wrestish
1134 clicked.push(piece);
1136 if (clicked.length == 0) return null;
1137 else return { clicked, held: held!, pinned: pinned! };
1140 function mouse_find_lowest(e: MouseEvent) {
1141 let clickpos = mouseevent_pos(e);
1142 let uelem = pieces_marker;
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);
1155 function mouse_find_clicked(e: MouseEvent,
1156 target: SVGGraphicsElement, piece: PieceId,
1157 count_allow_for_deselect: boolean,
1158 note_already: PieceSet | null,
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;
1172 if (special_count > 99) {
1174 `Refusing to try to select ${special_count} pieces (max is 99)`);
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); }
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;
1191 if (piece) p = pieces[piece]!;
1193 if (!piece || treat_as_pinned(p!)) {
1194 rectsel_start = mouseevent_pos(e);
1195 rectsel_shifted = shifted;
1196 rectsel_started_on_pinned = p;
1197 window.addEventListener('mousemove', rectsel_mousemove, true);
1198 window.addEventListener('mouseup', rectsel_mouseup, true);
1202 let note_already = shifted ? null : Object.create(null);
1204 let c = mouse_find_clicked(e, target, piece, false, note_already);
1205 if (c == null) return;
1206 let clicked = c.clicked;
1208 let multigrab = c.multigrab;
1210 special_count = null;
1211 mousecursor_etc_reupdate();
1217 ungrab_clicked(clicked);
1220 drag_start_prepare(DRAGGING.MAYBE_UNGRAB);
1221 } else if (held == null || wresting) {
1223 ungrab_all_except(note_already);
1225 if (treat_as_pinned(c)) {
1226 add_log_message(pinned_message_for_log(pieces[c.clicked[0]!]!));
1229 grab_clicked(clicked, !wresting, multigrab);
1230 drag_start_prepare(DRAGGING.MAYBE_GRAB);
1232 add_log_message('That piece is held by another player.');
1238 window.addEventListener('mousemove', drag_mousemove, true);
1239 window.addEventListener('mouseup', drag_mouseup, true);
1242 function mouseevent_pos(e: MouseEvent): Pos {
1243 let ctm = space.getScreenCTM()!;
1244 let px = (e.clientX - ctm.e)/(ctm.a * firefox_bug_zoom_factor_compensation);
1245 let py = (e.clientY - ctm.f)/(ctm.d * firefox_bug_zoom_factor_compensation);
1246 let pos: Pos = [px, py];
1247 console.log('mouseevent_pos', pos);
1251 function p_bbox_contains(p: PieceInfo, test: Pos) {
1252 let ctr = piece_xy(p);
1253 for (let i of [0,1]) {
1254 let offset = test[i] - ctr[i];
1255 if (offset < p.bbox[0][i] || offset > p.bbox[1][i])
1261 function do_ungrab_n(todo: [PieceId, PieceInfo][]) {
1262 function sort_with(a: [PieceId, PieceInfo],
1263 b: [PieceId, PieceInfo]): number {
1264 return piece_z_cmp(a[1], b[1]);
1266 todo.sort(sort_with);
1267 for (let [tpiece, tp] of todo) {
1268 do_ungrab_1(tpiece, tp);
1271 function ungrab_all_except(dont: PieceSet | null) {
1272 let todo: [PieceId, PieceInfo][] = [];
1273 for (let tpiece of Object.keys(pieces)) {
1274 if (dont && dont[tpiece]) continue;
1275 let tp = pieces[tpiece]!;
1276 if (tp.held == us) {
1277 todo.push([tpiece, tp]);
1282 function ungrab_all() {
1283 ungrab_all_except(null);
1286 function set_grab_us(piece: PieceId, p: PieceInfo) {
1288 p.held_us_raising = "NotYet";
1290 redisplay_ancillaries(piece,p);
1291 recompute_keybindings();
1293 function do_ungrab_1(piece: PieceId, p: PieceInfo) {
1294 let autoraise = p.held_us_raising == "Raised";
1296 p.held_us_raising = "NotYet";
1298 redisplay_ancillaries(piece,p);
1299 recompute_keybindings();
1300 api_piece('ungrab', piece,p, { autoraise });
1303 function clear_halo(piece: PieceId, p: PieceInfo) {
1304 let was = p.last_seen_moved;
1305 p.last_seen_moved = null;
1306 if (was) redisplay_ancillaries(piece,p);
1309 function ancillary_node(piece: PieceId, stroke: string): SVGGraphicsElement {
1310 var nelem = document.createElementNS(svg_ns,'use');
1311 nelem.setAttributeNS(null,'href','#surround'+piece);
1312 nelem.setAttributeNS(null,'stroke',stroke);
1313 nelem.setAttributeNS(null,'fill','none');
1314 return nelem as any;
1317 function redisplay_ancillaries(piece: PieceId, p: PieceInfo) {
1318 let href = '#surround'+piece;
1319 console.log('REDISPLAY ANCILLARIES',href);
1321 for (let celem = p.pelem.firstElementChild;
1324 var nextelem = celem.nextElementSibling
1325 let thref = celem.getAttributeNS(null,"href");
1326 if (thref == href) {
1331 let halo_colour = null;
1332 if (p.cseq_updatesvg != null) {
1333 halo_colour = 'purple';
1334 } else if (p.last_seen_moved != null) {
1335 halo_colour = 'yellow';
1336 } else if (p.held != null && p.pinned) {
1337 halo_colour = '#8cf';
1339 if (halo_colour != null) {
1340 let nelem = ancillary_node(piece, halo_colour);
1341 if (p.held != null) {
1342 // value 2ps is also in src/pieces.rs SELECT_STROKE_WIDTH
1343 nelem.setAttributeNS(null,'stroke-width','2px');
1345 p.pelem.prepend(nelem);
1347 if (p.held != null) {
1350 da = players[p.held!]!.dasharray;
1352 let [px, py] = piece_xy(p);
1353 let inoccult = occregions.contains_pos(px, py);
1354 p.held_us_inoccult = inoccult;
1356 da = "0.9 0.6"; // dotted dasharray
1359 let nelem = ancillary_node(piece, held_surround_colour);
1361 nelem.setAttributeNS(null,'stroke-dasharray',da);
1363 p.pelem.appendChild(nelem);
1367 function drag_mousemove(e: MouseEvent) {
1368 var ctm = space.getScreenCTM()!;
1369 var ddx = (e.clientX - dcx!)/(ctm.a * firefox_bug_zoom_factor_compensation);
1370 var ddy = (e.clientY - dcy!)/(ctm.d * firefox_bug_zoom_factor_compensation);
1371 var ddr2 = ddx*ddx + ddy*ddy;
1372 if (!(dragging & DRAGGING.YES)) {
1373 if (ddr2 > DRAGTHRESH) {
1374 for (let dp of drag_pieces) {
1375 let tpiece = dp.piece;
1376 let tp = pieces[tpiece]!;
1377 if (tp.moveable == "Yes") {
1379 } else if (tp.moveable == "IfWresting") {
1380 if (wresting) continue;
1382 `That piece (${tp.desc}) can only be moved when Wresting.`);
1385 `That piece (${tp.desc}) cannot be moved at the moment.`);
1389 dragging |= DRAGGING.YES;
1392 //console.log('mousemove', ddx, ddy, dragging);
1393 if (dragging & DRAGGING.YES) {
1394 console.log('DRAG PIECES',drag_pieces);
1395 for (let dp of drag_pieces) {
1396 console.log('DRAG PIECES PIECE',dp);
1397 let tpiece = dp.piece;
1398 let tp = pieces[tpiece]!;
1399 var x = Math.round(dp.dox + ddx);
1400 var y = Math.round(dp.doy + ddy);
1401 let need_redisplay_ancillaries = (
1403 occregions.contains_pos(x,y) != tp.held_us_inoccult
1405 piece_set_pos_core(tp, x, y);
1407 api_piece_x(api_delay, false, 'm', tpiece,tp, [x, y] );
1408 if (need_redisplay_ancillaries) redisplay_ancillaries(tpiece, tp);
1410 if (!(dragging & DRAGGING.RAISED)) {
1412 for (let dp of drag_pieces) {
1413 let piece = dp.piece;
1414 let p = pieces[piece]!;
1415 if (p.held_us_raising == "Lowered") continue;
1416 let dragraise = +p.pelem.dataset.dragraise!;
1417 if (dragraise > 0 && ddr2 >= dragraise*dragraise) {
1418 dragging |= DRAGGING.RAISED;
1419 console.log('CHECK RAISE ', dragraise, dragraise*dragraise, ddr2);
1420 piece_raise(piece,p,"Raised");
1427 function sort_drag_pieces() {
1428 function sort_with(a: DragInfo, b: DragInfo): number {
1429 return pieceid_z_cmp(a.piece,
1432 drag_pieces.sort(sort_with);
1435 function drag_mouseup(e: MouseEvent) {
1436 console.log('mouseup', dragging);
1437 let ddr2 : number = drag_mousemove(e);
1441 function drag_end() {
1442 if (dragging == DRAGGING.MAYBE_UNGRAB ||
1443 (dragging & ~DRAGGING.RAISED) == (DRAGGING.MAYBE_GRAB | DRAGGING.YES)) {
1445 for (let dp of drag_pieces) {
1446 let piece = dp.piece;
1447 let p = pieces[piece]!;
1448 do_ungrab_1(piece,p);
1454 function drag_cancel() {
1455 window.removeEventListener('mousemove', drag_mousemove, true);
1456 window.removeEventListener('mouseup', drag_mouseup, true);
1457 dragging = DRAGGING.NO;
1461 function rectsel_nontrivial_pos2(e: MouseEvent): Pos | null {
1462 let pos2 = mouseevent_pos(e);
1464 for (let i of [0,1]) {
1465 let d = pos2[i] - rectsel_start![i];
1468 return d2 > RECTSELTHRESH*RECTSELTHRESH ? pos2 : null;
1471 function rectsel_mousemove(e: MouseEvent) {
1472 let pos2 = rectsel_nontrivial_pos2(e);
1477 let pos1 = rectsel_start!;
1478 path = `M ${ pos1 [0]} ${ pos1 [1] }
1479 ${ pos2 [0]} ${ pos1 [1] }
1480 M ${ pos1 [0]} ${ pos2 [1] }
1481 ${ pos2 [0]} ${ pos2 [1] }
1482 M ${ pos1 [0]} ${ pos1 [1] }
1483 ${ pos1 [0]} ${ pos2 [1] }
1484 M ${ pos2 [0]} ${ pos1 [1] }
1485 ${ pos2 [0]} ${ pos2 [1] }`;
1487 rectsel_path.firstElementChild!.setAttributeNS(null,'d',path);
1490 function rectsel_mouseup(e: MouseEvent) {
1491 console.log('rectsel mouseup');
1492 window.removeEventListener('mousemove', rectsel_mousemove, true);
1493 window.removeEventListener('mouseup', rectsel_mouseup, true);
1494 rectsel_path.firstElementChild!.setAttributeNS(null,'d','');
1495 let pos2 = rectsel_nontrivial_pos2(e);
1498 // clicked not on an unpinned piece, and didn't drag
1499 if (rectsel_started_on_pinned !== null) {
1500 add_log_message(pinned_message_for_log(rectsel_started_on_pinned));
1502 special_count = null;
1503 mousecursor_etc_reupdate();
1504 // we'll bail in a moment, after possibly unselecting things
1507 let note_already = Object.create(null);
1511 if (special_count != null && special_count == 0) {
1512 add_log_message(`Cannot drag-select lowest.`);
1517 for (let i of [0,1]) {
1518 tl[i] = Math.min(rectsel_start![i], pos2[i]);
1519 br[i] = Math.max(rectsel_start![i], pos2[i]);
1521 c = mouse_find_predicate(
1522 special_count, rectsel_shifted!, note_already,
1523 function(p: PieceInfo) {
1524 let pp = piece_xy(p);
1525 for (let i of [0,1]) {
1526 if (pp[i] < tl[i] || pp[i] > br[i]) return false;
1534 // clicked not on a piece, didn't end up selecting anything
1535 // either because drag region had nothing in it, or special
1536 // failed, or some such.
1537 if (!rectsel_shifted) {
1539 while (mr = movements.pop()) {
1540 mr.p.last_seen_moved = null;
1541 redisplay_ancillaries(mr.piece, mr.p);
1549 special_count = null;
1550 mousecursor_etc_reupdate();
1552 if (rectsel_shifted && c.held == us) {
1553 ungrab_clicked(c.clicked);
1556 if (!rectsel_shifted) {
1557 ungrab_all_except(note_already);
1559 grab_clicked(c.clicked, false, undefined);
1563 // ----- general -----
1565 type PlayersUpdate = { new_info_pane: string };
1567 messages.SetPlayer = <MessageHandler>function
1568 (j: { player: string, data: PlayerInfo } & PlayersUpdate) {
1569 players[j.player] = j.data;
1570 player_info_pane_set(j);
1573 messages.RemovePlayer = <MessageHandler>function
1574 (j: { player: string } & PlayersUpdate ) {
1575 delete players[j.player];
1576 player_info_pane_set(j);
1579 function player_info_pane_set(j: PlayersUpdate) {
1580 document.getElementById('player_list')!
1581 .innerHTML = j.new_info_pane;
1584 messages.UpdateBundles = <MessageHandler>function
1585 (j: { new_info_pane: string }) {
1586 document.getElementById('bundle_list')!
1587 .innerHTML = j.new_info_pane;
1590 messages.SetTableSize = <MessageHandler>function
1591 ([x, y]: [number, number]) {
1592 function set_attrs(elem: Element, l: [string,string][]) {
1594 elem.setAttributeNS(null,a[0],a[1]);
1597 let rect = document.getElementById('table_rect')!;
1598 set_attrs(space, wasm_bindgen.space_table_attrs(x, y));
1599 set_attrs(rect, wasm_bindgen.space_table_attrs(x, y));
1602 messages.SetTableColour = <MessageHandler>function
1604 let rect = document.getElementById('table_rect')!;
1605 rect.setAttributeNS(null, 'fill', c);
1608 messages.SetLinks = <MessageHandler>function
1610 if (msg.length != 0 && layout == 'Portrait') {
1613 links_elem.innerHTML = msg
1616 // ---------- movehist ----------
1618 type MoveHistEnt = {
1620 posx: [MoveHistPosx, MoveHistPosx],
1621 diff: { 'Moved': { d: number } },
1623 type MoveHistPosx = {
1625 angle: CompassAngle,
1626 facehint: FaceId | null,
1629 messages.MoveHistEnt = <MessageHandler>movehist_record;
1630 messages.MoveHistClear = <MessageHandler>function() {
1631 movehist_revisible_custmax(0);
1634 function movehist_record(ent: MoveHistEnt) {
1635 let old_pos = ent.posx[0].pos;
1636 let new_pos = ent.posx[1].pos;
1639 movehist_gen %= (movehist_len_max * 2);
1640 let meid = 'motionhint-marker-' + movehist_gen;
1642 let moved = ent.diff['Moved'];
1646 for (let end of [0,1]) {
1647 let s = (!end ? MOVEHIST_ENDS : d - MOVEHIST_ENDS) / d;
1648 ends.push([ (1-s) * old_pos[0] + s * new_pos[0],
1649 (1-s) * old_pos[1] + s * new_pos[1] ]);
1651 let g = document.createElementNS(svg_ns,'g');
1653 let pi = players[ent.held];
1654 let nick = pi ? pi.nick : '';
1655 // todo: would be nice to place text variously along arrow, rotated
1657 <marker id="${meid}" viewBox="2 0 ${sz} ${sz}"
1658 refX="${sz}" refY="${sz/2}"
1659 markerWidth="${sz + 2}" markerHeight="${sz}"
1660 stroke="yellow" fill="none"
1661 orient="auto-start-reverse" stroke-linejoin="miter">
1662 <path d="M 0 0 L ${sz} ${sz/2} L 0 ${sz}" />
1664 <line x1="${ends[0][0].toString()}"
1665 y1="${ends[0][1].toString()}"
1666 x2="${ends[1][0].toString()}"
1667 y2="${ends[1][1].toString()}"
1669 stroke-width="1" pointer-events="none"
1670 marker-end="url(#${meid})" />
1671 <text x="${((ends[0][0] + ends[1][0]) / 2).toString()}"
1672 y="${((ends[0][1] + ends[1][1]) / 2).toString()}"
1673 font-size="5" pointer-events="none"
1674 stroke-width="0.1">${nick}</text>
1677 space.insertBefore(g, movehist_end);
1678 movehist_revisible();
1682 function movehist_revisible() {
1683 movehist_revisible_custmax(movehist_len_max);
1686 function movehist_revisible_custmax(len_max: number) {
1687 let n = movehist_lens[movehist_len_i];
1689 let node = movehist_end;
1690 while (i < len_max) {
1691 i++; // i now eg 1..10
1692 node = node.previousElementSibling! as SVGGraphicsElement;
1693 if (node == movehist_start)
1695 let prop = i > n ? 0 : (n-i+1)/n;
1696 let stroke = (prop * 1.0).toString();
1697 let marker = node.firstElementChild!;
1698 marker.setAttributeNS(null,'stroke-width',stroke);
1699 let line = marker.nextElementSibling!;
1700 line.setAttributeNS(null,'stroke-width',stroke);
1701 let text = line.nextElementSibling!;
1703 text.setAttributeNS(null,'stroke','none');
1704 text.setAttributeNS(null,'fill','none');
1706 text.setAttributeNS(null,'fill','yellow');
1707 text.setAttributeNS(null,'stroke','orange');
1711 let del = node.previousElementSibling!;
1712 if (del == movehist_start)
1720 messages.Log = <MessageHandler>function
1721 (j: { when: string, logent: { html: string } }) {
1722 add_timestamped_log_message(j.when, j.logent.html);
1725 function add_log_message(msg_html: string) {
1726 add_timestamped_log_message('', msg_html);
1729 function add_timestamped_log_message(ts_html: string, msg_html: string) {
1730 var lastent = log_elem.lastElementChild;
1734 // https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling/21627295#21627295
1736 // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
1738 let le_top = lastent.getBoundingClientRect()!.top;
1739 let le_bot = lastent.getBoundingClientRect()!.bottom;
1740 let ld_bot = logscroll_elem.getBoundingClientRect()!.bottom;
1741 console.log("ADD_LOG_MESSAGE bboxes: le t b, bb",
1742 le_top, le_bot, ld_bot);
1743 return 0.5 * (le_bot + le_top) > ld_bot;
1746 console.log('ADD LOG MESSAGE ',in_scrollback, layout, msg_html);
1748 var ne : HTMLElement;
1750 function add_thing(elemname: string, cl: string, html: string) {
1751 var ie = document.createElement(elemname);
1752 ie.innerHTML = html;
1753 ie.setAttribute("class", cl);
1757 if (layout == 'Portrait') {
1758 ne = document.createElement('tr');
1759 add_thing('td', 'logmsg', msg_html);
1760 add_thing('td', 'logts', ts_html);
1761 } else if (layout == 'Landscape') {
1762 ts_html = last_log_ts.update(ts_html);
1763 ne = document.createElement('div');
1764 add_thing('span', 'logts', ts_html);
1765 ne.appendChild(document.createElement('br'));
1766 add_thing('span', 'logmsg', msg_html);
1767 ne.appendChild(document.createElement('br'));
1769 throw 'bad layout ' + layout;
1771 log_elem.appendChild(ne);
1773 if (!in_scrollback) {
1774 logscroll_elem.scrollTop = logscroll_elem.scrollHeight;
1780 function zoom_pct (): number | undefined {
1781 let str = zoom_val.value;
1782 let val = parseFloat(str);
1790 function zoom_enable() {
1791 zoom_btn.disabled = (zoom_pct() === undefined);
1794 function zoom_activate() {
1795 let pct = zoom_pct();
1796 if (pct !== undefined) {
1797 let fact = pct * 0.01;
1798 let last_ctm_a = space.getScreenCTM()!.a;
1799 (document.getElementsByTagName('body')[0] as HTMLElement)
1800 .style.transform = 'scale('+fact+','+fact+')';
1801 if (fact != last_zoom_factor) {
1802 if (last_ctm_a == space.getScreenCTM()!.a) {
1803 console.log('FIREFOX GETSCREENCTM BUG');
1804 firefox_bug_zoom_factor_compensation = fact;
1806 console.log('No firefox getscreenctm bug');
1807 firefox_bug_zoom_factor_compensation = 1.0;
1809 last_zoom_factor = fact;
1812 zoom_btn.disabled = true;
1815 // ----- test counter, startup -----
1817 type TransmitUpdateEntry_Piece = {
1821 type ErrorTransmitUpdateEntry_Piece = TransmitUpdateEntry_Piece & {
1822 cseq: ClientSeq | null,
1825 function handle_piece_update(j: TransmitUpdateEntry_Piece) {
1826 console.log('PIECE UPDATE ',j)
1827 var piece = j.piece;
1828 var m = j.op as { [k: string]: Object };
1829 var k = Object.keys(m)[0];
1830 let p = pieces[piece];
1831 pieceops[k](piece,p, m[k]);
1834 messages.Piece = <MessageHandler>handle_piece_update;
1836 type PreparedPieceState = {
1840 held: PlayerId | null,
1845 uos: UoDescription[],
1846 moveable: PieceMoveable,
1847 rotateable: boolean,
1849 occregion: string | null,
1853 pieceops.ModifyQuiet = <PieceHandler>function
1854 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1855 console.log('PIECE UPDATE MODIFY QUIET ',piece,info)
1856 piece_modify(piece, p, info);
1859 pieceops.Modify = <PieceHandler>function
1860 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1861 console.log('PIECE UPDATE MODIFY LOuD ',piece,info)
1862 piece_note_moved(piece,p);
1863 piece_modify(piece, p, info);
1866 pieceops.InsertQuiet = <PieceHandler>(insert_piece as any);
1867 pieceops.Insert = <PieceHandler>function
1868 (piece: PieceId, xp: any, info: PreparedPieceState) {
1869 let p = insert_piece(piece,xp,info);
1870 piece_note_moved(piece,p);
1873 function insert_piece(piece: PieceId, xp: any,
1874 info: PreparedPieceState): PieceInfo
1876 console.log('PIECE UPDATE INSERT ',piece,info)
1877 let delem = document.createElementNS(svg_ns,'defs');
1878 delem.setAttributeNS(null,'id','defs'+piece);
1879 delem.innerHTML = info.svg;
1880 defs_marker.insertAdjacentElement('afterend', delem);
1881 let pelem = piece_element('piece',piece);
1882 let uelem = document.createElementNS(svg_ns,'use');
1883 uelem.setAttributeNS(null,'id',"use"+piece);
1884 uelem.setAttributeNS(null,'href',"#piece"+piece);
1885 uelem.setAttributeNS(null,'data-piece',piece);
1890 } as any as PieceInfo; // fudge this, piece_modify_core will fix it
1894 piece_resolve_special(piece, p);
1895 piece_modify_core(piece, p, info);
1899 pieceops.Delete = <PieceHandler>function
1900 (piece: PieceId, p: PieceInfo, info: {}) {
1901 console.log('PIECE UPDATE DELETE ', piece)
1902 piece_stop_special(piece, p);
1905 delete pieces[piece];
1907 recompute_keybindings();
1911 piece_error_handlers.PosOffTable = <PieceErrorHandler>function()
1913 piece_error_handlers.Conflict = <PieceErrorHandler>function()
1916 function piece_modify_image(piece: PieceId, p: PieceInfo,
1917 info: PreparedPieceImage) {
1918 p.delem.innerHTML = info.svg;
1919 p.pelem= piece_element('piece',piece)!;
1923 piece_resolve_special(piece, p);
1926 function piece_resolve_special(piece: PieceId, p: PieceInfo) {
1928 p.pelem.dataset.special ?
1929 JSON.parse(p.pelem.dataset.special) : null;
1930 let new_special_kind = new_special ? new_special.kind : '';
1931 let old_special_kind = p .special ? p .special.kind : '';
1933 if (new_special_kind != old_special_kind) {
1934 piece_stop_special(piece, p);
1937 console.log('SPECIAL START', new_special);
1938 new_special.stop = function() { };
1939 p.special = new_special;
1940 special_renderings[new_special_kind](piece, p, new_special);
1944 function piece_stop_special(piece: PieceId, p: PieceInfo) {
1948 console.log('SPECIAL STOP', s);
1949 s.stop(piece, p, s);
1953 function piece_modify(piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1954 piece_modify_image(piece, p, info);
1955 piece_modify_core(piece, p, info);
1958 function piece_set_pos_core(p: PieceInfo, x: number, y: number) {
1959 p.uelem.setAttributeNS(null, "x", x+"");
1960 p.uelem.setAttributeNS(null, "y", y+"");
1963 function piece_modify_core(piece: PieceId, p: PieceInfo,
1964 info: PreparedPieceState) {
1965 p.uelem.setAttributeNS(null, "x", info.pos[0]+"");
1966 p.uelem.setAttributeNS(null, "y", info.pos[1]+"");
1968 p.held_us_raising = "NotYet";
1969 p.pinned = info.pinned;
1970 p.moveable = info.moveable;
1971 p.rotateable = info.rotateable;
1972 p.multigrab = info.multigrab;
1973 p.angle = info.angle;
1975 piece_set_zlevel_from(piece,p,info);
1976 let occregions_changed = occregion_update(piece, p, info);
1977 piece_checkconflict_nrda(piece,p);
1978 redisplay_ancillaries(piece,p);
1979 if (occregions_changed) redisplay_held_ancillaries();
1980 recompute_keybindings();
1981 console.log('MODIFY DONE');
1983 function occregion_update(piece: PieceId, p: PieceInfo,
1984 info: PreparedPieceState) {
1985 let occregions_changed = (
1986 info.occregion != null
1987 ? occregions.insert(piece, info.occregion)
1988 : occregions.remove(piece)
1990 return occregions_changed;
1992 function redisplay_held_ancillaries() {
1993 for (let piece of Object.keys(pieces)) {
1994 let p = pieces[piece];
1995 if (p.held != us) continue;
1996 redisplay_ancillaries(piece,p);
2000 type PreparedPieceImage = {
2003 uos: UoDescription[],
2007 type TransmitUpdateEntry_Image = {
2009 im: PreparedPieceImage,
2012 messages.Image = <MessageHandler>function(j: TransmitUpdateEntry_Image) {
2013 console.log('IMAGE UPDATE ',j)
2014 var piece = j.piece;
2015 let p = pieces[piece]!;
2016 piece_modify_image(piece, p, j.im);
2017 redisplay_ancillaries(piece,p);
2018 recompute_keybindings();
2019 console.log('IMAGE DONE');
2022 function piece_set_zlevel(piece: PieceId, p: PieceInfo,
2023 modify : (oldtop_piece: PieceId) => void) {
2024 // Calls modify, which should set .z and/or .gz, and/or
2025 // make any necessary API call.
2027 // Then moves uelem to the right place in the DOM. This is done
2028 // by assuming that uelem ought to go at the end, so this is
2029 // O(new depth), which is right (since the UI for inserting
2030 // an object is itself O(new depth) UI operations to prepare.
2032 let oldtop_elem = (defs_marker.previousElementSibling! as
2033 unknown as SVGGraphicsElement);
2034 let oldtop_piece = oldtop_elem.dataset.piece!;
2035 modify(oldtop_piece);
2037 let ins_before = defs_marker
2039 for (; ; ins_before = earlier_elem) {
2040 earlier_elem = (ins_before.previousElementSibling! as
2041 unknown as SVGGraphicsElement);
2042 if (earlier_elem == pieces_marker) break;
2043 if (earlier_elem == p.uelem) continue;
2044 let earlier_p = pieces[earlier_elem.dataset.piece!]!;
2045 if (!piece_z_before(p, earlier_p)) break;
2047 if (ins_before != p.uelem)
2048 space.insertBefore(p.uelem, ins_before);
2053 function check_z_order() {
2054 if (!otter_debug) return;
2055 let s = pieces_marker;
2058 s = s.nextElementSibling as SVGGraphicsElement;
2059 if (s == defs_marker) break;
2060 let piece = s.dataset.piece!;
2061 let z = pieces[piece].z;
2063 json_report_error(['Z ORDER INCONSISTENCY!', piece, z, last_z]);
2069 function piece_note_moved(piece: PieceId, p: PieceInfo) {
2070 let now = performance.now();
2072 let need_redisplay = p.last_seen_moved == null;
2073 p.last_seen_moved = now;
2074 if (need_redisplay) redisplay_ancillaries(piece,p);
2076 let cutoff = now-1000.;
2077 while (movements.length > 0 && movements[0].this_motion < cutoff) {
2078 let mr = movements.shift()!;
2079 if (mr.p.last_seen_moved != null &&
2080 mr.p.last_seen_moved < cutoff) {
2081 mr.p.last_seen_moved = null;
2082 redisplay_ancillaries(mr.piece,mr.p);
2086 movements.push({ piece: piece, p: p, this_motion: now });
2089 function piece_z_cmp(a: PieceInfo, b: PieceInfo) {
2090 if (a.z < b.z ) return -1;
2091 if (a.z > b.z ) return +1;
2092 if (a.zg < b.zg) return -1;
2093 if (a.zg > b.zg) return +1;
2097 function piece_z_before(a: PieceInfo, b: PieceInfo) {
2098 return piece_z_cmp(a,
2102 function pieceid_z_cmp(a: PieceId, b: PieceId) {
2103 return piece_z_cmp(pieces[a]!,
2107 pieceops.Move = <PieceHandler>function
2108 (piece,p, info: Pos ) {
2109 piece_checkconflict_nrda(piece,p);
2110 piece_note_moved(piece, p);
2111 piece_set_pos_core(p, info[0], info[1]);
2114 pieceops.MoveQuiet = <PieceHandler>function
2115 (piece,p, info: Pos ) {
2116 piece_checkconflict_nrda(piece,p);
2117 piece_set_pos_core(p, info[0], info[1]);
2120 pieceops.SetZLevel = <PieceHandler>function
2121 (piece,p, info: { z: ZCoord, zg: Generation }) {
2122 piece_note_moved(piece,p);
2123 piece_set_zlevel_from(piece,p,info);
2126 pieceops.SetZLevelQuiet = <PieceHandler>function
2127 (piece,p, info: { z: ZCoord, zg: Generation }) {
2128 piece_set_zlevel_from(piece,p,info);
2131 function piece_set_zlevel_from(piece: PieceId, p: PieceInfo,
2132 info: { z: ZCoord, zg: Generation }) {
2133 piece_set_zlevel(piece,p, (oldtop_piece)=>{
2139 messages.Recorded = <MessageHandler>function
2140 (j: { piece: PieceId, cseq: ClientSeq,
2141 zg: Generation|null, svg: string | null, desc: string | null } ) {
2142 let piece = j.piece;
2143 let p = pieces[piece]!;
2144 piece_recorded_cseq(p, j);
2145 if (p.cseq_updatesvg != null && j.cseq >= p.cseq_updatesvg) {
2146 p.cseq_updatesvg = null;
2147 redisplay_ancillaries(piece,p);
2149 if (j.svg != null) {
2150 p.delem.innerHTML = j.svg;
2151 p.pelem= piece_element('piece',piece)!;
2152 piece_resolve_special(piece, p);
2153 redisplay_ancillaries(piece,p);
2156 var zg_new = j.zg; // type narrowing doesn't propagate :-/
2157 piece_set_zlevel(piece,p, (oldtop_piece: PieceId)=>{
2161 if (j.desc != null) {
2166 function piece_recorded_cseq(p: PieceInfo, j: { cseq: ClientSeq }) {
2167 if (p.cseq_main != null && j.cseq >= p.cseq_main ) { p.cseq_main = null; }
2168 if (p.cseq_loose != null && j.cseq >= p.cseq_loose) { p.cseq_loose = null; }
2171 messages.RecordedUnpredictable = <MessageHandler>function
2172 (j: { piece: PieceId, cseq: ClientSeq, ns: PreparedPieceState } ) {
2173 let piece = j.piece;
2174 let p = pieces[piece]!;
2175 piece_recorded_cseq(p, j);
2176 piece_modify(piece, p, j.ns);
2179 messages.Error = <MessageHandler>function
2181 console.log('ERROR UPDATE ', m);
2182 var k = Object.keys(m)[0];
2183 update_error_handlers[k](m[k]);
2186 type PieceOpError = {
2189 state: ErrorTransmitUpdateEntry_Piece,
2192 update_error_handlers.PieceOpError = <MessageHandler>function
2194 let piece = m.state.piece;
2195 let cseq = m.state.cseq;
2196 let p = pieces[piece];
2197 console.log('ERROR UPDATE PIECE ', piece, cseq, m, m.error_msg, p);
2198 if (p == null) return; // who can say!
2199 if (m.error != 'Conflict') {
2200 // Our gen was high enough we we sent this, that it ought to have
2201 // worked. Report it as a problem, then.
2202 add_log_message('Problem manipulating piece: ' + m.error_msg);
2203 // Mark aus as having no outstanding requests, and cancel any drag.
2204 piece_checkconflict_nrda(piece, p, true);
2206 handle_piece_update(m.state);
2209 function piece_checkconflict_nrda(piece: PieceId, p: PieceInfo,
2210 already_logged: boolean = false) {
2211 // Our state machine for cseq:
2213 // When we send an update (api_piece_x) we always set cseq. If the
2214 // update is loose we also set cseq_beforeloose. Whenever we
2215 // clear cseq we clear cseq_beforeloose too.
2217 // The result is that if cseq_beforeloose is non-null precisely if
2218 // the last op we sent was loose.
2220 // We track separately the last loose, and the last non-loose,
2221 // outstanding API request. (We discard our idea of the last
2222 // loose request if we follow it with a non-loose one.)
2225 // cseq_main > cseq_loose one loose request then some non-loose
2226 // cseq_main, no cseq_loose just non-loose requests
2227 // no cseq_main, but cseq_loose just one loose request
2228 // neither no outstanding requests
2230 // If our only outstanding update is loose, we ignore a detected
2231 // conflict. We expect the server to send us a proper
2232 // (non-Conflict) error later.
2233 if (p.cseq_main != null || p.cseq_loose != null) {
2234 if (drag_pieces.some(function(dp) { return dp.piece == piece; })) {
2235 console.log('drag end due to conflict');
2239 if (p.cseq_main != null) {
2240 if (!already_logged)
2241 add_log_message('Conflict! - simultaneous update');
2244 p.cseq_loose = null;
2247 function test_swap_stack() {
2248 let old_bot = pieces_marker.nextElementSibling!;
2249 let container = old_bot.parentElement!;
2250 container.insertBefore(old_bot, defs_marker);
2251 window.setTimeout(test_swap_stack, 1000);
2254 function startup() {
2255 console.log('STARTUP');
2256 console.log(wasm_bindgen.setup("OK"));
2258 var body = document.getElementById("main-body")!;
2259 zoom_btn = document.getElementById("zoom-btn") as any;
2260 zoom_val = document.getElementById("zoom-val") as any;
2261 links_elem = document.getElementById("links") as any;
2262 ctoken = body.dataset.ctoken!;
2263 us = body.dataset.us!;
2264 gen = +body.dataset.gen!;
2265 let sse_url_prefix = body.dataset.sseUrlPrefix!;
2266 status_node = document.getElementById('status')!;
2267 status_node.innerHTML = 'js-done';
2268 log_elem = document.getElementById("log")!;
2269 logscroll_elem = document.getElementById("logscroll") || log_elem;
2270 let dataload = JSON.parse(body.dataset.load!);
2271 held_surround_colour = dataload.held_surround_colour!;
2272 players = dataload.players!;
2273 delete body.dataset.load;
2274 uos_node = document.getElementById("uos")!;
2275 occregions = wasm_bindgen.empty_region_list();
2277 space = svg_element('space')!;
2278 pieces_marker = svg_element("pieces_marker")!;
2279 defs_marker = svg_element("defs_marker")!;
2280 movehist_start = svg_element('movehist_marker')!;
2281 movehist_end = svg_element('movehist_end')!;
2282 rectsel_path = svg_element('rectsel_path')!;
2283 svg_ns = space.getAttribute('xmlns')!;
2285 for (let uelem = pieces_marker.nextElementSibling! as SVGGraphicsElement;
2286 uelem != defs_marker;
2287 uelem = uelem.nextElementSibling! as SVGGraphicsElement) {
2288 let piece = uelem.dataset.piece!;
2289 let p = JSON.parse(uelem.dataset.info!);
2291 p.delem = piece_element('defs',piece);
2292 p.pelem = piece_element('piece',piece);
2294 occregion_update(piece, p, p); delete p.occregion;
2295 delete uelem.dataset.info;
2297 piece_resolve_special(piece,p);
2298 redisplay_ancillaries(piece,p);
2301 if (test_update_hook == null) test_update_hook = function() { };
2304 last_log_ts = wasm_bindgen.timestamp_abbreviator(dataload.last_log_ts);
2306 for (let ent of dataload.movehist.hist) {
2307 movehist_record(ent);
2310 var es = new EventSource(
2311 sse_url_prefix + "/_/updates?ctoken="+ctoken+'&gen='+gen
2313 es.onmessage = function(event) {
2314 console.log('GOTEVE', event.data);
2318 var [tgen, ms] = JSON.parse(event.data);
2320 k = Object.keys(m)[0];
2326 var s = exc.toString();
2327 string_report_error('exception handling update '
2328 + k + ': ' + JSON.stringify(m) + ': ' + s);
2331 es.addEventListener('commsworking', function(event) {
2332 console.log('GOTDATA', (event as any).data);
2333 status_node.innerHTML = (event as any).data;
2335 es.addEventListener('player-gone', function(event) {
2336 console.log('PLAYER-GONE', event);
2337 status_node.innerHTML = (event as any).data;
2338 add_log_message('<strong>You are no longer in the game</strong>');
2339 space.removeEventListener('mousedown', some_mousedown);
2340 document.removeEventListener('keydown', some_keydown);
2343 es.addEventListener('updates-expired', function(event) {
2344 console.log('UPDATES-EXPIRED', event);
2345 string_report_error('connection to server interrupted too long');
2347 es.onerror = function(e) {
2350 updates_event_source : es,
2351 updates_event_source_ready : es.readyState,
2352 update_oe : (e as any).className,
2354 if (es.readyState == 2) {
2356 reason: "TOTAL SSE FAILURE",
2360 console.log('SSE error event', info);
2363 recompute_keybindings();
2364 space.addEventListener('mousedown', some_mousedown);
2365 space.addEventListener('dragstart', function (e) {
2367 e.stopPropagation();
2369 document.addEventListener('keydown', some_keydown);
2373 type DieSpecialRendering = SpecialRendering & {
2374 cd_path: SVGPathElement,
2375 loaded_ts: DOMHighResTimeStamp,
2376 loaded_remprop: number,
2379 anim_id: number | null,
2381 special_renderings['Die'] = function(piece: PieceId, p: PieceInfo,
2382 s: DieSpecialRendering) {
2383 let cd_path = document.getElementById('def.'+piece+'.die.cd');
2384 if (!cd_path) return;
2386 s.cd_path = cd_path as any as SVGPathElement;
2387 s.loaded_ts = performance.now();
2388 s.loaded_remprop = parseFloat(cd_path.dataset.remprop!)!;
2389 s.total_ms = parseFloat(cd_path.dataset.total_ms!)!;
2390 s.radius = parseFloat(cd_path.dataset.radius!)!;
2392 s.stop = die_rendering_stop as any;
2393 die_request_animation(piece, p, s);
2395 function die_request_animation(piece: PieceId, p: PieceInfo,
2396 s: DieSpecialRendering) {
2397 s.anim_id = window.requestAnimationFrame(
2398 function(ts) { die_render_frame(piece, p, s, ts) }
2401 function die_render_frame(piece: PieceId, p: PieceInfo,
2402 s: DieSpecialRendering, ts: DOMHighResTimeStamp) {
2404 let remprop = s.loaded_remprop - (ts - s.loaded_ts) / s.total_ms;
2405 //console.log('DIE RENDER', piece, s, remprop);
2407 console.log('DIE COMPLETE', piece, s, remprop);
2408 let to_remove: Element = s.cd_path;
2410 let previous = to_remove.previousElementSibling!;
2411 // see dice/overlya-template-extractor
2412 if (to_remove.tagName == 'text') break;
2414 to_remove = previous;
2417 let path_d = wasm_bindgen.die_cooldown_path(s.radius, remprop);
2418 s.cd_path.setAttributeNS(null, "d", path_d);
2419 die_request_animation(piece, p, s);
2422 function die_rendering_stop(piece: PieceId, p: PieceInfo,
2423 s: DieSpecialRendering) {
2424 let anim_id = s.anim_id;
2425 if (anim_id == null) return;
2427 window.cancelAnimationFrame(anim_id);
2430 declare var wasm_input : any;
2431 var wasm_promise : Promise<any>;;
2434 console.log('DOLOAD');
2435 globalinfo_elem = document.getElementById('global-info')!;
2436 layout = globalinfo_elem!.dataset!.layout! as any;
2437 var elem = document.getElementById('loading_token')!;
2438 var ptoken = elem.dataset.ptoken;
2439 xhr_post_then('/_/session/' + layout,
2440 JSON.stringify({ ptoken : ptoken }),
2443 wasm_promise = wasm_input
2444 .then(wasm_bindgen);
2447 function loaded(xhr: XMLHttpRequest){
2448 console.log('LOADED');
2449 var body = document.getElementById('loading_body')!;
2450 wasm_promise.then((got_wasm) => {
2452 body.outerHTML = xhr.response;
2456 let s = exc.toString();
2457 string_report_error_raw('Exception on load, unrecoverable: ' + s);
2462 // todo scroll of log messages to bottom did not always work somehow
2463 // think I have fixed this with approximation