anvilsign in

collin/mahjong

1import type { GameState } from '../game/engine';
2import { makeRng, type Tile } from '../game/tiles';
3import type { SeatId } from '../game/types';
4import {
5 aimAt,
6 canThrow,
7 canThrowFrom,
8 centreOf,
9 measure,
10 spanThrough,
11 type Point,
12 type TableGeometry,
13} from './geometry';
14import {
15 addBody,
16 advance as advanceWorld,
17 createWorld,
18 liftFor,
19 reshape,
20 settled,
21 stir,
22 SLIDE_TIME,
23 type Body,
24 type Impact,
25 type Rect,
26 type World,
27} from './physics';
28
29const SEATS: SeatId[] = [0, 1, 2, 3];
30
31/**
32 * The tiles in the middle, kept honest against the game state.
33 *
34 * This *diffs* rather than listening for events, and that is the whole design.
35 * A discard is identified by which seat threw it and how many it had thrown
36 * before — and those keys never shift, because discards are only ever pushed and
37 * `engine.executeClaim` only ever pops the one on top. So every way the pile can
38 * change is the same code path: a key that has appeared is a tile to throw in, a
39 * key that has gone is a tile to take out. Undo, 下一局, a claim, and picking up
40 * a saved game all fall out of that without the engine knowing this exists.
41 *
42 * Nothing here is stored in the game state, so there is no save format to
43 * change. A pile is rebuilt from the discards it can see, seeded off the hand
44 * number and each tile's place in it, which is why a refresh mid-hand comes back
45 * to the pile it had rather than a freshly scattered one.
46 */
47
48/** How long a placed tile is in the air. Long enough to arc over the wall. */
49const PLACE_FLIGHT = 0.62;
50/** A flicked tile hops rather than lofts — across the table, not over a wall. */
51const THROW_LIFT = 0.18;
52/** Fastest flick we will honour, px/s. Beyond this it is a slip, not a throw. */
53export const MAX_THROW_SPEED = 3600;
54/** How long a claimed tile takes to leave the table for the seat taking it. */
55const TAKE_FLIGHT = 0.34;
56
57/** A tile on its way off the table, no longer part of the pile. */
58interface Leaving {
59 body: Body;
60 tx: number;
61 ty: number;
62 /** 0 to 1. */
63 t: number;
64}
65
66/**
67 * Whether a tile turns over on its way in.
68 *
69 * Off for now. Like `LOB_WHEN_WALLED` below, the tumble is kept whole — the
70 * flip is a real axis in `physics.ts` and the renderer already squashes the
71 * tile along it — and this is the only switch that reaches it, so putting it
72 * back is one word rather than a rewrite.
73 */
74const TUMBLE: boolean = false;
75
76/**
77 * Whether a wall standing in the way turns a discard into a lob over the top
78 * rather than a flick across the table.
79 *
80 * Back on now that the square is a square again. It was off while the wall ran
81 * along the edges of the middle, where there was nothing much to get over and
82 * everything read better slid; a square standing in the middle with the pool
83 * inside it is the other case, and a tile slid flat at it simply bounces off
84 * and ends up lying outside — which is not where a discard goes. As the square
85 * is eaten the gaps open and the slide comes back on its own, seat by seat.
86 */
87const LOB_WHEN_WALLED: boolean = true;
88
89/** A tile lifted out of a hand and carried about. Drawn, but not simulated. */
90export interface Held {
91 seat: SeatId;
92 tile: Tile;
93 /** Where it came from in that seat's hand, so the caller knows what to play. */
94 index: number;
95 x: number;
96 y: number;
97 angle: number;
98 /** The size it was in the hand — it shrinks to pool size once thrown. */
99 w: number;
100 h: number;
101}
102
103/** A throw that has been let go of, waiting for the discard it belongs to. */
104interface Release {
105 seat: SeatId;
106 x: number;
107 y: number;
108 angle: number;
109 w: number;
110 h: number;
111 vx: number;
112 vy: number;
113 spin: number;
114}
115
116export class TablePool {
117 world: World | null = null;
118 geo: TableGeometry | null = null;
119 /** The tile in somebody's fingers, if any. */
120 held: Held | null = null;
121 /**
122 * Poke the render loop. Set by ui/Pool.tsx while it is mounted; a gesture
123 * calls it so a carried tile follows the finger without waiting on a re-render.
124 */
125 wake: () => void = () => {};
126
127 private table: HTMLElement | null = null;
128 /** Bodies by `seat:index` into that seat's discards. */
129 private entries = new Map<string, Body>();
130 private release: Release | null = null;
131 /** What the wall looked like when we last measured, so we know to re-measure. */
132 private measuredAt = '';
133 private hand = -1;
134 /** The tile currently on the table to be claimed, so it can be marked. */
135 private newestKey: string | null = null;
136 /** How many melds each seat had last time, to spot who took a tile. */
137 private melds = [0, 0, 0, 0];
138 /** Tiles on their way off the table. Drawn, but out of the physics. */
139 private leaving: Leaving[] = [];
140
141 // Which seats can throw, as a string, so the seats can re-render when it
142 // changes. Read through useSyncExternalStore, the same way the game is.
143 private openness = '----';
144 private listeners = new Set<() => void>();
145
146 attach(table: HTMLElement) {
147 this.table = table;
148 this.measuredAt = '';
149 }
150
151 detach() {
152 this.table = null;
153 this.world = null;
154 this.geo = null;
155 this.held = null;
156 this.release = null;
157 this.entries.clear();
158 this.leaving = [];
159 this.measuredAt = '';
160 }
161
162 subscribe = (cb: () => void) => {
163 this.listeners.add(cb);
164 return () => this.listeners.delete(cb);
165 };
166
167 /** Which seats have a clear line in, as a string — cheap to compare. */
168 getSnapshot = () => this.openness;
169
170 /** Force a re-measure — the window resized, or the layout changed under us. */
171 invalidate() {
172 this.measuredAt = '';
173 }
174
175 /**
176 * Whether this seat can flick a tile in, or has to lift it over the wall.
177 * Unmeasured (or compact, where there is no square) means no.
178 */
179 canThrow(seat: SeatId): boolean {
180 return this.openness[seat] === 'y';
181 }
182
183 /** Where the middle of the table is, for a gesture working out its aim. */
184 get poolCentre(): Point | null {
185 return this.geo ? centreOf(this.geo.pool) : null;
186 }
187
188 /** Whether a point is already inside the square — a tile dropped there stays. */
189 inPool(x: number, y: number): boolean {
190 const p = this.geo?.pool;
191 if (!p) return false;
192 return x >= p.x && x <= p.x + p.w && y >= p.y && y <= p.y + p.h;
193 }
194
195 /** Whether a tile let go of *here* has a clear line in. Not the same question
196 * as `canThrow(seat)`: a carried tile is wherever the player took it. */
197 canThrowFrom(x: number, y: number): boolean {
198 return !!this.geo && canThrowFrom(this.geo, { x, y });
199 }
200
201 /** Where the pool sits on the table, for the patch of it you can reach into. */
202 get poolRect(): Rect | null {
203 return this.geo?.pool ?? null;
204 }
205
206 /**
207 * Push the tiles in the middle about — washing them, the way everybody does
208 * to a pool of discards while waiting. Purely cosmetic: where a discard is
209 * lying is not part of the game.
210 */
211 stir(x: number, y: number, vx: number, vy: number) {
212 if (!this.world || !this.geo) return;
213 // A finger's worth: about a tile across.
214 stir(this.world, x, y, vx, vy, this.geo.tile.w * 0.6);
215 }
216
217 // ---- the tile in your fingers -----------------------------------------
218
219 /** Lifted out of a hand. From here the canvas draws it, not the DOM. */
220 pickUp(held: Held) {
221 this.held = held;
222 }
223
224 moveHeld(x: number, y: number, angle?: number) {
225 if (!this.held) return;
226 this.held.x = x;
227 this.held.y = y;
228 if (angle !== undefined) this.held.angle = angle;
229 }
230
231 /** Put it back in the hand — the throw was not committed to. */
232 cancelHeld() {
233 this.held = null;
234 }
235
236 /**
237 * Let go of it. The body is not made here: the reconciler owns every tile in
238 * the pool, so this leaves the throw where the next `sync` will find it and
239 * the caller goes on to call `game.discard`. The held tile stays drawn until
240 * that happens, so there is no frame with nothing on screen.
241 */
242 throwHeld(vx: number, vy: number, spin: number) {
243 const h = this.held;
244 if (!h) return;
245 const speed = Math.hypot(vx, vy);
246 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
247 this.release = {
248 seat: h.seat,
249 x: h.x,
250 y: h.y,
251 angle: h.angle,
252 w: h.w,
253 h: h.h,
254 vx: vx * scale,
255 vy: vy * scale,
256 spin,
257 };
258 }
259
260 // ---- keeping up with the game ----------------------------------------
261
262 /** Bring the pile in line with the state. Cheap when nothing has changed. */
263 sync(state: GameState) {
264 this.remeasure(state);
265 const geo = this.geo;
266 const world = this.world;
267 if (!geo || !world) return;
268
269 // A new hand is a new pile, and nothing should fly anywhere.
270 const fresh = state.handNumber !== this.hand;
271 this.hand = state.handNumber;
272
273 const want = new Set<string>();
274 const added: { key: string; seat: SeatId; index: number; tile: Tile }[] = [];
275 for (const seat of SEATS) {
276 const discards = state.players[seat].discards;
277 for (let i = 0; i < discards.length; i++) {
278 const key = `${seat}:${i}`;
279 want.add(key);
280 if (!this.entries.has(key)) added.push({ key, seat, index: i, tile: discards[i] });
281 }
282 }
283
284 const taken: Body[] = [];
285 for (const [key, body] of this.entries) {
286 if (want.has(key)) continue;
287 const at = world.bodies.indexOf(body);
288 if (at >= 0) world.bodies.splice(at, 1);
289 this.entries.delete(key);
290 taken.push(body);
291 }
292
293 // Exactly one tile off the table is somebody taking it — a 碰, a 吃, a 槓,
294 // or a discard being taken back. It goes to whoever now has a meld they did
295 // not have a moment ago, and failing that back to the seat that threw it,
296 // which is what an undo is. Several at once is the hand ending, and those
297 // simply go.
298 const claimer = SEATS.find((q) => state.players[q].melds.length > this.melds[q]);
299 this.melds = SEATS.map((q) => state.players[q].melds.length);
300 if (taken.length === 1 && !fresh) {
301 const to = geo.launch[claimer ?? taken[0].seat];
302 if (to) this.leaving.push({ body: taken[0], tx: to.x, ty: to.y, t: 0 });
303 }
304
305 // One tile at a time is somebody playing, and it gets thrown. Several at
306 // once is a pile being rebuilt — a save picked up, an undo, a fresh deal —
307 // and those tiles were thrown long ago, so they are simply already there.
308 const rebuilding = fresh || added.length > 1;
309 for (const a of added) {
310 this.entries.set(a.key, rebuilding ? this.settle(geo, state, a) : this.launch(geo, state, a));
311 }
312
313 // A throw is good for exactly one discard, and the tile it belonged to has
314 // either just arrived or is never going to.
315 if (added.length || this.release) {
316 this.release = null;
317 this.held = null;
318 }
319
320 const ld = state.lastDiscard;
321 this.newestKey = ld ? `${ld.from}:${state.players[ld.from].discards.length - 1}` : null;
322 }
323
324 /** Run the physics on. Returns impacts worth a sound. */
325 advance(seconds: number): Impact[] {
326 this.carryOff(seconds);
327 return this.world ? advanceWorld(this.world, seconds) : [];
328 }
329
330 /** Tiles leaving the table, lifted and carried off to the seat taking them. */
331 private carryOff(seconds: number) {
332 if (this.leaving.length === 0) return;
333 for (const l of this.leaving) {
334 l.t = Math.min(1, l.t + seconds / TAKE_FLIGHT);
335 // Ease out, so it leaves quickly and arrives gently.
336 const k = 1 - (1 - l.t) * (1 - l.t);
337 l.body.x += (l.tx - l.body.x) * k * 0.5;
338 l.body.y += (l.ty - l.body.y) * k * 0.5;
339 // Up off the table on the way, the way a tile picked up would be.
340 l.body.z = Math.sin(l.t * Math.PI) * 40;
341 l.body.angle += seconds * 2.2;
342 }
343 this.leaving = this.leaving.filter((l) => l.t < 1);
344 }
345
346 /** What is on its way off, and how far gone, for the renderer to fade. */
347 get departing(): { body: Body; fade: number }[] {
348 return this.leaving.map((l) => ({ body: l.body, fade: 1 - l.t }));
349 }
350
351 get bodies(): Body[] {
352 return this.world?.bodies ?? [];
353 }
354
355 /** The tile on the table, if there is one — drawn lit, as a lifted tile is. */
356 get newest(): Body | null {
357 return (this.newestKey && this.entries.get(this.newestKey)) || null;
358 }
359
360 /**
361 * A tile is still on its way to the middle. The computer players hold off
362 * while this is true — nobody at a real table reaches across for a tile that
363 * has not landed, and a 碰 called over one still turning over in the air looks
364 * like it was snatched out of flight.
365 */
366 get throwInFlight(): boolean {
367 const b = this.newest;
368 return !!b && !b.resting;
369 }
370
371 /** Nothing is moving, so the render loop can stop until something changes. */
372 get settled(): boolean {
373 return !this.held && this.leaving.length === 0 && (!this.world || settled(this.world));
374 }
375
376 // ---- measuring ---------------------------------------------------------
377
378 /**
379 * Re-read the table when the wall's shape has changed or the window has. The
380 * pile keeps its positions across a re-measure: the wall shrinking does not
381 * move the tiles already on the felt.
382 */
383 private remeasure(state: GameState) {
384 const table = this.table;
385 if (!table) return;
386 const stamp = `${state.drawnFront}/${state.drawnBack}/${Math.round(
387 table.clientWidth,
388 )}x${Math.round(table.clientHeight)}`;
389 if (stamp === this.measuredAt) return;
390
391 const geo = measure(table, state);
392 this.measuredAt = geo ? stamp : '';
393 this.geo = geo;
394 if (!geo) {
395 this.world = null;
396 this.entries.clear();
397 this.setOpenness('----');
398 return;
399 }
400 // Bounded by the felt, not by the square: what keeps a tile in the middle is
401 // the stacks still standing, and once they are gone the pool is free to
402 // spread out through the gap the way a real one does.
403 if (!this.world) this.world = createWorld(geo.felt, geo.walls);
404 else reshape(this.world, geo.felt, geo.walls);
405 // Only here, never per frame: a hundred-odd ray casts is nothing once a
406 // draw, and a great deal every sixtieth of a second.
407 this.setOpenness(SEATS.map((s) => (canThrow(geo, s) ? 'y' : '-')).join(''));
408 }
409
410 private setOpenness(next: string) {
411 if (next === this.openness) return;
412 this.openness = next;
413 for (const cb of this.listeners) cb();
414 }
415
416 // ---- putting tiles in -------------------------------------------------
417
418 /** A tile that is simply there already — a rebuilt pile. */
419 private settle(
420 geo: TableGeometry,
421 state: GameState,
422 a: { seat: SeatId; index: number; tile: Tile },
423 ): Body {
424 const rng = this.seeded(state, a);
425 const { pool } = geo;
426 // Bunched towards the middle rather than spread evenly to the edges, which
427 // is what a pool thrown into from four sides actually looks like.
428 const spread = 0.3;
429 return addBody(this.world!, {
430 tile: a.tile,
431 seat: a.seat,
432 x: pool.x + pool.w * (0.5 + (rng() - 0.5) * 2 * spread),
433 y: pool.y + pool.h * (0.5 + (rng() - 0.5) * 2 * spread),
434 vx: 0,
435 vy: 0,
436 z: 0,
437 vz: 0,
438 angle: (rng() - 0.5) * Math.PI,
439 spin: 0,
440 w: geo.tile.w,
441 h: geo.tile.h,
442 atRest: true,
443 });
444 }
445
446 /** A tile arriving now: thrown if somebody threw it, placed over the wall if
447 * it was tapped, and flat and quick if a bot's wall happens to be open. */
448 private launch(
449 geo: TableGeometry,
450 state: GameState,
451 a: { seat: SeatId; index: number; tile: Tile },
452 ): Body {
453 const rng = this.seeded(state, a);
454 const thrown = this.release?.seat === a.seat ? this.release : null;
455
456 if (thrown) {
457 // Which of the two ways a tile goes in, decided by what is in its way.
458 //
459 // A clear line to the square means it can be *slid* — flat across the
460 // cloth, at exactly the speed it was let go at, which is what a flick
461 // wants to be. A standing wall means it has to be *thrown* instead: lifted
462 // over the top and dropped in, and then the flick's speed decides how far
463 // across the pool it lands rather than how fast it skates.
464 // Sliding is the preferred way in, and the question is asked from where
465 // the tile actually is — a player who carried it out over the square has a
466 // clear line even though the seat they came from does not. Only a tile
467 // with nothing but standing wall in front of it has to be lobbed.
468 const set = this.inPool(thrown.x, thrown.y);
469 const slide = set || !LOB_WHEN_WALLED || this.canThrowFrom(thrown.x, thrown.y);
470 let { vx, vy } = thrown;
471 let vz = 0;
472 const speed = Math.hypot(vx, vy);
473 let flipTurns = 0;
474 let flipOver = 0;
475
476 if (!slide) {
477 // Lofted over a standing wall, and it has to come *down* inside the
478 // square: a lob solved for where it would come to rest touches down
479 // short, on the wrong side of the wall, and stops dead against it.
480 //
481 // So the flick picks a landing spot along its own line, between just
482 // inside the near edge of the square and just short of the far one. A
483 // limp one drops in over the near wall, a hard one carries to the far
484 // side and barges through whatever is lying there, and neither of them
485 // can leave the tile outside.
486 const dir = speed > 0 ? { x: vx / speed, y: vy / speed } : { x: 0, y: -1 };
487 const span = spanThrough(geo.pool, thrown, dir);
488 const centre = centreOf(geo.pool);
489 let carry = speed * PLACE_FLIGHT;
490 if (span) {
491 const near = span.near + geo.tile.h;
492 carry = Math.min(Math.max(near, carry), Math.max(near, span.far - geo.tile.h));
493 } else {
494 // Flicked somewhere that is not the square at all — put it in anyway.
495 carry = Math.hypot(centre.x - thrown.x, centre.y - thrown.y);
496 dir.x = (centre.x - thrown.x) / (carry || 1);
497 dir.y = (centre.y - thrown.y) / (carry || 1);
498 }
499 vx = (dir.x * carry) / PLACE_FLIGHT;
500 vy = (dir.y * carry) / PLACE_FLIGHT;
501 vz = liftFor(PLACE_FLIGHT);
502 // Long enough in the air to turn over properly, and harder means more.
503 flipOver = PLACE_FLIGHT;
504 flipTurns = speed > 1300 ? 2 : 1;
505 } else if (!set) {
506 // A skated tile leaves the fingers off the cloth, and turns over on its
507 // way down — harder means longer in the air and more turns in it.
508 const hop = THROW_LIFT + Math.min(0.22, (speed / MAX_THROW_SPEED) * 0.28);
509 vz = liftFor(hop);
510 flipOver = hop;
511 flipTurns = speed > 2200 ? 2 : speed > 600 ? 1 : 0;
512 }
513 if (!TUMBLE) flipTurns = 0;
514
515 return addBody(this.world!, {
516 tile: a.tile,
517 seat: a.seat,
518 x: thrown.x,
519 y: thrown.y,
520 vx,
521 vy,
522 z: 0,
523 vz,
524 angle: thrown.angle,
525 spin: thrown.spin,
526 flipTurns,
527 flipOver,
528 // It tumbles across its line of travel, the way a thrown tile does.
529 flipAxis: Math.atan2(vy, vx),
530 w: geo.tile.w,
531 h: geo.tile.h,
532 // It was drawn at hand size a moment ago; it shrinks on the way down.
533 scale: thrown.w / geo.tile.w,
534 });
535 }
536
537 // Off the end of the hand, not the middle of it — a tile is thrown from the
538 // hand holding it, which is the one at the right-hand end of the row.
539 const from = geo.throwFrom[a.seat] ?? geo.launch[a.seat] ?? centreOf(geo.pool);
540 const open = !LOB_WHEN_WALLED || this.canThrow(a.seat);
541 const target = this.aimFor(geo, a.seat, rng);
542 const flight = open ? 0.34 + rng() * 0.1 : PLACE_FLIGHT;
543 // A slide is aimed at where it comes to *rest*, since it keeps going after
544 // it lands and SLIDE_TIME is roughly how much further. A lob is aimed at
545 // where it touches *down*, because it has to come down on the inside of the
546 // wall — solving for the resting place lands it short, against the outside.
547 const reach = open ? flight + SLIDE_TIME : flight;
548
549 const vx = (target.x - from.x) / reach;
550 const vy = (target.y - from.y) / reach;
551 return addBody(this.world!, {
552 tile: a.tile,
553 seat: a.seat,
554 x: from.x,
555 y: from.y,
556 vx,
557 vy,
558 z: 0,
559 vz: liftFor(flight),
560 angle: (rng() - 0.5) * Math.PI,
561 spin: (rng() - 0.5) * (open ? 7 : 2.5),
562 // It turns over on its way in, whichever way it is going.
563 flipTurns: TUMBLE ? 1 : 0,
564 flipOver: flight,
565 flipAxis: Math.atan2(vy, vx),
566 w: geo.tile.w,
567 h: geo.tile.h,
568 });
569 }
570
571 /** Where a tile from this seat is headed, with a little scatter. */
572 private aimFor(geo: TableGeometry, seat: SeatId, rng: () => number): Point {
573 const base = aimAt(geo, seat) ?? centreOf(geo.pool);
574 const jitter = Math.min(geo.pool.w, geo.pool.h) * 0.22;
575 return { x: base.x + (rng() - 0.5) * jitter, y: base.y + (rng() - 0.5) * jitter };
576 }
577
578 /**
579 * A tile's own random stream. Keyed on the hand and its place in that seat's
580 * discards, so the same tile scatters the same way every time it is rebuilt —
581 * a refresh mid-hand puts the pile back exactly as it was.
582 */
583 private seeded(state: GameState, a: { seat: SeatId; index: number; tile: Tile }) {
584 return makeRng(state.handNumber * 7919 + a.seat * 977 + a.index * 31 + a.tile + 1);
585 }
586}