anvilsign in

collin/mahjong

1import type { NetThrow } from '../game/ctl';
2import type { GameState } from '../game/engine';
3import { makeRng, type Tile } from '../game/tiles';
4import type { SeatId } from '../game/types';
5import { SEAT_ROT } from '../ui/rotation';
6import {
7 aimAt,
8 canThrow,
9 canThrowFrom,
10 centreOf,
11 measure,
12 type Point,
13 type TableGeometry,
14} from './geometry';
15import {
16 addBody,
17 advance as advanceWorld,
18 createWorld,
19 liftFor,
20 reshape,
21 settled,
22 drop,
23 lift,
24 tileAt,
25 SLIDE_TIME,
26 type Body,
27 type Impact,
28 type Rect,
29 type World,
30} from './physics';
31
32const SEATS: SeatId[] = [0, 1, 2, 3];
33
34/**
35 * The tiles in the middle, kept honest against the game state.
36 *
37 * This *diffs* rather than listening for events, and that is the whole design.
38 * A discard is identified by which seat threw it and how many it had thrown
39 * before — and those keys never shift, because discards are only ever pushed and
40 * `engine.executeClaim` only ever pops the one on top. So every way the pile can
41 * change is the same code path: a key that has appeared is a tile to throw in, a
42 * key that has gone is a tile to take out. Undo, 下一局, a claim, and picking up
43 * a saved game all fall out of that without the engine knowing this exists.
44 *
45 * Nothing here is stored in the game state, so there is no save format to
46 * change. A pile is rebuilt from the discards it can see, seeded off the hand
47 * number and each tile's place in it, which is why a refresh mid-hand comes back
48 * to the pile it had rather than a freshly scattered one.
49 */
50
51/** How long a placed tile is in the air. Long enough to arc over the wall. */
52const PLACE_FLIGHT = 0.62;
53/** A flicked tile hops rather than lofts — across the table, not over a wall. */
54const THROW_LIFT = 0.18;
55/** Fastest flick we will honour, px/s. Beyond this it is a slip, not a throw. */
56export const MAX_THROW_SPEED = 3600;
57/** How long a claimed tile takes to leave the table for the seat taking it. */
58const TAKE_FLIGHT = 0.34;
59
60/** A tile on its way off the table, no longer part of the pile. */
61interface Leaving {
62 body: Body;
63 tx: number;
64 ty: number;
65 /** 0 to 1. */
66 t: number;
67}
68
69/**
70 * Whether a tile turns over on its way in.
71 *
72 * Off for now. Like `LOB_WHEN_WALLED` below, the tumble is kept whole — the
73 * flip is a real axis in `physics.ts` and the renderer already squashes the
74 * tile along it — and this is the only switch that reaches it, so putting it
75 * back is one word rather than a rewrite.
76 */
77const TUMBLE: boolean = false;
78
79/**
80 * Whether a wall standing in the way turns a discard into a lob over the top
81 * rather than a flick across the table.
82 *
83 * Back on now that the square is a square again. It was off while the wall ran
84 * along the edges of the middle, where there was nothing much to get over and
85 * everything read better slid; a square standing in the middle with the pool
86 * inside it is the other case, and a tile slid flat at it simply bounces off
87 * and ends up lying outside — which is not where a discard goes. As the square
88 * is eaten the gaps open and the slide comes back on its own, seat by seat.
89 */
90const LOB_WHEN_WALLED: boolean = true;
91
92/** How many sandbox throws stay on the table before the oldest is swept off.
93 * A wall's worth: enough to test a crowded pool, not enough to bury it. */
94const LOOSE_LIMIT = 60;
95
96/** Let go of moving faster than this and it was a flick, not a place. Slow
97 * enough that putting a tile down deliberately never sends it skidding. */
98const DRAG_FLICK = 260;
99
100/** A tile lifted out of a hand and carried about. Drawn, but not simulated. */
101export interface Held {
102 seat: SeatId;
103 tile: Tile;
104 /** Where it came from in that seat's hand, so the caller knows what to play. */
105 index: number;
106 x: number;
107 y: number;
108 angle: number;
109 /** The size it was in the hand — it shrinks to pool size once thrown. */
110 w: number;
111 h: number;
112}
113
114/** One throw, as the overlay wants to see it: let go of at (x, y) along
115 * (fx, fy), and actually sent along (vx, vy). `how` says why they differ. */
116export interface ThrowMark {
117 x: number;
118 y: number;
119 fx: number;
120 fy: number;
121 vx: number;
122 vy: number;
123 how: string;
124}
125
126/** A throw that has been let go of, waiting for the discard it belongs to. */
127interface Release {
128 seat: SeatId;
129 x: number;
130 y: number;
131 angle: number;
132 w: number;
133 h: number;
134 vx: number;
135 vy: number;
136 spin: number;
137}
138
139export class TablePool {
140 world: World | null = null;
141 geo: TableGeometry | null = null;
142 /** The tile in somebody's fingers, if any. */
143 held: Held | null = null;
144 /**
145 * Poke the render loop. Set by ui/Pool.tsx while it is mounted; a gesture
146 * calls it so a carried tile follows the finger without waiting on a re-render.
147 */
148 wake: () => void = () => {};
149
150 private table: HTMLElement | null = null;
151 /** Bodies by `seat:index` into that seat's discards. */
152 private entries = new Map<string, Body>();
153 private release: Release | null = null;
154 /** When the throw was let go of. Online its discard takes a round-trip to
155 * come back, so a release has to be able to outlive a few frames. */
156 private releasedAt = 0;
157 /** What the wall looked like when we last measured, so we know to re-measure. */
158 private measuredAt = '';
159 private hand = -1;
160 /** The tile currently on the table to be claimed, so it can be marked. */
161 private newestKey: string | null = null;
162 /** How many melds each seat had last time, to spot who took a tile. */
163 private melds = [0, 0, 0, 0];
164 /** Tiles on their way off the table. Drawn, but out of the physics. */
165 private leaving: Leaving[] = [];
166 /**
167 * The last few throws: where each was let go of, the line it was let go
168 * *along*, and the line it actually left on.
169 *
170 * Read by the collider overlay and by nothing else. A throw is not always
171 * sent where it was aimed — a flick with standing wall in front of it is
172 * lobbed rather than slid, and one whose line misses the square altogether is
173 * re-aimed at the middle of it — and a tile that leaves on a line nobody
174 * threw reads exactly like a tile that bounced off something invisible.
175 */
176 throws: ThrowMark[] = [];
177 /** The discard being dragged about, if any. */
178 private carried: Body | null = null;
179 /**
180 * Sandbox throws: real tiles in the real world, but belonging to no discard,
181 * so the reconciler never looks at them — nothing in `entries` means nothing
182 * to cull. See `throwLoose`.
183 */
184 private loose: Body[] = [];
185 /** When the table will have stopped talking. See `heckle`. */
186 private quietAt = 0;
187
188 // Which seats can throw, as a string, so the seats can re-render when it
189 // changes. Read through useSyncExternalStore, the same way the game is.
190 private openness = '----';
191 private listeners = new Set<() => void>();
192
193 attach(table: HTMLElement) {
194 this.table = table;
195 this.measuredAt = '';
196 }
197
198 detach() {
199 this.table = null;
200 this.world = null;
201 this.geo = null;
202 this.loose = [];
203 this.carried = null;
204 this.held = null;
205 this.release = null;
206 this.entries.clear();
207 this.leaving = [];
208 this.measuredAt = '';
209 }
210
211 subscribe = (cb: () => void) => {
212 this.listeners.add(cb);
213 return () => this.listeners.delete(cb);
214 };
215
216 /** Which seats have a clear line in, as a string — cheap to compare. */
217 getSnapshot = () => this.openness;
218
219 /** Force a re-measure — the window resized, or the layout changed under us. */
220 invalidate() {
221 this.measuredAt = '';
222 }
223
224 /**
225 * Whether this seat can flick a tile in, or has to lift it over the wall.
226 * Unmeasured (or compact, where there is no square) means no.
227 */
228 canThrow(seat: SeatId): boolean {
229 return this.openness[seat] === 'y';
230 }
231
232 /** Where the middle of the table is, for a gesture working out its aim. */
233 get poolCentre(): Point | null {
234 return this.geo ? centreOf(this.geo.pool) : null;
235 }
236
237 /** Whether a point is already inside the square — a tile dropped there stays. */
238 inPool(x: number, y: number): boolean {
239 const p = this.geo?.pool;
240 if (!p) return false;
241 return x >= p.x && x <= p.x + p.w && y >= p.y && y <= p.y + p.h;
242 }
243
244 /** Whether a tile let go of *here* has a clear line in. Not the same question
245 * as `canThrow(seat)`: a carried tile is wherever the player took it. */
246 canThrowFrom(x: number, y: number): boolean {
247 return !!this.geo && canThrowFrom(this.geo, { x, y });
248 }
249
250 /** Where the pool sits on the table, for the patch of it you can reach into. */
251 get poolRect(): Rect | null {
252 return this.geo?.pool ?? null;
253 }
254
255 /**
256 * Take hold of whatever discard is under the finger.
257 *
258 * The pile is a pile of tiles, so the thing you do to it is pick one up and
259 * put it somewhere else — which is what everybody does to a pool of discards
260 * while waiting for their turn. It comes up out of the pile and is carried
261 * over the top of it rather than ploughing through it.
262 */
263 grabAt(x: number, y: number): boolean {
264 if (!this.world) return false;
265 const b = tileAt(this.world, x, y);
266 if (!b) return false;
267 lift(b);
268 this.carried = b;
269 return true;
270 }
271
272 /** Follow the finger. A carried tile is placed, not pushed. */
273 dragTo(x: number, y: number, angle?: number) {
274 const b = this.carried;
275 if (!b) return;
276 b.x = x;
277 b.y = y;
278 if (angle !== undefined) b.angle = angle;
279 }
280
281 /**
282 * Let go. Slowly, and it is put down where it is; flicked, and it goes off
283 * across the felt at the speed it left the fingers — the same throw a tile
284 * gets out of a hand, made from the middle of the table instead.
285 */
286 releaseGrab(vx: number, vy: number, spin: number) {
287 const b = this.carried;
288 if (!b) return;
289 this.carried = null;
290 const speed = Math.hypot(vx, vy);
291 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
292 const flick = speed > DRAG_FLICK;
293 drop(b, flick ? vx * scale : 0, flick ? vy * scale : 0, flick ? spin : 0);
294 }
295
296 /** Whether a discard is in somebody's fingers right now. */
297 get dragging(): boolean {
298 return !!this.carried;
299 }
300
301 // ---- the tile in your fingers -----------------------------------------
302
303 /** Lifted out of a hand. From here the canvas draws it, not the DOM. */
304 pickUp(held: Held) {
305 this.held = held;
306 }
307
308 moveHeld(x: number, y: number, angle?: number) {
309 if (!this.held) return;
310 this.held.x = x;
311 this.held.y = y;
312 if (angle !== undefined) this.held.angle = angle;
313 }
314
315 /** Put it back in the hand — the throw was not committed to. */
316 cancelHeld() {
317 this.held = null;
318 }
319
320 /**
321 * Let go of it. The body is not made here: the reconciler owns every tile in
322 * the pool, so this leaves the throw where the next `sync` will find it and
323 * the caller goes on to call `game.discard`. The held tile stays drawn until
324 * that happens, so there is no frame with nothing on screen.
325 */
326 throwHeld(vx: number, vy: number, spin: number) {
327 const h = this.held;
328 if (!h) return;
329 const speed = Math.hypot(vx, vy);
330 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
331 this.release = {
332 seat: h.seat,
333 x: h.x,
334 y: h.y,
335 angle: h.angle,
336 w: h.w,
337 h: h.h,
338 vx: vx * scale,
339 vy: vy * scale,
340 spin,
341 };
342 this.releasedAt = Date.now();
343 }
344
345 /**
346 * A throw that is not a discard.
347 *
348 * The tile stays in the hand, the game does not move, and the body goes
349 * straight into the world rather than waiting for a discard to arrive and
350 * claim it. For throwing the same tile a hundred times with the colliders
351 * drawn, which is the only way to tell a bounce that is wrong from a bounce
352 * that only looks wrong.
353 */
354 throwLoose(vx: number, vy: number, spin: number) {
355 const h = this.held;
356 const geo = this.geo;
357 const world = this.world;
358 if (!h || !geo || !world) return;
359 const speed = Math.hypot(vx, vy);
360 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
361 this.loose.push(
362 this.fling(geo, h.tile, {
363 seat: h.seat,
364 x: h.x,
365 y: h.y,
366 angle: h.angle,
367 w: h.w,
368 h: h.h,
369 vx: vx * scale,
370 vy: vy * scale,
371 spin,
372 }),
373 );
374 // Oldest off the table first, or an afternoon of this buries the felt and
375 // every throw lands on a pile instead of on the thing being tested.
376 while (this.loose.length > LOOSE_LIMIT) this.drop(this.loose.shift()!);
377 this.held = null;
378 }
379
380 /** Sweep the sandbox's tiles away and start again. */
381 clearLoose() {
382 for (const b of this.loose) this.drop(b);
383 this.loose = [];
384 }
385
386 private drop(body: Body) {
387 const at = this.world?.bodies.indexOf(body) ?? -1;
388 if (at >= 0) this.world!.bodies.splice(at, 1);
389 }
390
391 /**
392 * A throw that happened on somebody's phone, arriving over the wire in their
393 * own frame: `u` along their edge, `vy` into the table. It is stood at their
394 * side of this screen and turned into the table's coordinates, so the tile
395 * flies in from off their edge — from where they are sitting, as a thrown
396 * tile should. The discard it belongs to arrives through the state as usual;
397 * this only decides how it enters.
398 */
399 throwFromNet(seat: SeatId, t: NetThrow) {
400 const geo = this.geo;
401 if (!geo) return;
402 const f = geo.felt;
403 // Just beyond the felt, where the thrower's strip is.
404 const m = geo.tile.h * 1.4;
405 const u = Math.min(1, Math.max(0, t.u));
406 let x: number;
407 let y: number;
408 let vx: number;
409 let vy: number;
410 // Each seat's frame: x runs to the player's right along their edge, y into
411 // the table. The screen rotation for each seat is what `ROT` says it is.
412 switch (seat) {
413 case 0:
414 x = f.x + u * f.w;
415 y = f.y + f.h + m;
416 vx = t.vx;
417 vy = -t.vy;
418 break;
419 case 1:
420 x = f.x + f.w + m;
421 y = f.y + (1 - u) * f.h;
422 vx = -t.vy;
423 vy = -t.vx;
424 break;
425 case 2:
426 x = f.x + (1 - u) * f.w;
427 y = f.y - m;
428 vx = -t.vx;
429 vy = t.vy;
430 break;
431 default:
432 x = f.x - m;
433 y = f.y + u * f.h;
434 vx = t.vy;
435 vy = t.vx;
436 break;
437 }
438 const speed = Math.hypot(vx, vy);
439 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
440 this.release = {
441 seat,
442 x,
443 y,
444 // Facing its thrower, the way a tile lifted from their hand would be.
445 angle: (SEAT_ROT[seat] * Math.PI) / 180,
446 w: geo.tile.w,
447 h: geo.tile.h,
448 vx: vx * scale,
449 vy: vy * scale,
450 spin: t.spin,
451 };
452 this.releasedAt = Date.now();
453 }
454
455 // ---- keeping up with the game ----------------------------------------
456
457 /** Bring the pile in line with the state. Cheap when nothing has changed. */
458 sync(state: GameState) {
459 this.remeasure(state);
460 const geo = this.geo;
461 const world = this.world;
462 if (!geo || !world) return;
463
464 // A new hand is a new pile, and nothing should fly anywhere.
465 const fresh = state.handNumber !== this.hand;
466 this.hand = state.handNumber;
467
468 const want = new Set<string>();
469 const added: { key: string; seat: SeatId; index: number; tile: Tile }[] = [];
470 for (const seat of SEATS) {
471 const discards = state.players[seat].discards;
472 for (let i = 0; i < discards.length; i++) {
473 const key = `${seat}:${i}`;
474 want.add(key);
475 if (!this.entries.has(key)) added.push({ key, seat, index: i, tile: discards[i] });
476 }
477 }
478
479 const taken: Body[] = [];
480 for (const [key, body] of this.entries) {
481 if (want.has(key)) continue;
482 const at = world.bodies.indexOf(body);
483 if (at >= 0) world.bodies.splice(at, 1);
484 // Claimed out from under the finger holding it.
485 if (this.carried === body) this.carried = null;
486 this.entries.delete(key);
487 taken.push(body);
488 }
489
490 // Exactly one tile off the table is somebody taking it — a 碰, a 吃, a 槓,
491 // or a discard being taken back. It goes to whoever now has a meld they did
492 // not have a moment ago, and failing that back to the seat that threw it,
493 // which is what an undo is. Several at once is the hand ending, and those
494 // simply go.
495 const claimer = SEATS.find((q) => state.players[q].melds.length > this.melds[q]);
496 this.melds = SEATS.map((q) => state.players[q].melds.length);
497 if (taken.length === 1 && !fresh) {
498 const to = geo.launch[claimer ?? taken[0].seat];
499 if (to) this.leaving.push({ body: taken[0], tx: to.x, ty: to.y, t: 0 });
500 }
501
502 // One tile at a time is somebody playing, and it gets thrown. Several at
503 // once is a pile being rebuilt — a save picked up, an undo, a fresh deal —
504 // and those tiles were thrown long ago, so they are simply already there.
505 const rebuilding = fresh || added.length > 1;
506 for (const a of added) {
507 this.entries.set(a.key, rebuilding ? this.settle(geo, state, a) : this.launch(geo, state, a));
508 }
509
510 // A throw is good for exactly one discard. At a local table the discard is
511 // in the state before the next frame, so the tile has either just arrived
512 // or is never going to; online it is out on a round-trip, so the release
513 // waits — but not forever, in case the host turned the move down.
514 if (added.length || (this.release && Date.now() - this.releasedAt > 2500)) {
515 this.release = null;
516 this.held = null;
517 }
518
519 const ld = state.lastDiscard;
520 this.newestKey = ld ? `${ld.from}:${state.players[ld.from].discards.length - 1}` : null;
521 }
522
523 /** Run the physics on. Returns impacts worth a sound. */
524 advance(seconds: number, stopOnImpact = false): Impact[] {
525 this.carryOff(seconds);
526 return this.world ? advanceWorld(this.world, seconds, stopOnImpact) : [];
527 }
528
529 /** Tiles leaving the table, lifted and carried off to the seat taking them. */
530 private carryOff(seconds: number) {
531 if (this.leaving.length === 0) return;
532 for (const l of this.leaving) {
533 l.t = Math.min(1, l.t + seconds / TAKE_FLIGHT);
534 // Ease out, so it leaves quickly and arrives gently.
535 const k = 1 - (1 - l.t) * (1 - l.t);
536 l.body.x += (l.tx - l.body.x) * k * 0.5;
537 l.body.y += (l.ty - l.body.y) * k * 0.5;
538 // Up off the table on the way, the way a tile picked up would be.
539 l.body.z = Math.sin(l.t * Math.PI) * 40;
540 l.body.angle += seconds * 2.2;
541 }
542 this.leaving = this.leaving.filter((l) => l.t < 1);
543 }
544
545 /** What is on its way off, and how far gone, for the renderer to fade. */
546 get departing(): { body: Body; fade: number }[] {
547 return this.leaving.map((l) => ({ body: l.body, fade: 1 - l.t }));
548 }
549
550 get bodies(): Body[] {
551 return this.world?.bodies ?? [];
552 }
553
554 /** The tile on the table, if there is one — drawn lit, as a lifted tile is. */
555 get newest(): Body | null {
556 return (this.newestKey && this.entries.get(this.newestKey)) || null;
557 }
558
559 /**
560 * A tile is still on its way to the middle. The computer players hold off
561 * while this is true — nobody at a real table reaches across for a tile that
562 * has not landed, and a 碰 called over one still turning over in the air looks
563 * like it was snatched out of flight.
564 */
565 get throwInFlight(): boolean {
566 const b = this.newest;
567 return !!b && !b.resting;
568 }
569
570 /**
571 * Somebody is being told off for where they put that tile. Held for as long
572 * as the line takes to say, told to us by whoever is saying it.
573 */
574 heckle(seconds: number) {
575 this.quietAt = Math.max(this.quietAt, Date.now() + seconds * 1000);
576 }
577
578 /**
579 * Whether the table is mid-something and a computer player should wait: a
580 * tile still in the air, or a player still complaining about the last one.
581 * Reaching for a tile over the top of somebody objecting to it lands the
582 * objection on nobody.
583 */
584 get busy(): boolean {
585 return this.throwInFlight || Date.now() < this.quietAt;
586 }
587
588 /** Nothing is moving, so the render loop can stop until something changes. */
589 get settled(): boolean {
590 return (
591 !this.held &&
592 !this.carried &&
593 this.leaving.length === 0 &&
594 (!this.world || settled(this.world))
595 );
596 }
597
598 // ---- measuring ---------------------------------------------------------
599
600 /**
601 * Re-read the table when the wall's shape has changed or the window has. The
602 * pile keeps its positions across a re-measure: the wall shrinking does not
603 * move the tiles already on the felt.
604 */
605 private remeasure(state: GameState) {
606 const table = this.table;
607 if (!table) return;
608 // Every tile on the table is a collider now, so the shape of each hand and
609 // each set laid down is part of what has to be re-read — not just the wall.
610 const hands = state.players.map((p) => `${p.hand.length}.${p.melds.length}.${p.flowers.length}`);
611 const stamp = `${state.drawnFront}/${state.drawnBack}/${hands.join(',')}/${Math.round(
612 table.clientWidth,
613 )}x${Math.round(table.clientHeight)}`;
614 if (stamp === this.measuredAt) return;
615
616 const geo = measure(table);
617 this.measuredAt = geo ? stamp : '';
618 this.geo = geo;
619 if (!geo) {
620 this.world = null;
621 this.entries.clear();
622 this.setOpenness('----');
623 return;
624 }
625 // What keeps a tile in is the tiles: the stacks still standing, the sets
626 // laid down, and the hands beyond them. `felt` is the table's own edge and
627 // is only there so a tile that got past all of that is still on the table.
628 if (!this.world) this.world = createWorld(geo.felt, geo.barriers);
629 else reshape(this.world, geo.felt, geo.barriers);
630 // Only here, never per frame: a hundred-odd ray casts is nothing once a
631 // draw, and a great deal every sixtieth of a second.
632 this.setOpenness(SEATS.map((s) => (canThrow(geo, s) ? 'y' : '-')).join(''));
633 }
634
635 private setOpenness(next: string) {
636 if (next === this.openness) return;
637 this.openness = next;
638 for (const cb of this.listeners) cb();
639 }
640
641 // ---- putting tiles in -------------------------------------------------
642
643 /** A tile that is simply there already — a rebuilt pile. */
644 private settle(
645 geo: TableGeometry,
646 state: GameState,
647 a: { seat: SeatId; index: number; tile: Tile },
648 ): Body {
649 const rng = this.seeded(state, a);
650 const { pool } = geo;
651 // Bunched towards the middle rather than spread evenly to the edges, which
652 // is what a pool thrown into from four sides actually looks like.
653 const spread = 0.3;
654 return addBody(this.world!, {
655 tile: a.tile,
656 seat: a.seat,
657 x: pool.x + pool.w * (0.5 + (rng() - 0.5) * 2 * spread),
658 y: pool.y + pool.h * (0.5 + (rng() - 0.5) * 2 * spread),
659 vx: 0,
660 vy: 0,
661 z: 0,
662 vz: 0,
663 angle: (rng() - 0.5) * Math.PI,
664 spin: 0,
665 w: geo.tile.w,
666 h: geo.tile.h,
667 atRest: true,
668 });
669 }
670
671 /**
672 * A tile let go of by a hand: what a flick actually becomes.
673 *
674 * Its own method because a throw is not always a discard — the sandbox
675 * behind ?colliders throws the same tile over and over without the game
676 * moving at all, and it has to be the *same* throw or there would be no
677 * point testing with it.
678 */
679 private fling(geo: TableGeometry, tile: Tile, thrown: Release): Body {
680 // The flick is the throw. Where the tile goes and how fast it gets there
681 // are both the hand's business, and nothing here touches either — a tile
682 // that leaves at an angle to the flick that made it reads as a bounce off
683 // something invisible, and there is nothing there to bounce off.
684 //
685 // The one thing still decided here is *height*, which is not aim. With a
686 // standing wall in front of the throw a flat tile would only skid into it,
687 // so it is lofted over instead: exactly as far as it was thrown, simply in
688 // the air for the first part of the way. A tile that carries past the
689 // square and out into the open stays there — the middle is not a box, and
690 // where a discard came to rest is where somebody threw it.
691 //
692 // Asked from where the tile actually *is*, not from the seat: a player who
693 // carried it out over the square has a clear line even though the seat they
694 // came from does not.
695 const set = this.inPool(thrown.x, thrown.y);
696 const walled = !set && LOB_WHEN_WALLED && !this.canThrowFrom(thrown.x, thrown.y);
697 const { vx, vy } = thrown;
698 let vz = 0;
699 const speed = Math.hypot(vx, vy);
700 let flipTurns = 0;
701 let flipOver = 0;
702 let how = set ? 'slide, from inside the square' : 'slide';
703
704 if (walled) {
705 how = 'lob — over the wall, same line';
706 vz = liftFor(PLACE_FLIGHT);
707 // Long enough in the air to turn over properly, and harder means more.
708 flipOver = PLACE_FLIGHT;
709 flipTurns = speed > 1300 ? 2 : 1;
710 } else if (!set) {
711 // A skated tile leaves the fingers off the cloth, and turns over on its
712 // way down — harder means longer in the air and more turns in it.
713 const hop = THROW_LIFT + Math.min(0.22, (speed / MAX_THROW_SPEED) * 0.28);
714 vz = liftFor(hop);
715 flipOver = hop;
716 flipTurns = speed > 2200 ? 2 : speed > 600 ? 1 : 0;
717 }
718 if (!TUMBLE) flipTurns = 0;
719
720 this.throws.push({ x: thrown.x, y: thrown.y, fx: thrown.vx, fy: thrown.vy, vx, vy, how });
721 if (this.throws.length > 6) this.throws.shift();
722
723 return addBody(this.world!, {
724 tile: tile,
725 seat: thrown.seat,
726 x: thrown.x,
727 y: thrown.y,
728 vx,
729 vy,
730 z: 0,
731 vz,
732 angle: thrown.angle,
733 spin: thrown.spin,
734 flipTurns,
735 flipOver,
736 // It tumbles across its line of travel, the way a thrown tile does.
737 flipAxis: Math.atan2(vy, vx),
738 w: geo.tile.w,
739 h: geo.tile.h,
740 // It was drawn at hand size a moment ago; it shrinks on the way down.
741 scale: thrown.w / geo.tile.w,
742 });
743 }
744
745 /** A tile arriving now: thrown if somebody threw it, placed over the wall if
746 * it was tapped, and flat and quick if a bot's wall happens to be open. */
747 private launch(
748 geo: TableGeometry,
749 state: GameState,
750 a: { seat: SeatId; index: number; tile: Tile },
751 ): Body {
752 const rng = this.seeded(state, a);
753 const thrown = this.release?.seat === a.seat ? this.release : null;
754
755 if (thrown) return this.fling(geo, a.tile, thrown);
756
757 // Off the end of the hand, not the middle of it — a tile is thrown from the
758 // hand holding it, which is the one at the right-hand end of the row.
759 const from = geo.throwFrom[a.seat] ?? geo.launch[a.seat] ?? centreOf(geo.pool);
760 const open = !LOB_WHEN_WALLED || this.canThrow(a.seat);
761 const target = this.aimFor(geo, a.seat, rng);
762 const flight = open ? 0.34 + rng() * 0.1 : PLACE_FLIGHT;
763 // A slide is aimed at where it comes to *rest*, since it keeps going after
764 // it lands and SLIDE_TIME is roughly how much further. A lob is aimed at
765 // where it touches *down*, because it has to come down on the inside of the
766 // wall — solving for the resting place lands it short, against the outside.
767 const reach = open ? flight + SLIDE_TIME : flight;
768
769 const vx = (target.x - from.x) / reach;
770 const vy = (target.y - from.y) / reach;
771 return addBody(this.world!, {
772 tile: a.tile,
773 seat: a.seat,
774 x: from.x,
775 y: from.y,
776 vx,
777 vy,
778 z: 0,
779 vz: liftFor(flight),
780 angle: (rng() - 0.5) * Math.PI,
781 spin: (rng() - 0.5) * (open ? 7 : 2.5),
782 // It turns over on its way in, whichever way it is going.
783 flipTurns: TUMBLE ? 1 : 0,
784 flipOver: flight,
785 flipAxis: Math.atan2(vy, vx),
786 w: geo.tile.w,
787 h: geo.tile.h,
788 });
789 }
790
791 /** Where a tile from this seat is headed, with a little scatter. */
792 private aimFor(geo: TableGeometry, seat: SeatId, rng: () => number): Point {
793 const base = aimAt(geo, seat) ?? centreOf(geo.pool);
794 const jitter = Math.min(geo.pool.w, geo.pool.h) * 0.22;
795 return { x: base.x + (rng() - 0.5) * jitter, y: base.y + (rng() - 0.5) * jitter };
796 }
797
798 /**
799 * A tile's own random stream. Keyed on the hand and its place in that seat's
800 * discards, so the same tile scatters the same way every time it is rebuilt —
801 * a refresh mid-hand puts the pile back exactly as it was.
802 */
803 private seeded(state: GameState, a: { seat: SeatId; index: number; tile: Tile }) {
804 return makeRng(state.handNumber * 7919 + a.seat * 977 + a.index * 31 + a.tile + 1);
805 }
806}