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 wresting: boolean;
162 var occregions: wasm_bindgen.RegionList;
163 let special_count: number | null;
165 var movehist_gen: number = 0;
166 const MOVEHIST_ENDS = 2.5;
167 const SPECIAL_MULTI_DELTA_EACH = 3;
168 const SPECIAL_MULTI_DELTA_MAX = 18;
170 type PaneName = string;
171 const pane_keys : { [key: string]: PaneName } = {
177 const uo_kind_prec : { [kind: string]: number } = {
189 var players : { [player: string]: PlayerInfo };
191 type MovementRecord = { // for yellow halo, unrelasted to movehist
194 this_motion: DOMHighResTimeStamp,
196 var movements : MovementRecord[] = [];
198 function xhr_post_then(url : string, data: string,
199 good : (xhr: XMLHttpRequest) => void) {
200 var xhr : XMLHttpRequest = new XMLHttpRequest();
201 xhr.onreadystatechange = function(){
202 if (xhr.readyState != XMLHttpRequest.DONE) { return; }
203 if (xhr.status != 200) { xhr_report_error(xhr); }
206 xhr.timeout = general_timeout;
207 xhr.open('POST',url);
208 xhr.setRequestHeader('Content-Type','application/json');
212 function xhr_report_error(xhr: XMLHttpRequest) {
214 statusText : xhr.statusText,
215 responseText : xhr.responseText,
219 function json_report_error(error_for_json: Object) {
220 let error_message = JSON.stringify(error_for_json);
221 string_report_error(error_message);
224 function string_report_error(error_message: String) {
225 string_report_error_raw('Error (reloading may help?): ' + error_message)
227 function string_report_error_raw(error_message: String) {
228 let errornode = document.getElementById('error')!;
229 errornode.textContent += '\n' + error_message;
230 console.error("ERROR reported via log", error_message);
231 // todo want to fix this for at least basic game reconfigs, auto-reload?
234 function api_immediate(meth: string, data: Object) {
235 api_queue.push([meth, data]);
238 function api_delay(meth: string, data: Object) {
239 if (api_queue.length==0) window.setTimeout(api_check, 10);
240 api_queue.push([meth, data]);
242 function api_check() {
243 if (api_posting) { return; }
244 if (!api_queue.length) { test_update_hook(); return; }
246 var [meth, data] = api_queue.shift()!;
247 if (meth != 'm') break;
248 let piece = (data as any).piece;
249 let p = pieces[piece];
250 if (p == null) break;
252 if (p.queued_moves == 0) break;
253 } while (api_queue.length);
255 xhr_post_then('/_/api/'+meth, JSON.stringify(data), api_posted);
257 function api_posted() {
262 function api_piece_x(f: (meth: string, payload: Object) => void,
265 piece: PieceId, p: PieceInfo,
284 function api_piece(meth: string,
285 piece: PieceId, p: PieceInfo,
287 api_piece_x(api_immediate, false,meth, piece, p, op);
290 function svg_element(id: string): SVGGraphicsElement | null {
291 let elem = document.getElementById(id);
292 return elem as unknown as (SVGGraphicsElement | null);
294 function piece_element(base: string, piece: PieceId): SVGGraphicsElement | null
296 return svg_element(base+piece);
299 function piece_moveable(p: PieceInfo) {
300 return p.moveable == 'Yes' || p.moveable == 'IfWresting' && wresting;
303 // ----- key handling -----
305 function recompute_keybindings() {
306 uo_map = Object.create(null);
307 let all_targets = [];
308 for (let piece of Object.keys(pieces)) {
309 let p = pieces[piece];
310 if (p.held != us) continue;
311 all_targets.push(piece);
312 for (var uo of p.uos) {
313 let currently = uo_map[uo.def_key];
314 if (currently === null) continue;
315 if (currently !== undefined) {
316 if (currently.opname != uo.opname) {
317 uo_map[uo.def_key] = null;
325 uo_map[uo.def_key] = currently;
327 currently.desc = currently.desc < uo.desc ? currently.desc : uo.desc;
328 currently.targets!.push(piece);
331 all_targets.sort(pieceid_z_cmp);
332 let add_uo = function(targets: PieceId[] | null, uo: UoDescription) {
333 uo_map[uo.def_key] = {
338 if (all_targets.length) {
339 let got_rotateable = false;
340 for (let t of all_targets) {
341 if (pieces[t]!.rotateable)
342 got_rotateable = true;
344 if (got_rotateable) {
345 add_uo(all_targets, {
352 add_uo(all_targets, {
357 desc: "rotate right",
360 add_uo(all_targets, {
365 desc: "send to bottom (below other pieces)",
367 add_uo(all_targets, {
372 desc: "raise to top",
375 if (all_targets.length) {
377 for (let t of all_targets) {
378 got |= 1 << Number(pieces[t]!.pinned);
381 add_uo(all_targets, {
385 desc: 'Pin to table',
388 } else if (got == 2) {
389 add_uo(all_targets, {
393 desc: 'Unpin from table',
402 desc: wresting ? 'Exit wresting mode' : 'Enter wresting mode',
405 if (special_count != null) {
407 if (special_count == 0) {
408 desc = 'select bottommost';
410 desc = `select ${special_count}`;
412 desc = `cancel <strong style="color:purple">${desc}</strong>`;
414 def_key: 'SPC', // won't match key event; we handle this ad-hoc
416 opname: 'cancel-special',
424 opname: 'motion-hint-history',
425 desc: 'Recent history display',
428 var uo_keys = Object.keys(uo_map);
429 uo_keys.sort(function (ak,bk) {
432 if (a==null || b==null) return (
436 return uo_kind_prec[a.kind] - uo_kind_prec[b.kind]
437 || ak.localeCompare(bk);
440 for (let celem = uos_node.firstElementChild;
443 var nextelem = celem.nextElementSibling;
444 let cid = celem.getAttribute("id");
445 if (cid == "uos-mid") mid_elem = celem;
446 else if (celem.getAttribute("class") == 'uos-mid') { }
449 for (var kk of uo_keys) {
452 let prec = uo_kind_prec[uo.kind];
453 let ent = document.createElement('div');
454 ent.innerHTML = '<b>' + kk + '</b> ' + uo.desc;
456 ent.setAttribute('class','uokey-l');
457 uos_node.insertBefore(ent, mid_elem);
459 ent.setAttribute('class','uokey-r');
460 uos_node.appendChild(ent);
465 function some_keydown(e: KeyboardEvent) {
466 // https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
467 // says to do this, something to do with CJK composition.
468 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
469 // says that keyCode is deprecated
470 // my tsc says this isComposing thing doesn't exist. wat.
471 if ((e as any).isComposing /* || e.keyCode === 229 */) return;
472 if (e.ctrlKey || e.altKey || e.metaKey) return;
474 // someone else is dealing with it ?
475 let tag = (e.target as HTMLElement).tagName;
476 if (tag == 'INPUT') return;
479 let y = function() { e.preventDefault(); e.stopPropagation(); }
481 let pane = pane_keys[e.key];
484 return pane_switch(pane);
487 let special_count_key = parseInt(e.key);
488 if (isFinite(special_count_key)) {
490 if (special_count == null) special_count = 0;
492 special_count += special_count_key;
493 special_count %= 100000;
494 special_count_reupdate();
499 special_count = null;
500 special_count_reupdate();
504 let uo = uo_map[e.key];
505 if (uo === undefined || uo === null) return;
508 console.log('KEY UO', e, uo);
509 if (uo.kind == 'Client' || uo.kind == 'ClientExtra') {
510 let f = keyops_local[uo.opname];
514 if (!(uo.kind == 'Global' || uo.kind == 'GlobalExtra' || uo.kind == 'Piece'))
515 throw 'bad kind '+uo.kind;
517 for (var piece of uo.targets!) {
518 let p = pieces[piece]!;
519 api_piece('k', piece, p, { opname: uo.opname, wrc: uo.wrc });
520 if (uo.wrc == 'UpdateSvg') {
521 // No UpdateSvg is loose, so no need to check p.cseq_loose
522 p.cseq_updatesvg = p.cseq_main;
523 redisplay_ancillaries(piece,p);
528 function pane_switch(newpane: PaneName) {
531 new_e = document.getElementById('pane_' + newpane)!;
532 let style = new_e.getAttribute('style');
533 if (style || newpane == 'help') break;
536 for (let old_e = new_e.parentElement!.firstElementChild;
538 old_e = old_e.nextElementSibling) {
539 old_e.setAttribute('style','display: none;');
541 new_e.removeAttribute('style');
544 function special_count_reupdate() {
545 let style_elem = document.getElementById("space-cursor-style")!;
547 if (special_count == null) {
552 if (special_count != 0) {
553 let path = 'stroke-linecap="square" d="M -10 -10 10 10 M 10 -10 -10 10"';
554 let text_len = special_count.toString().length;
555 let text_x = text_len <= 3 ? 0 : -15;
556 let text_size = text_len <= 3 ? 50 : 45 * (4/text_len);
559 `<svg xmlns="http://www.w3.org/2000/svg"
560 viewBox="-15 0 120 65" width="120" height="65">
561 <g transform="translate(0 50)">
562 <path stroke-width="8" stroke="#fcf" ${path}/>
563 <path stroke-width="4" stroke="purple" ${path}/>
564 <text x="${text_x}" y="0" fill="purple" stroke="#fcf" stroke-width="2"
565 font-family="sans-serif" font-size="${text_size}">${special_count}</text>
568 let path = 'stroke-linecap="square" d="M -10 -10 0 0 10 -10 M 0 0 0 -20"';
571 `<svg xmlns="http://www.w3.org/2000/svg"
572 viewBox="-15 -25 30 30" width="30" height="30">
573 <g transform="translate(0 0)">
574 <path stroke-width="8" stroke="#fcf" ${path}/>
575 <path stroke-width="4" stroke="purple" ${path}/>
578 let svg_data = btoa(svg);
581 cursor: url(data:image/svg+xml;base64,${svg_data}) ${xy}, auto;
584 style_elem.innerHTML = style_text;
585 recompute_keybindings();
588 keyops_local['left' ] = function (uo: UoRecord) { rotate_targets(uo, +1); }
589 keyops_local['right'] = function (uo: UoRecord) { rotate_targets(uo, -1); }
591 function rotate_targets(uo: UoRecord, dangle: number): boolean {
592 for (let piece of uo.targets!) {
593 let p = pieces[piece]!;
594 if (!p.rotateable) continue;
595 p.angle += dangle + 8;
597 let transform = wasm_bindgen.angle_transform(p.angle);
598 p.pelem.setAttributeNS(null,'transform',transform);
599 api_piece('rotate', piece,p, p.angle);
601 recompute_keybindings();
607 type LowerTodoItem = {
613 type LowerTodoList = { [piece: string]: LowerTodoItem };
615 keyops_local['lower'] = function (uo: UoRecord) { lower_targets(uo); }
617 function lower_heavy(p: PieceInfo): boolean {
618 return wresting || p.pinned || p.moveable == "No";
621 function lower_targets(uo: UoRecord): boolean {
622 let targets_todo : LowerTodoList = Object.create(null);
624 for (let piece of uo.targets!) {
625 let p = pieces[piece]!;
626 let heavy = lower_heavy(p);
627 targets_todo[piece] = { p, piece, heavy, };
629 let problem = lower_pieces(targets_todo);
630 if (problem !== null) {
631 add_log_message('Cannot lower: ' + problem);
637 function lower_pieces(targets_todo: LowerTodoList):
640 // This is a bit subtle. We don't want to lower below heavy pieces
641 // (unless we are heavy too, or the user is wresting). But maybe
642 // the heavy pieces aren't already at the bottom. For now we will
643 // declare that all heavy pieces "should" be below all light
644 // ones. Not as an invariant, but as a thing we will do here to try
645 // to make a sensible result. We implement this as follows: if we
646 // find heavy pieces above light pieces, we move those heavy
647 // pieces to the bottom too, just below us, preserving their
650 // Disregarding heavy targets:
652 // Z <some stuff not including any light targets>
654 // topmost light target *
656 // B light non-target
657 // B | light target *
658 // B | heavy non-target, mis-stacked *
661 // bottommost light non-target
662 // if that is below topmost light target
663 // <- tomove_light: insert targets from * here Q ->
664 // <- tomove_misstacked: insert non-targets from * here Q ->
665 // <- heavy non-targets with clashing Z Coords X ->
667 // A heavy non-targets (nomove_heavy)
668 // <- tomove_heavy: insert all heavy targets here P ->
670 // When wresting, treat all targets as heavy.
676 // bottom of the stack order first
677 let tomove_light : Entry[] = [];
678 let tomove_misstacked : Entry[] = [];
679 let nomove_heavy : Entry[] = [];
680 let tomove_heavy : Entry[] = [];
683 let q_z_top : ZCoord | null = null; // null some some
684 let n_targets_todo_light = 0; // 0
686 let any_targets = false;
687 for (const piece of Object.keys(targets_todo)) {
689 let p = targets_todo[piece];
690 if (!p.heavy) n_targets_todo_light++;
692 if (!any_targets) return 'Nothing to lower!';
694 let walk = pieces_marker;
695 for (;;) { // starting at the bottom of the stack order
696 if (Object.keys(targets_todo).length == 0 &&
698 // no targets left, state Z, we can stop now
699 console.log('LOWER STATE Z FINISHED');
703 let new_walk = walk.nextElementSibling;
704 if (new_walk == null) {
705 console.log('LOWER WALK NO SIBLING!');
708 walk = new_walk as SVGGraphicsElement;
709 let piece = walk.dataset.piece;
711 console.log('LOWER WALK REACHED TOP');
715 let p = pieces[piece]!;
716 let todo = targets_todo[piece];
719 if (q_z_top === null && !todo.heavy) {
723 console.log('LOWER WALK', piece, 'TODO', todo.heavy ? "H" : "_", xst);
724 delete targets_todo[piece];
725 if (!todo.heavy) n_targets_todo_light--;
726 (todo.heavy ? tomove_heavy : tomove_light).push(todo);
730 let p_heavy = lower_heavy(p);
731 if (q_z_top === null) { // state A
733 console.log('LOWER WALK', piece, 'STATE A -> Z');
736 console.log('LOWER WALK', piece, 'STATE A');
737 nomove_heavy.push({ p, piece });
744 console.log('LOWER WALK', piece, 'STATE B MIS-STACKED');
745 tomove_misstacked.push({ p, piece });
747 console.log('LOWER WALK', piece, 'STATE B');
751 if (q_z_top === null) {
752 // Somehow we didn't find the top of Q, so we didn't meet any
753 // targets. (In the walk loop, we always set q_z_top if todo.)
755 tomove_misstacked.length ? tomove_misstacked[0].p.z :
756 tomove_light .length ? tomove_light [0].p.z :
757 tomove_heavy [0].p.z;
760 while (nomove_heavy.length &&
761 (tomove_light.length || tomove_misstacked.length) &&
762 nomove_heavy[nomove_heavy.length-1].p.z == q_z_top) {
763 // Yowzer. We have to reset the Z coordinates on these heavy
764 // pieces, whose Z coordinate is the same as the stuff we are not
765 // touching, because otherwise there is no gap.
767 // Treating them as misstacked instead is sufficient, provided
768 // we put them at the front (bottom end) of the misstacked list.
770 // This is X in the chart.
772 let restack = nomove_heavy.pop()!;
773 console.log('LOWER CLASHING Z - RESTACKING', restack);
774 tomove_misstacked.unshift(restack);
778 content: Entry[], // bottom to top
780 z_bot: ZCoord | null,
783 let plan : PlanEntry[] = [];
785 console.log('LOWER PARTQ X', tomove_misstacked);
786 console.log('LOWER PARTQ L', tomove_light);
787 console.log('LOWER PARTP H', tomove_heavy);
788 let partQ = tomove_misstacked.concat(tomove_light);
789 let partP = tomove_heavy;
791 if (nomove_heavy.length == 0) {
793 content: partP.concat(partQ),
801 z_bot: nomove_heavy[nomove_heavy.length-1].p.z,
804 z_top: nomove_heavy[0].p.z,
809 console.log('LOWER PLAN', plan);
811 for (const pe of plan) {
812 for (const e of pe.content) {
813 if (e.p.held != null && e.p.held != us) {
814 return "lowering would disturb a piece held by another player";
819 for (const pe of plan) {
820 let z_top = pe.z_top;
821 let z_bot = pe.z_bot;
822 if (! pe.content.length) continue;
824 let first_z = pe.content[0].p.z;
825 if (z_top >= first_z)
828 let zrange = wasm_bindgen.range(z_bot, z_top, pe.content.length);
829 console.log('LOQER PLAN PE',
830 pe, z_bot, z_top, pe.content.length, zrange.debug());
831 for (const e of pe.content) {
833 p.held_us_raising = "Lowered";
834 piece_set_zlevel(e.piece, p, (oldtop_piece) => {
835 let z = zrange.next();
837 api_piece("setz", e.piece, e.p, { z });
844 keyops_local['wrest'] = function (uo: UoRecord) {
845 wresting = !wresting;
846 document.getElementById('wresting-warning')!.innerHTML = !wresting ? "" :
847 " <strong>(wresting mode!)</strong>";
849 recompute_keybindings();
852 keyops_local['motion-hint-history'] = function (uo: UoRecord) {
854 movehist_len_i %= movehist_lens.length;
855 movehist_revisible();
858 keyops_local['pin' ] = function (uo) {
859 if (!lower_targets(uo)) return;
862 keyops_local['unpin'] = function (uo) {
863 pin_unpin(uo, false);
866 function pin_unpin(uo: UoRecord, newpin: boolean) {
867 for (let piece of uo.targets!) {
868 let p = pieces[piece]!;
870 api_piece('pin', piece,p, newpin);
871 redisplay_ancillaries(piece,p);
873 recompute_keybindings();
876 // ----- raising -----
878 keyops_local['raise'] = function (uo: UoRecord) { raise_targets(uo); }
880 function raise_targets(uo: UoRecord) {
882 for (let piece of uo.targets!) {
883 let p = pieces[piece]!;
884 if (p.pinned || !piece_moveable(p)) continue;
886 piece_raise(piece, p, "NotYet");
889 add_log_message('No pieces could be raised.');
893 function piece_raise(piece: PieceId, p: PieceInfo,
894 new_held_us_raising: HeldUsRaising,
895 implement: (piece: PieceId, p: PieceInfo, z: ZCoord) => void
896 = function(piece: PieceId, p: PieceInfo, z: ZCoord) {
897 api_piece("setz", piece,p, { z: z });
900 p.held_us_raising = new_held_us_raising;
901 piece_set_zlevel(piece,p, (oldtop_piece) => {
902 let oldtop_p = pieces[oldtop_piece]!;
903 let z = wasm_bindgen.increment(oldtop_p.z);
905 implement(piece,p,z);
909 // ----- clicking/dragging pieces -----
917 enum DRAGGING { // bitmask
925 var drag_pieces : DragInfo[] = [];
926 var dragging = DRAGGING.NO;
927 var dcx : number | null;
928 var dcy : number | null;
930 const DRAGTHRESH = 5;
932 let rectsel_start: Pos | null;
933 let rectsel_shifted: boolean | null;
934 const RECTSELTHRESH = 5;
936 function piece_xy(p: PieceInfo): Pos {
937 return [ parseFloat(p.uelem.getAttributeNS(null,"x")!),
938 parseFloat(p.uelem.getAttributeNS(null,"y")!) ];
941 function drag_start_prepare(new_dragging: DRAGGING) {
942 dragging = new_dragging;
944 let spos_map = Object.create(null);
945 for (let piece of Object.keys(pieces)) {
946 let p = pieces[piece]!;
947 if (p.held != us) continue;
948 let spos = piece_xy(p);
949 let sposk = `${spos[0]} ${spos[1]}`;
950 if (spos_map[sposk] === undefined) spos_map[sposk] = [spos, []];
951 spos_map[sposk][1].push([spos, piece,p]);
954 for (let sposk of Object.keys(spos_map)) {
955 let [[dox, doy], ents] = spos_map[sposk];
956 for (let i=0; i<ents.length; i++) {
957 let [p, piece] = ents[i];
958 let delta = (-(ents.length-1)/2 + i) * SPECIAL_MULTI_DELTA_EACH;
959 p.drag_delta = Math.min(Math.max(delta, -SPECIAL_MULTI_DELTA_MAX),
960 +SPECIAL_MULTI_DELTA_MAX);
963 dox: dox + p.drag_delta,
970 function some_mousedown(e : MouseEvent) {
971 console.log('mousedown', e, e.clientX, e.clientY, e.target);
973 if (e.button != 0) { return }
974 if (e.altKey) { return }
975 if (e.metaKey) { return }
979 drag_mousedown(e, e.shiftKey);
983 type MouseFindClicked = null | {
985 held: PlayerId | null,
990 type PieceSet = { [piece: string]: true };
992 function grab_clicked(clicked: PieceId[], loose: boolean,
993 multigrab: number | undefined) {
994 for (let piece of clicked) {
995 let p = pieces[piece]!;
996 set_grab_us(piece,p);
997 if (multigrab === undefined) {
998 api_piece_x(api_immediate, loose,
999 wresting ? 'wrest' : 'grab', piece,p, { });
1001 piece_raise(piece,p, 'Raised', function(piece,p,z) {
1002 api_piece_x(api_immediate, loose, 'multigrab',
1003 piece,p, { n: multigrab, z: z });
1008 function ungrab_clicked(clicked: PieceId[]) {
1009 let todo: [PieceId, PieceInfo][] = [];
1010 for (let tpiece of clicked) {
1011 let tp = pieces[tpiece]!;
1012 todo.push([tpiece, tp]);
1017 function mouse_clicked_one(piece: PieceId, p: PieceInfo): MouseFindClicked {
1019 let pinned = p.pinned;
1020 return { clicked: [piece], held, pinned };
1023 function mouse_find_predicate(
1024 wanted: number | null,
1025 allow_for_deselect: boolean,
1026 note_already: PieceSet | null,
1027 predicate: (p: PieceInfo) => boolean
1028 ): MouseFindClicked {
1029 let clicked: PieceId[];
1030 let held: string | null;
1032 let already_count = 0;
1035 let uelem = defs_marker;
1036 while (wanted == null || (clicked.length + already_count) < wanted) {
1037 let i = clicked.length;
1038 uelem = uelem.previousElementSibling as any;
1039 if (uelem == pieces_marker) {
1040 if (wanted != null) {
1041 add_log_message(`Not enough pieces! Stopped after ${i}.`);
1046 let piece = uelem.dataset.piece!;
1048 function is_already() {
1049 if (note_already != null) {
1051 note_already[piece] = true;
1055 let p = pieces[piece];
1056 if (p.pinned && !wresting) continue;
1057 if (p.held && p.held != us && !wresting) continue;
1058 if (i > 0 && !piece_moveable(p))
1060 if (!predicate(p)) {
1063 if (p.pinned) pinned = true;
1067 if (held == us && !allow_for_deselect) held = null;
1070 // user is going to be deselecting
1072 // skip ones we don't have
1076 } else { // user is going to be selecting
1079 continue; // skip ones we have already
1080 } else if (p.held == null) {
1082 held = p.held; // wrestish
1085 clicked.push(piece);
1087 if (clicked.length == 0) return null;
1088 else return { clicked, held: held!, pinned: pinned! };
1091 function mouse_find_lowest(e: MouseEvent) {
1092 let clickpos = mouseevent_pos(e);
1093 let uelem = pieces_marker;
1095 uelem = uelem.nextElementSibling as any;
1096 if (uelem == defs_marker) break;
1097 let piece = uelem.dataset.piece!;
1098 let p = pieces[piece]!;
1099 if (p_bbox_contains(p, clickpos)) {
1100 return mouse_clicked_one(piece, p);
1106 function mouse_find_clicked(e: MouseEvent,
1107 target: SVGGraphicsElement, piece: PieceId,
1108 count_allow_for_deselect: boolean,
1109 note_already: PieceSet | null,
1112 let p = pieces[piece]!;
1113 if (special_count == null) {
1114 return mouse_clicked_one(piece, p);
1115 } else if (special_count == 0) {
1116 return mouse_find_lowest(e);
1117 } else { // special_count > 0
1118 if (p.multigrab && !wresting) {
1119 let clicked = mouse_clicked_one(piece, p);
1120 if (clicked) clicked.multigrab = special_count;
1123 if (special_count > 99) {
1125 `Refusing to try to select ${special_count} pieces (max is 99)`);
1128 let clickpos = mouseevent_pos(e);
1129 return mouse_find_predicate(
1130 special_count, count_allow_for_deselect, note_already,
1131 function(p) { return p_bbox_contains(p, clickpos); }
1137 function drag_mousedown(e : MouseEvent, shifted: boolean) {
1138 let target = e.target as SVGGraphicsElement; // we check this just now!
1139 let piece: PieceId | undefined = target.dataset.piece;
1142 rectsel_start = mouseevent_pos(e);
1143 rectsel_shifted = shifted;
1144 window.addEventListener('mousemove', rectsel_mousemove, true);
1145 window.addEventListener('mouseup', rectsel_mouseup, true);
1149 let note_already = shifted ? null : Object.create(null);
1151 let c = mouse_find_clicked(e, target, piece, false, note_already);
1152 if (c == null) return;
1153 let clicked = c.clicked;
1155 let pinned = c.pinned;
1156 let multigrab = c.multigrab;
1158 special_count = null;
1159 special_count_reupdate();
1165 ungrab_clicked(clicked);
1168 drag_start_prepare(DRAGGING.MAYBE_UNGRAB);
1169 } else if (held == null || wresting) {
1171 ungrab_all_except(note_already);
1173 if (pinned && !wresting) {
1174 let p = pieces[c.clicked[0]!]!;
1175 add_log_message('That piece ('+p.desc+') is pinned to the table.');
1178 grab_clicked(clicked, !wresting, multigrab);
1179 drag_start_prepare(DRAGGING.MAYBE_GRAB);
1181 add_log_message('That piece is held by another player.');
1187 window.addEventListener('mousemove', drag_mousemove, true);
1188 window.addEventListener('mouseup', drag_mouseup, true);
1191 function mouseevent_pos(e: MouseEvent): Pos {
1192 let ctm = space.getScreenCTM()!;
1193 let px = (e.clientX - ctm.e)/(ctm.a * firefox_bug_zoom_factor_compensation);
1194 let py = (e.clientY - ctm.f)/(ctm.d * firefox_bug_zoom_factor_compensation);
1195 let pos: Pos = [px, py];
1196 console.log('mouseevent_pos', pos);
1200 function p_bbox_contains(p: PieceInfo, test: Pos) {
1201 let ctr = piece_xy(p);
1202 for (let i of [0,1]) {
1203 let offset = test[i] - ctr[i];
1204 if (offset < p.bbox[0][i] || offset > p.bbox[1][i])
1210 function do_ungrab_n(todo: [PieceId, PieceInfo][]) {
1211 function sort_with(a: [PieceId, PieceInfo],
1212 b: [PieceId, PieceInfo]): number {
1213 return piece_z_cmp(a[1], b[1]);
1215 todo.sort(sort_with);
1216 for (let [tpiece, tp] of todo) {
1217 do_ungrab_1(tpiece, tp);
1220 function ungrab_all_except(dont: PieceSet | null) {
1221 let todo: [PieceId, PieceInfo][] = [];
1222 for (let tpiece of Object.keys(pieces)) {
1223 if (dont && dont[tpiece]) continue;
1224 let tp = pieces[tpiece]!;
1225 if (tp.held == us) {
1226 todo.push([tpiece, tp]);
1231 function ungrab_all() {
1232 ungrab_all_except(null);
1235 function set_grab_us(piece: PieceId, p: PieceInfo) {
1237 p.held_us_raising = "NotYet";
1239 redisplay_ancillaries(piece,p);
1240 recompute_keybindings();
1242 function do_ungrab_1(piece: PieceId, p: PieceInfo) {
1243 let autoraise = p.held_us_raising == "Raised";
1245 p.held_us_raising = "NotYet";
1247 redisplay_ancillaries(piece,p);
1248 recompute_keybindings();
1249 api_piece('ungrab', piece,p, { autoraise });
1252 function clear_halo(piece: PieceId, p: PieceInfo) {
1253 let was = p.last_seen_moved;
1254 p.last_seen_moved = null;
1255 if (was) redisplay_ancillaries(piece,p);
1258 function ancillary_node(piece: PieceId, stroke: string): SVGGraphicsElement {
1259 var nelem = document.createElementNS(svg_ns,'use');
1260 nelem.setAttributeNS(null,'href','#surround'+piece);
1261 nelem.setAttributeNS(null,'stroke',stroke);
1262 nelem.setAttributeNS(null,'fill','none');
1263 return nelem as any;
1266 function redisplay_ancillaries(piece: PieceId, p: PieceInfo) {
1267 let href = '#surround'+piece;
1268 console.log('REDISPLAY ANCILLARIES',href);
1270 for (let celem = p.pelem.firstElementChild;
1273 var nextelem = celem.nextElementSibling
1274 let thref = celem.getAttributeNS(null,"href");
1275 if (thref == href) {
1280 let halo_colour = null;
1281 if (p.cseq_updatesvg != null) {
1282 halo_colour = 'purple';
1283 } else if (p.last_seen_moved != null) {
1284 halo_colour = 'yellow';
1285 } else if (p.held != null && p.pinned) {
1286 halo_colour = '#8cf';
1288 if (halo_colour != null) {
1289 let nelem = ancillary_node(piece, halo_colour);
1290 if (p.held != null) {
1291 // value 2ps is also in src/pieces.rs SELECT_STROKE_WIDTH
1292 nelem.setAttributeNS(null,'stroke-width','2px');
1294 p.pelem.prepend(nelem);
1296 if (p.held != null) {
1299 da = players[p.held!]!.dasharray;
1301 let [px, py] = piece_xy(p);
1302 let inoccult = occregions.contains_pos(px, py);
1303 p.held_us_inoccult = inoccult;
1305 da = "0.9 0.6"; // dotted dasharray
1308 let nelem = ancillary_node(piece, held_surround_colour);
1310 nelem.setAttributeNS(null,'stroke-dasharray',da);
1312 p.pelem.appendChild(nelem);
1316 function drag_mousemove(e: MouseEvent) {
1317 var ctm = space.getScreenCTM()!;
1318 var ddx = (e.clientX - dcx!)/(ctm.a * firefox_bug_zoom_factor_compensation);
1319 var ddy = (e.clientY - dcy!)/(ctm.d * firefox_bug_zoom_factor_compensation);
1320 var ddr2 = ddx*ddx + ddy*ddy;
1321 if (!(dragging & DRAGGING.YES)) {
1322 if (ddr2 > DRAGTHRESH) {
1323 for (let dp of drag_pieces) {
1324 let tpiece = dp.piece;
1325 let tp = pieces[tpiece]!;
1326 if (tp.moveable == "Yes") {
1328 } else if (tp.moveable == "IfWresting") {
1329 if (wresting) continue;
1330 add_log_message('That piece can only be moved when Wresting.');
1332 add_log_message('That piece cannot be moved at the moment.');
1336 dragging |= DRAGGING.YES;
1339 //console.log('mousemove', ddx, ddy, dragging);
1340 if (dragging & DRAGGING.YES) {
1341 console.log('DRAG PIECES',drag_pieces);
1342 for (let dp of drag_pieces) {
1343 console.log('DRAG PIECES PIECE',dp);
1344 let tpiece = dp.piece;
1345 let tp = pieces[tpiece]!;
1346 var x = Math.round(dp.dox + ddx);
1347 var y = Math.round(dp.doy + ddy);
1348 let need_redisplay_ancillaries = (
1350 occregions.contains_pos(x,y) != tp.held_us_inoccult
1352 piece_set_pos_core(tp, x, y);
1354 api_piece_x(api_delay, false, 'm', tpiece,tp, [x, y] );
1355 if (need_redisplay_ancillaries) redisplay_ancillaries(tpiece, tp);
1357 if (!(dragging & DRAGGING.RAISED)) {
1359 for (let dp of drag_pieces) {
1360 let piece = dp.piece;
1361 let p = pieces[piece]!;
1362 if (p.held_us_raising == "Lowered") continue;
1363 let dragraise = +p.pelem.dataset.dragraise!;
1364 if (dragraise > 0 && ddr2 >= dragraise*dragraise) {
1365 dragging |= DRAGGING.RAISED;
1366 console.log('CHECK RAISE ', dragraise, dragraise*dragraise, ddr2);
1367 piece_raise(piece,p,"Raised");
1374 function sort_drag_pieces() {
1375 function sort_with(a: DragInfo, b: DragInfo): number {
1376 return pieceid_z_cmp(a.piece,
1379 drag_pieces.sort(sort_with);
1382 function drag_mouseup(e: MouseEvent) {
1383 console.log('mouseup', dragging);
1384 let ddr2 : number = drag_mousemove(e);
1388 function drag_end() {
1389 if (dragging == DRAGGING.MAYBE_UNGRAB ||
1390 (dragging & ~DRAGGING.RAISED) == (DRAGGING.MAYBE_GRAB | DRAGGING.YES)) {
1392 for (let dp of drag_pieces) {
1393 let piece = dp.piece;
1394 let p = pieces[piece]!;
1395 do_ungrab_1(piece,p);
1401 function drag_cancel() {
1402 window.removeEventListener('mousemove', drag_mousemove, true);
1403 window.removeEventListener('mouseup', drag_mouseup, true);
1404 dragging = DRAGGING.NO;
1408 function rectsel_nontrivial_pos2(e: MouseEvent): Pos | null {
1409 let pos2 = mouseevent_pos(e);
1411 for (let i of [0,1]) {
1412 let d = pos2[i] - rectsel_start![i];
1415 return d2 > RECTSELTHRESH*RECTSELTHRESH ? pos2 : null;
1418 function rectsel_mousemove(e: MouseEvent) {
1419 let pos2 = rectsel_nontrivial_pos2(e);
1424 let pos1 = rectsel_start!;
1425 path = `M ${ pos1 [0]} ${ pos1 [1] }
1426 ${ pos2 [0]} ${ pos1 [1] }
1427 M ${ pos1 [0]} ${ pos2 [1] }
1428 ${ pos2 [0]} ${ pos2 [1] }
1429 M ${ pos1 [0]} ${ pos1 [1] }
1430 ${ pos1 [0]} ${ pos2 [1] }
1431 M ${ pos2 [0]} ${ pos1 [1] }
1432 ${ pos2 [0]} ${ pos2 [1] }`;
1434 rectsel_path.firstElementChild!.setAttributeNS(null,'d',path);
1437 function rectsel_mouseup(e: MouseEvent) {
1438 console.log('rectsel mouseup');
1439 window.removeEventListener('mousemove', rectsel_mousemove, true);
1440 window.removeEventListener('mouseup', rectsel_mouseup, true);
1441 rectsel_path.firstElementChild!.setAttributeNS(null,'d','');
1442 let pos2 = rectsel_nontrivial_pos2(e);
1445 // clicked not on a piece, and didn't drag
1446 special_count = null;
1447 special_count_reupdate();
1448 // we'll bail in a moment, after possibly unselecting things
1451 let note_already = Object.create(null);
1455 if (special_count != null && special_count == 0) {
1456 add_log_message(`Cannot drag-select lowest.`);
1461 for (let i of [0,1]) {
1462 tl[i] = Math.min(rectsel_start![i], pos2[i]);
1463 br[i] = Math.max(rectsel_start![i], pos2[i]);
1465 c = mouse_find_predicate(
1466 special_count, rectsel_shifted!, note_already,
1467 function(p: PieceInfo) {
1468 let pp = piece_xy(p);
1469 for (let i of [0,1]) {
1470 if (pp[i] < tl[i] || pp[i] > br[i]) return false;
1478 // clicked not on a piece, didn't end up selecting anything
1479 // either because drag region had nothing in it, or special
1480 // failed, or some such.
1481 if (!rectsel_shifted) {
1483 while (mr = movements.pop()) {
1484 mr.p.last_seen_moved = null;
1485 redisplay_ancillaries(mr.piece, mr.p);
1493 special_count = null;
1494 special_count_reupdate();
1496 if (rectsel_shifted && c.held == us) {
1497 ungrab_clicked(c.clicked);
1500 if (!rectsel_shifted) {
1501 ungrab_all_except(note_already);
1503 grab_clicked(c.clicked, false, undefined);
1507 // ----- general -----
1509 type PlayersUpdate = { new_info_pane: string };
1511 messages.SetPlayer = <MessageHandler>function
1512 (j: { player: string, data: PlayerInfo } & PlayersUpdate) {
1513 players[j.player] = j.data;
1514 player_info_pane_set(j);
1517 messages.RemovePlayer = <MessageHandler>function
1518 (j: { player: string } & PlayersUpdate ) {
1519 delete players[j.player];
1520 player_info_pane_set(j);
1523 function player_info_pane_set(j: PlayersUpdate) {
1524 document.getElementById('player_list')!
1525 .innerHTML = j.new_info_pane;
1528 messages.UpdateBundles = <MessageHandler>function
1529 (j: { new_info_pane: string }) {
1530 document.getElementById('bundle_list')!
1531 .innerHTML = j.new_info_pane;
1534 messages.SetTableSize = <MessageHandler>function
1535 ([x, y]: [number, number]) {
1536 function set_attrs(elem: Element, l: [string,string][]) {
1538 elem.setAttributeNS(null,a[0],a[1]);
1541 let rect = document.getElementById('table_rect')!;
1542 set_attrs(space, wasm_bindgen.space_table_attrs(x, y));
1543 set_attrs(rect, wasm_bindgen.space_table_attrs(x, y));
1546 messages.SetTableColour = <MessageHandler>function
1548 let rect = document.getElementById('table_rect')!;
1549 rect.setAttributeNS(null, 'fill', c);
1552 messages.SetLinks = <MessageHandler>function
1554 if (msg.length != 0 && layout == 'Portrait') {
1557 links_elem.innerHTML = msg
1560 // ---------- movehist ----------
1562 type MoveHistEnt = {
1564 posx: [MoveHistPosx, MoveHistPosx],
1565 diff: { 'Moved': { d: number } },
1567 type MoveHistPosx = {
1569 angle: CompassAngle,
1570 facehint: FaceId | null,
1573 messages.MoveHistEnt = <MessageHandler>movehist_record;
1574 messages.MoveHistClear = <MessageHandler>function() {
1575 movehist_revisible_custmax(0);
1578 function movehist_record(ent: MoveHistEnt) {
1579 let old_pos = ent.posx[0].pos;
1580 let new_pos = ent.posx[1].pos;
1583 movehist_gen %= (movehist_len_max * 2);
1584 let meid = 'motionhint-marker-' + movehist_gen;
1586 let moved = ent.diff['Moved'];
1590 for (let end of [0,1]) {
1591 let s = (!end ? MOVEHIST_ENDS : d - MOVEHIST_ENDS) / d;
1592 ends.push([ (1-s) * old_pos[0] + s * new_pos[0],
1593 (1-s) * old_pos[1] + s * new_pos[1] ]);
1595 let g = document.createElementNS(svg_ns,'g');
1597 let pi = players[ent.held];
1598 let nick = pi ? pi.nick : '';
1599 // todo: would be nice to place text variously along arrow, rotated
1601 <marker id="${meid}" viewBox="2 0 ${sz} ${sz}"
1602 refX="${sz}" refY="${sz/2}"
1603 markerWidth="${sz + 2}" markerHeight="${sz}"
1604 stroke="yellow" fill="none"
1605 orient="auto-start-reverse" stroke-linejoin="miter">
1606 <path d="M 0 0 L ${sz} ${sz/2} L 0 ${sz}" />
1608 <line x1="${ends[0][0].toString()}"
1609 y1="${ends[0][1].toString()}"
1610 x2="${ends[1][0].toString()}"
1611 y2="${ends[1][1].toString()}"
1613 stroke-width="1" pointer-events="none"
1614 marker-end="url(#${meid})" />
1615 <text x="${((ends[0][0] + ends[1][0]) / 2).toString()}"
1616 y="${((ends[0][1] + ends[1][1]) / 2).toString()}"
1617 font-size="5" pointer-events="none"
1618 stroke-width="0.1">${nick}</text>
1621 space.insertBefore(g, movehist_end);
1622 movehist_revisible();
1626 function movehist_revisible() {
1627 movehist_revisible_custmax(movehist_len_max);
1630 function movehist_revisible_custmax(len_max: number) {
1631 let n = movehist_lens[movehist_len_i];
1633 let node = movehist_end;
1634 while (i < len_max) {
1635 i++; // i now eg 1..10
1636 node = node.previousElementSibling! as SVGGraphicsElement;
1637 if (node == movehist_start)
1639 let prop = i > n ? 0 : (n-i+1)/n;
1640 let stroke = (prop * 1.0).toString();
1641 let marker = node.firstElementChild!;
1642 marker.setAttributeNS(null,'stroke-width',stroke);
1643 let line = marker.nextElementSibling!;
1644 line.setAttributeNS(null,'stroke-width',stroke);
1645 let text = line.nextElementSibling!;
1647 text.setAttributeNS(null,'stroke','none');
1648 text.setAttributeNS(null,'fill','none');
1650 text.setAttributeNS(null,'fill','yellow');
1651 text.setAttributeNS(null,'stroke','orange');
1655 let del = node.previousElementSibling!;
1656 if (del == movehist_start)
1664 messages.Log = <MessageHandler>function
1665 (j: { when: string, logent: { html: string } }) {
1666 add_timestamped_log_message(j.when, j.logent.html);
1669 function add_log_message(msg_html: string) {
1670 add_timestamped_log_message('', msg_html);
1673 function add_timestamped_log_message(ts_html: string, msg_html: string) {
1674 var lastent = log_elem.lastElementChild;
1678 // https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling/21627295#21627295
1680 // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
1682 let le_top = lastent.getBoundingClientRect()!.top;
1683 let le_bot = lastent.getBoundingClientRect()!.bottom;
1684 let ld_bot = logscroll_elem.getBoundingClientRect()!.bottom;
1685 console.log("ADD_LOG_MESSAGE bboxes: le t b, bb",
1686 le_top, le_bot, ld_bot);
1687 return 0.5 * (le_bot + le_top) > ld_bot;
1690 console.log('ADD LOG MESSAGE ',in_scrollback, layout, msg_html);
1692 var ne : HTMLElement;
1694 function add_thing(elemname: string, cl: string, html: string) {
1695 var ie = document.createElement(elemname);
1696 ie.innerHTML = html;
1697 ie.setAttribute("class", cl);
1701 if (layout == 'Portrait') {
1702 ne = document.createElement('tr');
1703 add_thing('td', 'logmsg', msg_html);
1704 add_thing('td', 'logts', ts_html);
1705 } else if (layout == 'Landscape') {
1706 ts_html = last_log_ts.update(ts_html);
1707 ne = document.createElement('div');
1708 add_thing('span', 'logts', ts_html);
1709 ne.appendChild(document.createElement('br'));
1710 add_thing('span', 'logmsg', msg_html);
1711 ne.appendChild(document.createElement('br'));
1713 throw 'bad layout ' + layout;
1715 log_elem.appendChild(ne);
1717 if (!in_scrollback) {
1718 logscroll_elem.scrollTop = logscroll_elem.scrollHeight;
1724 function zoom_pct (): number | undefined {
1725 let str = zoom_val.value;
1726 let val = parseFloat(str);
1734 function zoom_enable() {
1735 zoom_btn.disabled = (zoom_pct() === undefined);
1738 function zoom_activate() {
1739 let pct = zoom_pct();
1740 if (pct !== undefined) {
1741 let fact = pct * 0.01;
1742 let last_ctm_a = space.getScreenCTM()!.a;
1743 (document.getElementsByTagName('body')[0] as HTMLElement)
1744 .style.transform = 'scale('+fact+','+fact+')';
1745 if (fact != last_zoom_factor) {
1746 if (last_ctm_a == space.getScreenCTM()!.a) {
1747 console.log('FIREFOX GETSCREENCTM BUG');
1748 firefox_bug_zoom_factor_compensation = fact;
1750 console.log('No firefox getscreenctm bug');
1751 firefox_bug_zoom_factor_compensation = 1.0;
1753 last_zoom_factor = fact;
1756 zoom_btn.disabled = true;
1759 // ----- test counter, startup -----
1761 type TransmitUpdateEntry_Piece = {
1765 type ErrorTransmitUpdateEntry_Piece = TransmitUpdateEntry_Piece & {
1766 cseq: ClientSeq | null,
1769 function handle_piece_update(j: TransmitUpdateEntry_Piece) {
1770 console.log('PIECE UPDATE ',j)
1771 var piece = j.piece;
1772 var m = j.op as { [k: string]: Object };
1773 var k = Object.keys(m)[0];
1774 let p = pieces[piece];
1775 pieceops[k](piece,p, m[k]);
1778 messages.Piece = <MessageHandler>handle_piece_update;
1780 type PreparedPieceState = {
1784 held: PlayerId | null,
1789 uos: UoDescription[],
1790 moveable: PieceMoveable,
1791 rotateable: boolean,
1793 occregion: string | null,
1797 pieceops.ModifyQuiet = <PieceHandler>function
1798 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1799 console.log('PIECE UPDATE MODIFY QUIET ',piece,info)
1800 piece_modify(piece, p, info);
1803 pieceops.Modify = <PieceHandler>function
1804 (piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1805 console.log('PIECE UPDATE MODIFY LOuD ',piece,info)
1806 piece_note_moved(piece,p);
1807 piece_modify(piece, p, info);
1810 pieceops.InsertQuiet = <PieceHandler>(insert_piece as any);
1811 pieceops.Insert = <PieceHandler>function
1812 (piece: PieceId, xp: any, info: PreparedPieceState) {
1813 let p = insert_piece(piece,xp,info);
1814 piece_note_moved(piece,p);
1817 function insert_piece(piece: PieceId, xp: any,
1818 info: PreparedPieceState): PieceInfo
1820 console.log('PIECE UPDATE INSERT ',piece,info)
1821 let delem = document.createElementNS(svg_ns,'defs');
1822 delem.setAttributeNS(null,'id','defs'+piece);
1823 delem.innerHTML = info.svg;
1824 defs_marker.insertAdjacentElement('afterend', delem);
1825 let pelem = piece_element('piece',piece);
1826 let uelem = document.createElementNS(svg_ns,'use');
1827 uelem.setAttributeNS(null,'id',"use"+piece);
1828 uelem.setAttributeNS(null,'href',"#piece"+piece);
1829 uelem.setAttributeNS(null,'data-piece',piece);
1834 } as any as PieceInfo; // fudge this, piece_modify_core will fix it
1838 piece_resolve_special(piece, p);
1839 piece_modify_core(piece, p, info);
1843 pieceops.Delete = <PieceHandler>function
1844 (piece: PieceId, p: PieceInfo, info: {}) {
1845 console.log('PIECE UPDATE DELETE ', piece)
1846 piece_stop_special(piece, p);
1849 delete pieces[piece];
1851 recompute_keybindings();
1855 piece_error_handlers.PosOffTable = <PieceErrorHandler>function()
1857 piece_error_handlers.Conflict = <PieceErrorHandler>function()
1860 function piece_modify_image(piece: PieceId, p: PieceInfo,
1861 info: PreparedPieceImage) {
1862 p.delem.innerHTML = info.svg;
1863 p.pelem= piece_element('piece',piece)!;
1867 piece_resolve_special(piece, p);
1870 function piece_resolve_special(piece: PieceId, p: PieceInfo) {
1872 p.pelem.dataset.special ?
1873 JSON.parse(p.pelem.dataset.special) : null;
1874 let new_special_kind = new_special ? new_special.kind : '';
1875 let old_special_kind = p .special ? p .special.kind : '';
1877 if (new_special_kind != old_special_kind) {
1878 piece_stop_special(piece, p);
1881 console.log('SPECIAL START', new_special);
1882 new_special.stop = function() { };
1883 p.special = new_special;
1884 special_renderings[new_special_kind](piece, p, new_special);
1888 function piece_stop_special(piece: PieceId, p: PieceInfo) {
1892 console.log('SPECIAL STOP', s);
1893 s.stop(piece, p, s);
1897 function piece_modify(piece: PieceId, p: PieceInfo, info: PreparedPieceState) {
1898 piece_modify_image(piece, p, info);
1899 piece_modify_core(piece, p, info);
1902 function piece_set_pos_core(p: PieceInfo, x: number, y: number) {
1903 p.uelem.setAttributeNS(null, "x", x+"");
1904 p.uelem.setAttributeNS(null, "y", y+"");
1907 function piece_modify_core(piece: PieceId, p: PieceInfo,
1908 info: PreparedPieceState) {
1909 p.uelem.setAttributeNS(null, "x", info.pos[0]+"");
1910 p.uelem.setAttributeNS(null, "y", info.pos[1]+"");
1912 p.held_us_raising = "NotYet";
1913 p.pinned = info.pinned;
1914 p.moveable = info.moveable;
1915 p.rotateable = info.rotateable;
1916 p.multigrab = info.multigrab;
1917 p.angle = info.angle;
1919 piece_set_zlevel_from(piece,p,info);
1920 let occregions_changed = occregion_update(piece, p, info);
1921 piece_checkconflict_nrda(piece,p);
1922 redisplay_ancillaries(piece,p);
1923 if (occregions_changed) redisplay_held_ancillaries();
1924 recompute_keybindings();
1925 console.log('MODIFY DONE');
1927 function occregion_update(piece: PieceId, p: PieceInfo,
1928 info: PreparedPieceState) {
1929 let occregions_changed = (
1930 info.occregion != null
1931 ? occregions.insert(piece, info.occregion)
1932 : occregions.remove(piece)
1934 return occregions_changed;
1936 function redisplay_held_ancillaries() {
1937 for (let piece of Object.keys(pieces)) {
1938 let p = pieces[piece];
1939 if (p.held != us) continue;
1940 redisplay_ancillaries(piece,p);
1944 type PreparedPieceImage = {
1947 uos: UoDescription[],
1951 type TransmitUpdateEntry_Image = {
1953 im: PreparedPieceImage,
1956 messages.Image = <MessageHandler>function(j: TransmitUpdateEntry_Image) {
1957 console.log('IMAGE UPDATE ',j)
1958 var piece = j.piece;
1959 let p = pieces[piece]!;
1960 piece_modify_image(piece, p, j.im);
1961 redisplay_ancillaries(piece,p);
1962 recompute_keybindings();
1963 console.log('IMAGE DONE');
1966 function piece_set_zlevel(piece: PieceId, p: PieceInfo,
1967 modify : (oldtop_piece: PieceId) => void) {
1968 // Calls modify, which should set .z and/or .gz, and/or
1969 // make any necessary API call.
1971 // Then moves uelem to the right place in the DOM. This is done
1972 // by assuming that uelem ought to go at the end, so this is
1973 // O(new depth), which is right (since the UI for inserting
1974 // an object is itself O(new depth) UI operations to prepare.
1976 let oldtop_elem = (defs_marker.previousElementSibling! as
1977 unknown as SVGGraphicsElement);
1978 let oldtop_piece = oldtop_elem.dataset.piece!;
1979 modify(oldtop_piece);
1981 let ins_before = defs_marker
1983 for (; ; ins_before = earlier_elem) {
1984 earlier_elem = (ins_before.previousElementSibling! as
1985 unknown as SVGGraphicsElement);
1986 if (earlier_elem == pieces_marker) break;
1987 if (earlier_elem == p.uelem) continue;
1988 let earlier_p = pieces[earlier_elem.dataset.piece!]!;
1989 if (!piece_z_before(p, earlier_p)) break;
1991 if (ins_before != p.uelem)
1992 space.insertBefore(p.uelem, ins_before);
1997 function check_z_order() {
1998 if (!otter_debug) return;
1999 let s = pieces_marker;
2002 s = s.nextElementSibling as SVGGraphicsElement;
2003 if (s == defs_marker) break;
2004 let piece = s.dataset.piece!;
2005 let z = pieces[piece].z;
2007 json_report_error(['Z ORDER INCONSISTENCY!', piece, z, last_z]);
2013 function piece_note_moved(piece: PieceId, p: PieceInfo) {
2014 let now = performance.now();
2016 let need_redisplay = p.last_seen_moved == null;
2017 p.last_seen_moved = now;
2018 if (need_redisplay) redisplay_ancillaries(piece,p);
2020 let cutoff = now-1000.;
2021 while (movements.length > 0 && movements[0].this_motion < cutoff) {
2022 let mr = movements.shift()!;
2023 if (mr.p.last_seen_moved != null &&
2024 mr.p.last_seen_moved < cutoff) {
2025 mr.p.last_seen_moved = null;
2026 redisplay_ancillaries(mr.piece,mr.p);
2030 movements.push({ piece: piece, p: p, this_motion: now });
2033 function piece_z_cmp(a: PieceInfo, b: PieceInfo) {
2034 if (a.z < b.z ) return -1;
2035 if (a.z > b.z ) return +1;
2036 if (a.zg < b.zg) return -1;
2037 if (a.zg > b.zg) return +1;
2041 function piece_z_before(a: PieceInfo, b: PieceInfo) {
2042 return piece_z_cmp(a,
2046 function pieceid_z_cmp(a: PieceId, b: PieceId) {
2047 return piece_z_cmp(pieces[a]!,
2051 pieceops.Move = <PieceHandler>function
2052 (piece,p, info: Pos ) {
2053 piece_checkconflict_nrda(piece,p);
2054 piece_note_moved(piece, p);
2055 piece_set_pos_core(p, info[0], info[1]);
2058 pieceops.MoveQuiet = <PieceHandler>function
2059 (piece,p, info: Pos ) {
2060 piece_checkconflict_nrda(piece,p);
2061 piece_set_pos_core(p, info[0], info[1]);
2064 pieceops.SetZLevel = <PieceHandler>function
2065 (piece,p, info: { z: ZCoord, zg: Generation }) {
2066 piece_note_moved(piece,p);
2067 piece_set_zlevel_from(piece,p,info);
2070 pieceops.SetZLevelQuiet = <PieceHandler>function
2071 (piece,p, info: { z: ZCoord, zg: Generation }) {
2072 piece_set_zlevel_from(piece,p,info);
2075 function piece_set_zlevel_from(piece: PieceId, p: PieceInfo,
2076 info: { z: ZCoord, zg: Generation }) {
2077 piece_set_zlevel(piece,p, (oldtop_piece)=>{
2083 messages.Recorded = <MessageHandler>function
2084 (j: { piece: PieceId, cseq: ClientSeq,
2085 zg: Generation|null, svg: string | null, desc: string | null } ) {
2086 let piece = j.piece;
2087 let p = pieces[piece]!;
2088 piece_recorded_cseq(p, j);
2089 if (p.cseq_updatesvg != null && j.cseq >= p.cseq_updatesvg) {
2090 p.cseq_updatesvg = null;
2091 redisplay_ancillaries(piece,p);
2093 if (j.svg != null) {
2094 p.delem.innerHTML = j.svg;
2095 p.pelem= piece_element('piece',piece)!;
2096 piece_resolve_special(piece, p);
2097 redisplay_ancillaries(piece,p);
2100 var zg_new = j.zg; // type narrowing doesn't propagate :-/
2101 piece_set_zlevel(piece,p, (oldtop_piece: PieceId)=>{
2105 if (j.desc != null) {
2110 function piece_recorded_cseq(p: PieceInfo, j: { cseq: ClientSeq }) {
2111 if (p.cseq_main != null && j.cseq >= p.cseq_main ) { p.cseq_main = null; }
2112 if (p.cseq_loose != null && j.cseq >= p.cseq_loose) { p.cseq_loose = null; }
2115 messages.RecordedUnpredictable = <MessageHandler>function
2116 (j: { piece: PieceId, cseq: ClientSeq, ns: PreparedPieceState } ) {
2117 let piece = j.piece;
2118 let p = pieces[piece]!;
2119 piece_recorded_cseq(p, j);
2120 piece_modify(piece, p, j.ns);
2123 messages.Error = <MessageHandler>function
2125 console.log('ERROR UPDATE ', m);
2126 var k = Object.keys(m)[0];
2127 update_error_handlers[k](m[k]);
2130 type PieceOpError = {
2133 state: ErrorTransmitUpdateEntry_Piece,
2136 update_error_handlers.PieceOpError = <MessageHandler>function
2138 let piece = m.state.piece;
2139 let cseq = m.state.cseq;
2140 let p = pieces[piece];
2141 console.log('ERROR UPDATE PIECE ', piece, cseq, m, m.error_msg, p);
2142 if (p == null) return; // who can say!
2143 if (m.error != 'Conflict') {
2144 // Our gen was high enough we we sent this, that it ought to have
2145 // worked. Report it as a problem, then.
2146 add_log_message('Problem manipulating piece: ' + m.error_msg);
2147 // Mark aus as having no outstanding requests, and cancel any drag.
2148 piece_checkconflict_nrda(piece, p, true);
2150 handle_piece_update(m.state);
2153 function piece_checkconflict_nrda(piece: PieceId, p: PieceInfo,
2154 already_logged: boolean = false) {
2155 // Our state machine for cseq:
2157 // When we send an update (api_piece_x) we always set cseq. If the
2158 // update is loose we also set cseq_beforeloose. Whenever we
2159 // clear cseq we clear cseq_beforeloose too.
2161 // The result is that if cseq_beforeloose is non-null precisely if
2162 // the last op we sent was loose.
2164 // We track separately the last loose, and the last non-loose,
2165 // outstanding API request. (We discard our idea of the last
2166 // loose request if we follow it with a non-loose one.)
2169 // cseq_main > cseq_loose one loose request then some non-loose
2170 // cseq_main, no cseq_loose just non-loose requests
2171 // no cseq_main, but cseq_loose just one loose request
2172 // neither no outstanding requests
2174 // If our only outstanding update is loose, we ignore a detected
2175 // conflict. We expect the server to send us a proper
2176 // (non-Conflict) error later.
2177 if (p.cseq_main != null || p.cseq_loose != null) {
2178 if (drag_pieces.some(function(dp) { return dp.piece == piece; })) {
2179 console.log('drag end due to conflict');
2183 if (p.cseq_main != null) {
2184 if (!already_logged)
2185 add_log_message('Conflict! - simultaneous update');
2188 p.cseq_loose = null;
2191 function test_swap_stack() {
2192 let old_bot = pieces_marker.nextElementSibling!;
2193 let container = old_bot.parentElement!;
2194 container.insertBefore(old_bot, defs_marker);
2195 window.setTimeout(test_swap_stack, 1000);
2198 function startup() {
2199 console.log('STARTUP');
2200 console.log(wasm_bindgen.setup("OK"));
2202 var body = document.getElementById("main-body")!;
2203 zoom_btn = document.getElementById("zoom-btn") as any;
2204 zoom_val = document.getElementById("zoom-val") as any;
2205 links_elem = document.getElementById("links") as any;
2206 ctoken = body.dataset.ctoken!;
2207 us = body.dataset.us!;
2208 gen = +body.dataset.gen!;
2209 let sse_url_prefix = body.dataset.sseUrlPrefix!;
2210 status_node = document.getElementById('status')!;
2211 status_node.innerHTML = 'js-done';
2212 log_elem = document.getElementById("log")!;
2213 logscroll_elem = document.getElementById("logscroll") || log_elem;
2214 let dataload = JSON.parse(body.dataset.load!);
2215 held_surround_colour = dataload.held_surround_colour!;
2216 players = dataload.players!;
2217 delete body.dataset.load;
2218 uos_node = document.getElementById("uos")!;
2219 occregions = wasm_bindgen.empty_region_list();
2221 space = svg_element('space')!;
2222 pieces_marker = svg_element("pieces_marker")!;
2223 defs_marker = svg_element("defs_marker")!;
2224 movehist_start = svg_element('movehist_marker')!;
2225 movehist_end = svg_element('movehist_end')!;
2226 rectsel_path = svg_element('rectsel_path')!;
2227 svg_ns = space.getAttribute('xmlns')!;
2229 for (let uelem = pieces_marker.nextElementSibling! as SVGGraphicsElement;
2230 uelem != defs_marker;
2231 uelem = uelem.nextElementSibling! as SVGGraphicsElement) {
2232 let piece = uelem.dataset.piece!;
2233 let p = JSON.parse(uelem.dataset.info!);
2235 p.delem = piece_element('defs',piece);
2236 p.pelem = piece_element('piece',piece);
2238 occregion_update(piece, p, p); delete p.occregion;
2239 delete uelem.dataset.info;
2241 piece_resolve_special(piece,p);
2242 redisplay_ancillaries(piece,p);
2245 if (test_update_hook == null) test_update_hook = function() { };
2248 last_log_ts = wasm_bindgen.timestamp_abbreviator(dataload.last_log_ts);
2250 for (let ent of dataload.movehist.hist) {
2251 movehist_record(ent);
2254 var es = new EventSource(
2255 sse_url_prefix + "/_/updates?ctoken="+ctoken+'&gen='+gen
2257 es.onmessage = function(event) {
2258 console.log('GOTEVE', event.data);
2262 var [tgen, ms] = JSON.parse(event.data);
2264 k = Object.keys(m)[0];
2270 var s = exc.toString();
2271 string_report_error('exception handling update '
2272 + k + ': ' + JSON.stringify(m) + ': ' + s);
2275 es.addEventListener('commsworking', function(event) {
2276 console.log('GOTDATA', (event as any).data);
2277 status_node.innerHTML = (event as any).data;
2279 es.addEventListener('player-gone', function(event) {
2280 console.log('PLAYER-GONE', event);
2281 status_node.innerHTML = (event as any).data;
2282 add_log_message('<strong>You are no longer in the game</strong>');
2283 space.removeEventListener('mousedown', some_mousedown);
2284 document.removeEventListener('keydown', some_keydown);
2287 es.addEventListener('updates-expired', function(event) {
2288 console.log('UPDATES-EXPIRED', event);
2289 string_report_error('connection to server interrupted too long');
2291 es.onerror = function(e) {
2294 updates_event_source : es,
2295 updates_event_source_ready : es.readyState,
2296 update_oe : (e as any).className,
2298 if (es.readyState == 2) {
2300 reason: "TOTAL SSE FAILURE",
2304 console.log('SSE error event', info);
2307 recompute_keybindings();
2308 space.addEventListener('mousedown', some_mousedown);
2309 space.addEventListener('dragstart', function (e) {
2311 e.stopPropagation();
2313 document.addEventListener('keydown', some_keydown);
2317 type DieSpecialRendering = SpecialRendering & {
2318 cd_path: SVGPathElement,
2319 loaded_ts: DOMHighResTimeStamp,
2320 loaded_remprop: number,
2323 anim_id: number | null,
2325 special_renderings['Die'] = function(piece: PieceId, p: PieceInfo,
2326 s: DieSpecialRendering) {
2327 let cd_path = document.getElementById('def.'+piece+'.die.cd');
2328 if (!cd_path) return;
2330 s.cd_path = cd_path as any as SVGPathElement;
2331 s.loaded_ts = performance.now();
2332 s.loaded_remprop = parseFloat(cd_path.dataset.remprop!)!;
2333 s.total_ms = parseFloat(cd_path.dataset.total_ms!)!;
2334 s.radius = parseFloat(cd_path.dataset.radius!)!;
2336 s.stop = die_rendering_stop as any;
2337 die_request_animation(piece, p, s);
2339 function die_request_animation(piece: PieceId, p: PieceInfo,
2340 s: DieSpecialRendering) {
2341 s.anim_id = window.requestAnimationFrame(
2342 function(ts) { die_render_frame(piece, p, s, ts) }
2345 function die_render_frame(piece: PieceId, p: PieceInfo,
2346 s: DieSpecialRendering, ts: DOMHighResTimeStamp) {
2348 let remprop = s.loaded_remprop - (ts - s.loaded_ts) / s.total_ms;
2349 //console.log('DIE RENDER', piece, s, remprop);
2351 console.log('DIE COMPLETE', piece, s, remprop);
2352 let to_remove: Element = s.cd_path;
2354 let previous = to_remove.previousElementSibling!;
2355 // see dice/overlya-template-extractor
2356 if (to_remove.tagName == 'text') break;
2358 to_remove = previous;
2361 let path_d = wasm_bindgen.die_cooldown_path(s.radius, remprop);
2362 s.cd_path.setAttributeNS(null, "d", path_d);
2363 die_request_animation(piece, p, s);
2366 function die_rendering_stop(piece: PieceId, p: PieceInfo,
2367 s: DieSpecialRendering) {
2368 let anim_id = s.anim_id;
2369 if (anim_id == null) return;
2371 window.cancelAnimationFrame(anim_id);
2374 declare var wasm_input : any;
2375 var wasm_promise : Promise<any>;;
2378 console.log('DOLOAD');
2379 globalinfo_elem = document.getElementById('global-info')!;
2380 layout = globalinfo_elem!.dataset!.layout! as any;
2381 var elem = document.getElementById('loading_token')!;
2382 var ptoken = elem.dataset.ptoken;
2383 xhr_post_then('/_/session/' + layout,
2384 JSON.stringify({ ptoken : ptoken }),
2387 wasm_promise = wasm_input
2388 .then(wasm_bindgen);
2391 function loaded(xhr: XMLHttpRequest){
2392 console.log('LOADED');
2393 var body = document.getElementById('loading_body')!;
2394 wasm_promise.then((got_wasm) => {
2396 body.outerHTML = xhr.response;
2400 let s = exc.toString();
2401 string_report_error_raw('Exception on load, unrecoverable: ' + s);
2406 // todo scroll of log messages to bottom did not always work somehow
2407 // think I have fixed this with approximation