anvilsign in

collin/mahjong

1import { useEffect, useRef, useState } from 'react';
2import type { TableCtl } from '../game/ctl';
3import { barge, knock, type Place } from '../game/sound';
4import { aabbOf, centreLimits, faceOn, type Impact, type Rect } from '../table/physics';
5import type { TablePool } from '../table/pool';
6import type { SeatId } from '../game/types';
7import {
8 exposePool,
9 holdOn,
10 isHeld,
11 keyHeld,
12 noteImpacts,
13 onCollidersChange,
14 owedTime,
15 pausingOnHit,
16 recentImpacts,
17 showingColliders,
18} from './colliders';
19import { flickOf, type Sample } from './flick';
20import { EDGE_SEAT } from './rotation';
21import { drawShadow, drawTile, loadArt, type Art } from './tileArt';
22
23/**
24 * The tiles in the middle of the table, drawn.
25 *
26 * A canvas rather than elements, and it spans the whole table rather than just
27 * the centre. The span is the point: `.slot` and `.seat` both clip their own
28 * contents, which is exactly why a tile cannot be animated out of a strip as a
29 * div — on the canvas there is nothing to clip it, so a tile lifted out of a
30 * hand and thrown crosses the table in one piece.
31 *
32 * The loop stops as soon as the pile has settled, and starts again when the
33 * state changes, a tile is picked up, or the window resizes, so a table nobody
34 * is touching costs nothing.
35 */
36export function Pool({
37 game,
38 pool,
39 viewSeat = 0,
40}: {
41 game: TableCtl;
42 pool: TablePool;
43 /** The seat drawn at the bottom of this screen — see App. An edge the physics
44 * reports belongs to whoever is drawn there, not to seat 0 by birthright. */
45 viewSeat?: SeatId;
46}) {
47 const canvasRef = useRef<HTMLCanvasElement>(null);
48 const art = useSheet();
49
50 // What the loop reads. Refreshed on every render, read on every frame.
51 const live = useRef({ state: game.state, art, viewSeat });
52 live.current = { state: game.state, art, viewSeat };
53
54 // Poked by the effect below, and by the gesture through pool.wake.
55 const wake = useRef<() => void>(() => {});
56
57 useEffect(() => {
58 const canvas = canvasRef.current;
59 const table = canvas?.parentElement;
60 const ctx = canvas?.getContext('2d');
61 if (!canvas || !table || !ctx) return;
62
63 pool.attach(table);
64 exposePool(pool);
65 const stopDragging = dragging(table as HTMLElement, pool, () => wake.current());
66 // Somebody has pushed a wall along. Where a thrown tile bounces has moved
67 // with it, and the pool re-measures only when it is given a reason to.
68 const wallMoved = () => {
69 pool.invalidate();
70 wake.current();
71 };
72 table.addEventListener('wallmoved', wallMoved);
73
74 let frame = 0;
75 let previous = 0;
76
77 const resize = () => {
78 const dpr = window.devicePixelRatio || 1;
79 const w = Math.round(table.clientWidth * dpr);
80 const h = Math.round(table.clientHeight * dpr);
81 if (canvas.width !== w || canvas.height !== h) {
82 canvas.width = w;
83 canvas.height = h;
84 }
85 // The square moved, so the colliders and the launch points have too.
86 pool.invalidate();
87 run();
88 };
89
90 const tick = (now: number) => {
91 frame = 0;
92 // First frame after waking has no previous time to measure against.
93 const dt = previous ? Math.min(0.05, (now - previous) / 1000) : 0;
94 previous = now;
95
96 pool.sync(live.current.state);
97 // A tile in the fingers goes over the table's own buttons — seat 0 throws
98 // from the *right-hand end* of its row, which is directly under the undo
99 // button — so while one is being carried they stop taking the pointer.
100 table.classList.toggle('carrying', !!pool.held);
101 // The loudest contact this frame is the one you would actually hear; the
102 // rest of a scatter is the same event.
103 // Frozen on a contact: the world only moves when it is asked to, a fixed
104 // step at a time, so the moment can be walked through rather than watched.
105 const impacts = isHeld() ? pool.advance(owedTime()) : pool.advance(dt, pausingOnHit());
106 noteImpacts(impacts);
107 if (pausingOnHit() && !isHeld() && impacts.length) holdOn(impacts);
108 let loudest = 0;
109 let loudAt: Impact | null = null;
110 for (const i of impacts) {
111 // A contact quiet enough not to be worth hearing still counts as a tile
112 // arriving in somebody's lap, which is why the two thresholds differ.
113 if (i.strength > AUDIBLE && i.strength > loudest) {
114 loudest = i.strength;
115 loudAt = i;
116 }
117 // Straight into somebody's tiles — the wall square is nobody's, so this
118 // is a hand or a set that has been laid down.
119 if (i.into !== undefined) {
120 shove(pool, table, i.into, i.seat, i.strength, posOf(i.into, live.current.viewSeat));
121 } else if (i.edge) {
122 // An edge is already stated in this screen's own terms, which is what
123 // the sound wants; the seat sitting at it is the round trip back.
124 const pos = EDGE_SEAT[i.edge] as SeatId;
125 const at = ((pos + live.current.viewSeat) % 4) as SeatId;
126 shove(pool, table, at, i.seat, i.strength, pos);
127 }
128 }
129 // Out in the middle a sound has a real position rather than an edge it
130 // belongs to, and the physics knows it to the pixel.
131 if (loudest > 0) knock(loudest, spotOf(pool, loudAt!));
132 paint(ctx, canvas, pool, live.current.art);
133
134 // Keep going while anything is moving; otherwise wait to be poked. A held
135 // world is never running: it is stepped by hand and repainted each time.
136 if (!isHeld() && !pool.settled) frame = requestAnimationFrame(tick);
137 else previous = 0;
138 };
139
140 const run = () => {
141 if (!frame) frame = requestAnimationFrame(tick);
142 };
143 wake.current = run;
144 pool.wake = run;
145
146 const observer = new ResizeObserver(resize);
147 observer.observe(table);
148 const stopColliders = onCollidersChange(run);
149 const onKey = (e: KeyboardEvent) => {
150 if (keyHeld(e)) e.preventDefault();
151 };
152 window.addEventListener('keydown', onKey);
153 resize();
154
155 return () => {
156 table.removeEventListener('wallmoved', wallMoved);
157 stopDragging();
158 window.removeEventListener('keydown', onKey);
159 stopColliders();
160 observer.disconnect();
161 if (frame) cancelAnimationFrame(frame);
162 wake.current = () => {};
163 pool.wake = () => {};
164 pool.detach();
165 };
166 }, [pool]);
167
168 // Any change to the table — a discard, a claim, an undo, a new hand — is a
169 // reason to look again.
170 useEffect(() => {
171 wake.current();
172 });
173
174 return <canvas className="tile-pool" ref={canvasRef} aria-hidden />;
175}
176
177/**
178 * Picking a discard up and putting it somewhere else.
179 *
180 * A discard's position is not part of the game — the engine neither knows nor
181 * cares where in the middle a tile is lying — so the pile is free to be handled
182 * the way a real one is: take hold of a tile, carry it over the top of the
183 * others, and either set it down or send it skidding off with a flick.
184 *
185 * The listener is on the table and it *captures*, because the tiles are drawn
186 * on a canvas that has no elements to hit. It hit-tests the pile first and only
187 * takes the gesture when a tile is actually under the finger; anything else is
188 * let straight through to whatever it was really aimed at — a tile in a hand,
189 * the settings button, the wall.
190 */
191function dragging(table: HTMLElement, pool: TablePool, wake: () => void) {
192 let samples: Sample[] = [];
193
194 const at = (e: PointerEvent) => {
195 const r = table.getBoundingClientRect();
196 return { x: e.clientX - r.left, y: e.clientY - r.top, t: e.timeStamp };
197 };
198
199 const down = (e: PointerEvent) => {
200 // Only the primary button, and only where there is a tile to take hold of.
201 if (e.button !== 0) return;
202 const p = at(e);
203 if (!pool.grabAt(p.x, p.y)) return;
204 e.stopPropagation();
205 e.preventDefault();
206 samples = [p];
207 try {
208 table.setPointerCapture?.(e.pointerId);
209 } catch {
210 // Uncaptured still works while the pointer stays over the table.
211 }
212 wake();
213 };
214
215 const move = (e: PointerEvent) => {
216 if (!pool.dragging) return;
217 e.stopPropagation();
218 const p = at(e);
219 // Only the tail matters, and only the recent tail: a flick is the last few
220 // milliseconds of a drag, not an average over the whole of it.
221 samples.push(p);
222 if (samples.length > 6) samples.shift();
223 pool.dragTo(p.x, p.y);
224 wake();
225 };
226
227 const up = (e: PointerEvent) => {
228 if (!pool.dragging) return;
229 e.stopPropagation();
230 samples.push(at(e));
231 // Read exactly as a throw out of a hand is: same gesture, same reading,
232 // curve on it and all. See ui/flick.
233 const v = flickOf(samples);
234 pool.releaseGrab(v.vx, v.vy, v.spin);
235 samples = [];
236 wake();
237 };
238
239 table.addEventListener('pointerdown', down, true);
240 table.addEventListener('pointermove', move, true);
241 table.addEventListener('pointerup', up, true);
242 table.addEventListener('pointercancel', up, true);
243 return () => {
244 table.removeEventListener('pointerdown', down, true);
245 table.removeEventListener('pointermove', move, true);
246 table.removeEventListener('pointerup', up, true);
247 table.removeEventListener('pointercancel', up, true);
248 };
249}
250
251/** The sheet and the green back, once, shared by every tile drawn. */
252function useSheet(): Art {
253 const [art, setArt] = useState<Art>({ faces: null, back: null });
254 useEffect(() => {
255 let alive = true;
256 void loadArt().then((a) => alive && setArt(a));
257 return () => {
258 alive = false;
259 };
260 }, []);
261 return art;
262}
263
264/** How high a tile in somebody's fingers is held above the felt. */
265const HELD_Z = 52;
266
267/** Quieter than this and the contact is not worth a clack of its own. */
268const AUDIBLE = 0.12;
269
270/** How long the knocked row rocks for, in seconds. Matches `shoved` in the CSS,
271 * which is the other half of it: the table waits at least this long. */
272const SHAKE = 0.34;
273
274/** A seat, as an edge of the table this screen is drawing. */
275const posOf = (seat: SeatId, viewSeat: SeatId): SeatId => (((seat - viewSeat + 4) % 4) as SeatId);
276
277/**
278 * Where on the felt a contact happened, in the terms the sound wants: how far
279 * left or right of the middle, and how far up the table — the far half of the
280 * pool is over by 對家 and sounds like it. The felt is drawn in screen
281 * coordinates, so this needs no turning: it is already the way you are facing.
282 */
283function spotOf(pool: TablePool, at: Impact): Place {
284 const b = pool.world?.bounds;
285 if (!b) return {};
286 const pan = Math.max(-1, Math.min(1, (at.x - (b.x + b.w / 2)) / (b.w / 2)));
287 // Only the half of the table away from you counts as distance; the near half
288 // is all within reach, and dulling it would just sound like a blanket.
289 const far = Math.max(0, Math.min(1, (b.y + b.h / 2 - at.y) / (b.h / 2)));
290 return { pan: pan * 0.8, far: far * 0.55 };
291}
292
293/**
294 * A tile has ended up in this seat's tiles — knocked into them, or simply come
295 * to a stop off the table on their side. Either way it is theirs to complain
296 * about, and how hard it arrived only decides how loudly.
297 *
298 * Their row takes the knock — straight on the element rather than through
299 * React, because this happens inside the physics loop and re-rendering four
300 * strips to shake one of them would be absurd — and the table says something
301 * about it. Not for the thrower's own edge: you cannot be barged by your own
302 * discard, and everybody's tile passes over their own row on the way out.
303 */
304function shove(
305 pool: TablePool,
306 table: HTMLElement,
307 seat: SeatId,
308 thrower: SeatId | undefined,
309 strength: number,
310 pos: SeatId,
311) {
312 if (seat === thrower) return;
313 // Hold the table while it is being said and while the row is still rocking.
314 // The computer plays on a timer of its own, and a 碰 called over the top of
315 // somebody objecting to the tile lands the objection on nobody.
316 // It comes from their edge: they are the one whose tiles were scattered, and
317 // it is their voice complaining about it.
318 pool.heckle(Math.max(SHAKE, barge(strength, { pos })));
319 const hand = table.querySelector<HTMLElement>(`[data-seat="${seat}"] .hand`);
320 if (!hand || hand.classList.contains('shoved')) return;
321 hand.classList.add('shoved');
322 hand.addEventListener('animationend', () => hand.classList.remove('shoved'), { once: true });
323}
324
325function paint(
326 ctx: CanvasRenderingContext2D,
327 canvas: HTMLCanvasElement,
328 pool: TablePool,
329 art: Art,
330) {
331 const dpr = window.devicePixelRatio || 1;
332 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
333 ctx.clearRect(0, 0, canvas.width / dpr, canvas.height / dpr);
334
335 const bodies = pool.bodies;
336 const held = pool.held;
337 const departing = pool.departing;
338
339 // Shadows in one pass of their own, offset before rotation, so the light comes
340 // from one direction across the whole pool rather than turning with each tile.
341 for (const b of bodies) {
342 drawShadow(ctx, b.x, b.y, b.z, b.angle, b.w, b.h, b.scale, faceOn(b), b.flipAxis);
343 }
344 if (held) drawShadow(ctx, held.x, held.y, HELD_Z, held.angle, held.w, held.h, 1, 1, 0);
345
346 const newest = pool.newest;
347 for (const b of bodies) {
348 drawTile(ctx, art, {
349 x: b.x,
350 y: b.y,
351 z: b.z,
352 angle: b.angle,
353 w: b.w * b.scale,
354 h: b.h * b.scale,
355 facing: faceOn(b),
356 axis: b.flipAxis,
357 code: b.tile,
358 lit: b === newest,
359 });
360 }
361
362 // On its way to whoever called it — lifted, turning, and fading as it goes.
363 for (const { body: b, fade } of departing) {
364 ctx.save();
365 ctx.globalAlpha = fade;
366 drawTile(ctx, art, {
367 x: b.x,
368 y: b.y,
369 z: b.z,
370 angle: b.angle,
371 w: b.w * b.scale,
372 h: b.h * b.scale,
373 facing: faceOn(b),
374 axis: b.flipAxis,
375 code: b.tile,
376 lit: true,
377 });
378 ctx.restore();
379 }
380
381 // Whatever is in your fingers is above everything else on the table.
382 if (held) {
383 drawTile(ctx, art, {
384 x: held.x,
385 y: held.y,
386 z: HELD_Z,
387 angle: held.angle,
388 w: held.w,
389 h: held.h,
390 facing: 1,
391 axis: 0,
392 code: held.tile,
393 lit: true,
394 });
395 }
396
397 // Over the top of all of it, or there would be no point to it.
398 if (showingColliders()) colliders(ctx, pool);
399}
400
401/**
402 * Every boundary the physics uses, drawn where it actually is.
403 *
404 * Solid the felt — the fence that keeps a tile on the table, measured
405 * out to where each seat's tiles begin (table/geometry.ts).
406 * Solid each standing stack of two. Half stacks are not drawn because
407 * they are not colliders: a tile goes over them.
408 * Dashed the wall square's opening. Only where a throw is *aimed*; it
409 * stops nothing, which is why the pile spills out of it.
410 * Dotted, in where the moving tile's own centre is allowed to be — the felt
411 * less that tile's half width. This is the line a bounce happens
412 * at, and it is half a tile inside the solid one, which is what
413 * makes a bounce look early when it is not.
414 * Per tile the rotated rectangle it really collides with, and, fainter, the
415 * upright box the felt's straight edges use instead. The two come
416 * apart as a tile turns, and that difference is worth seeing.
417 */
418function colliders(ctx: CanvasRenderingContext2D, pool: TablePool) {
419 const world = pool.world;
420 if (!world) return;
421
422 const line = (r: Rect) => ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
423
424 ctx.save();
425 ctx.lineWidth = 1;
426
427 // The table's own edge, and every tile standing on it.
428 ctx.strokeStyle = '#ff2d20';
429 line(world.bounds);
430 for (const w of world.walls) line(w.rect);
431
432 // Where a throw is aimed. Not a fence — see TableGeometry.pool.
433 const aim = pool.poolRect;
434 if (aim) {
435 ctx.setLineDash([5, 5]);
436 ctx.strokeStyle = 'rgba(255, 45, 32, 0.45)';
437 line(aim);
438 ctx.setLineDash([]);
439 }
440
441 // Whatever is still moving: what it collides with, and what it is held by.
442 const live = world.bodies.find((b) => !b.resting) ?? pool.newest;
443
444 for (const b of world.bodies) {
445 // A tile in the fingers is held over everything and collides with nothing,
446 // so it gets no box: the boxes are what is solid.
447 if (b.carried) continue;
448 ctx.strokeStyle = b === live ? 'rgba(255, 45, 32, 0.9)' : 'rgba(255, 45, 32, 0.35)';
449 ctx.save();
450 ctx.translate(b.x, b.y);
451 ctx.rotate(b.angle);
452 ctx.strokeRect(-b.w / 2, -b.h / 2, b.w, b.h);
453 ctx.restore();
454
455 // The upright box the felt's edges are worked out from. Only for the one in
456 // flight: sixty of them at once is a red mess, not a picture.
457 if (b === live && b.angle % Math.PI !== 0) {
458 ctx.setLineDash([2, 3]);
459 ctx.strokeStyle = 'rgba(255, 45, 32, 0.5)';
460 line(aabbOf(b));
461 ctx.setLineDash([]);
462 }
463 }
464
465 if (live) {
466 // The box that tile's centre is held inside, and where the centre is now.
467 ctx.setLineDash([2, 3]);
468 ctx.strokeStyle = 'rgba(255, 45, 32, 0.75)';
469 line(centreLimits(world.bounds, live));
470 ctx.setLineDash([]);
471 ctx.fillStyle = '#ff2d20';
472 ctx.fillRect(live.x - 1.5, live.y - 1.5, 3, 3);
473 }
474
475 // How the last few throws actually left. Faint line: the flick, as it was
476 // let go of. Bright line: where the tile was actually sent. When those two
477 // disagree the tile leaves on a line nobody threw, which is the other way a
478 // bounce can be a bounce off nothing — see TablePool.throws.
479 ctx.font = '9px ui-monospace, monospace';
480 ctx.textBaseline = 'bottom';
481 for (const t of pool.throws) {
482 const ray = (dx: number, dy: number, len: number) => {
483 const d = Math.hypot(dx, dy) || 1;
484 ctx.beginPath();
485 ctx.moveTo(t.x, t.y);
486 ctx.lineTo(t.x + (dx / d) * len, t.y + (dy / d) * len);
487 ctx.stroke();
488 };
489 ctx.strokeStyle = 'rgba(90, 200, 250, 0.35)';
490 ray(t.fx, t.fy, 90);
491 ctx.strokeStyle = 'rgba(90, 200, 250, 0.9)';
492 ray(t.vx, t.vy, 130);
493 ctx.fillStyle = 'rgba(90, 200, 250, 0.9)';
494 ctx.fillText(t.how, t.x + 6, t.y - 4);
495 ctx.fillRect(t.x - 2, t.y - 2, 4, 4);
496 }
497
498 // Where contact was actually made, fading out. One of these with no box under
499 // it is the interesting case: a bounce off something that is not drawn is a
500 // bounce off something that is not a collider.
501 ctx.font = '9px ui-monospace, monospace';
502 ctx.textBaseline = 'bottom';
503 for (const m of recentImpacts(!isHeld())) {
504 const fade = 1 - m.age / 90;
505 ctx.strokeStyle = `rgba(255, 214, 10, ${fade})`;
506 ctx.fillStyle = `rgba(255, 214, 10, ${fade})`;
507 ctx.beginPath();
508 ctx.moveTo(m.x - 5, m.y);
509 ctx.lineTo(m.x + 5, m.y);
510 ctx.moveTo(m.x, m.y - 5);
511 ctx.lineTo(m.x, m.y + 5);
512 ctx.stroke();
513 if (m.kind) ctx.fillText(m.kind, m.x + 6, m.y - 2);
514 }
515
516 ctx.restore();
517}
518