anvilsign in

collin/mahjong

1import { isBarrier, wallStacks, type WallProgress } from '../game/wall';
2import type { SeatId } from '../game/types';
3import type { Rect } from './physics';
4
5/**
6 * Where everything on the table actually is, in pixels.
7 *
8 * The wall's size lives entirely in CSS — `--ws` and `--wd` in styles.css work
9 * it out from the tile, and how much of it there is to lay out is decided in
10 * `game/wall.ts` — so rather than restate any of that here and let them drift
11 * apart, this *measures* what came out.
12 * `WallRing` renders every stack as a real element tagged with its index, so the
13 * colliders come from `getBoundingClientRect()` on the things already on screen.
14 * That is the whole mapping from the HTML to the physics.
15 *
16 * Measuring is one layout flush over ~74 elements. It happens when the window
17 * resizes and when the wall's shape changes, never per frame.
18 */
19
20const SEATS: SeatId[] = [0, 1, 2, 3];
21
22export interface TableGeometry {
23 /** Table size, world units — the world's origin is the table's top left. */
24 size: { w: number; h: number };
25 /** Inside the wall square: where a discard is aimed, and where a rebuilt pile
26 * is laid out. Not a fence — see `felt`. */
27 pool: Rect;
28 /**
29 * The whole middle of the table, between the four strips. This is what
30 * actually stops a tile, because the square is not a box: it is eighteen
31 * stacks a side, and once they have been drawn there is nothing there. A tile
32 * is held in by the stacks still standing, and by the edge of the felt beyond
33 * them — so as the wall is eaten away the pool spills out through the gaps,
34 * exactly as it does on a table.
35 */
36 felt: Rect;
37 /** Stacks of two still standing. Half stacks are low enough to throw over. */
38 walls: Rect[];
39 /** A tile in the pool is the same tile that was in the wall. */
40 tile: { w: number; h: number };
41 /** The middle of each seat's hand, if that seat's hand is on screen. */
42 launch: Partial<Record<SeatId, Point>>;
43 /** The right-hand end of each seat's hand, which is where a tile is thrown
44 * from: the tile just drawn sits there, and that is the hand you throw with. */
45 throwFrom: Partial<Record<SeatId, Point>>;
46}
47
48export interface Point {
49 x: number;
50 y: number;
51}
52
53/**
54 * Read the table. Returns null when there is no wall square to measure — the
55 * compact layout has none, and neither does a table that has not laid out yet.
56 */
57export function measure(table: HTMLElement, state: WallProgress): TableGeometry | null {
58 const ring = table.querySelector<HTMLElement>('.wall-ring');
59 if (!ring) return null;
60
61 const base = table.getBoundingClientRect();
62 if (base.width === 0 || base.height === 0) return null;
63 const local = (r: DOMRect): Rect => ({
64 x: r.left - base.left,
65 y: r.top - base.top,
66 w: r.width,
67 h: r.height,
68 });
69
70 const stacks = wallStacks(state);
71 const walls: Rect[] = [];
72 // A stack element is --ws by --wd (or the other way round on the left and
73 // right sides), so its narrower side is the tile's width whichever wall it is
74 // in — the fallback for sizing a pool tile before any hand has been dealt.
75 // The probe is one cell that is always there, spent wall or not.
76 const probe = ring.querySelector<HTMLElement>('.wall-probe')?.getBoundingClientRect();
77 let short = probe ? Math.min(probe.width, probe.height) : 0;
78 for (const el of ring.querySelectorAll<HTMLElement>('[data-stack]')) {
79 const i = Number(el.dataset.stack);
80 const r = local(el.getBoundingClientRect());
81 short = Math.max(short, Math.min(r.w, r.h));
82 const stack = stacks[i];
83 if (stack && isBarrier(stack)) walls.push(r);
84 }
85 if (short === 0) return null;
86
87 // `.wall-ring` is the opening itself — the walls hang off its edges — so the
88 // pool is simply its box. (It used to be the wall's outside, which is why this
89 // had to subtract the wall's own thickness.)
90 const ringRect = local(ring.getBoundingClientRect());
91 const pool: Rect = {
92 x: ringRect.x,
93 y: ringRect.y,
94 w: Math.max(short, ringRect.w),
95 h: Math.max(short, ringRect.h),
96 };
97
98 const launch: Partial<Record<SeatId, Point>> = {};
99 const throwFrom: Partial<Record<SeatId, Point>> = {};
100 for (const seat of SEATS) {
101 const hand = table.querySelector<HTMLElement>(`[data-seat="${seat}"] .hand`);
102 if (!hand) continue;
103 const r = hand.getBoundingClientRect();
104 if (r.width === 0 && r.height === 0) continue;
105 // A rotated element's bounding box is still centred on the element, so this
106 // is the right point whichever edge the seat is sitting at.
107 launch[seat] = { x: r.left + r.width / 2 - base.left, y: r.top + r.height / 2 - base.top };
108
109 // The end of the row rather than the middle of it. That is where the tile
110 // just drawn is sitting and which hand it is in, so it is where a throw
111 // comes from — measured off the last cell, so it is the right end of the
112 // *row* whichever way round the seat is turned.
113 const end = hand.querySelector<HTMLElement>('.hand-cell:last-child');
114 const er = end?.getBoundingClientRect();
115 throwFrom[seat] = er
116 ? { x: er.left + er.width / 2 - base.left, y: er.top + er.height / 2 - base.top }
117 : launch[seat];
118 }
119
120 // The felt is the centre element's own box — the area the four strips leave.
121 const centre = table.querySelector<HTMLElement>('.center');
122 const felt = centre ? local(centre.getBoundingClientRect()) : ringRect;
123
124 return {
125 size: { w: base.width, h: base.height },
126 pool,
127 felt,
128 walls,
129 tile: poolTile(table, short),
130 launch,
131 throwFrom,
132 };
133}
134
135/**
136 * How big a tile in the middle is drawn: the same size as the tiles being
137 * played with.
138 *
139 * It used to be the size of a tile in the wall, which is much smaller, and that
140 * was a mistake you could see rather than measure — a tile thrown from a hand
141 * shrank as it crossed the table, so it read as being dropped away from you into
142 * the distance rather than skidded across a flat one. They are the same tiles,
143 * so they are the same size.
144 *
145 * A seat's strip is rotated by a right angle, which swaps its bounding box, and
146 * a tile is always taller than it is wide — so the narrower side is the width
147 * whichever edge is measured. Falls back to the wall's own tile if no hand has
148 * been dealt yet.
149 */
150function poolTile(table: HTMLElement, fallback: number): { w: number; h: number } {
151 const el = table.querySelector<HTMLElement>('.hand .tile');
152 const r = el?.getBoundingClientRect();
153 const w = r && r.width > 0 ? Math.min(r.width, r.height) : fallback;
154 return { w, h: w * 1.375 };
155}
156
157export const centreOf = (r: Rect): Point => ({ x: r.x + r.w / 2, y: r.y + r.h / 2 });
158
159/**
160 * Whether a seat has a clear line into the middle — the throw gate.
161 *
162 * Not a rule bolted on beside the physics; it *is* the physics, asked ahead of
163 * time. While a standing stack of two is between a seat and the pool, a tile
164 * flicked from there would hit it, so the seat cannot throw and has to place the
165 * tile over the wall instead (tap-tap, or 打出). As the hand eats the square,
166 * gaps open and seats come good one at a time.
167 *
168 * Aim is not just dead ahead: a fan of lines spread across the pool means a gap
169 * off to one side counts, which is how you would actually throw it.
170 */
171export function canThrow(geo: TableGeometry, seat: SeatId): boolean {
172 const from = throwsFrom(geo, seat);
173 return !!from && canThrowFrom(geo, from);
174}
175
176/**
177 * Where a tile this seat plays actually starts from — the end of the row, not
178 * the middle of it. The same point `pool.ts` launches from, and it has to be:
179 * asking whether the line is clear from somewhere the tile is not is how a tile
180 * gets waved through and then stopped dead by a stack it was never clear of.
181 */
182const throwsFrom = (geo: TableGeometry, seat: SeatId): Point | undefined =>
183 geo.throwFrom[seat] ?? geo.launch[seat];
184
185/**
186 * The same question asked from a particular point rather than from a seat.
187 *
188 * This is the one that matters for a tile somebody is holding: they have picked
189 * it up and can carry it anywhere, so what decides whether it can be slid in is
190 * the line from wherever they let go of it — not the line from the hand it came
191 * out of. Judging a throw released out over the square by the view from the
192 * player's own edge called almost everything a lob.
193 */
194export function canThrowFrom(geo: TableGeometry, from: Point): boolean {
195 if (inRect(geo.pool, from)) return true;
196 return aimPoints(geo).some((to) => clearLine(geo.walls, from, to));
197}
198
199export const inRect = (r: Rect, p: Point) =>
200 p.x >= r.x && p.x <= r.x + r.w && p.y >= r.y && p.y <= r.y + r.h;
201
202/** Somewhere in the pool this seat could actually get a tile to, or null. */
203export function aimAt(geo: TableGeometry, seat: SeatId): Point | null {
204 const from = throwsFrom(geo, seat);
205 if (!from) return null;
206 const open = aimPoints(geo).filter((to) => clearLine(geo.walls, from, to));
207 if (open.length === 0) return null;
208 // The most central thing reachable, so a tile lands among the others rather
209 // than hugging whichever edge it squeezed past.
210 const c = centreOf(geo.pool);
211 return open.reduce((best, p) =>
212 Math.hypot(p.x - c.x, p.y - c.y) < Math.hypot(best.x - c.x, best.y - c.y) ? p : best,
213 );
214}
215
216/**
217 * Landing spots to try for: a grid over the whole pool, not a line through its
218 * middle.
219 *
220 * A throw only has to *get inside* the square — once past the wall the tile
221 * slides to a stop wherever it ends up. So the near corners matter as much as
222 * the centre, and they matter more: they sit much closer to the seat, which is
223 * what makes a gap well off to one side worth aiming through at all. Aiming
224 * only at the middle would call a seat walled in when it plainly is not.
225 */
226function aimPoints(geo: TableGeometry): Point[] {
227 const { x, y, w, h } = geo.pool;
228 // Fine rather than coarse, and it costs nothing: this runs once when a tile
229 // is let go of, not per frame. A sparse grid missed narrow gaps and called a
230 // throw impossible when a tile would plainly have gone through, and sliding is
231 // what a discard should be whenever it can be.
232 const steps = [0.06, 0.2, 0.35, 0.5, 0.65, 0.8, 0.94];
233 const out: Point[] = [];
234 for (const u of steps) for (const v of steps) out.push({ x: x + w * u, y: y + h * v });
235 return out;
236}
237
238/** Segment against every standing stack, by the slab method. */
239function clearLine(walls: Rect[], from: Point, to: Point): boolean {
240 return !walls.some((w) => segmentHitsRect(from, to, w));
241}
242
243export function segmentHitsRect(a: Point, b: Point, r: Rect): boolean {
244 const dx = b.x - a.x;
245 const dy = b.y - a.y;
246 let t0 = 0;
247 let t1 = 1;
248
249 // Each axis clips the span of the segment that could still be inside.
250 const slab = (p: number, d: number, lo: number, hi: number): boolean => {
251 if (Math.abs(d) < 1e-9) return p >= lo && p <= hi;
252 const near = (lo - p) / d;
253 const far = (hi - p) / d;
254 t0 = Math.max(t0, Math.min(near, far));
255 t1 = Math.min(t1, Math.max(near, far));
256 return t1 >= t0;
257 };
258
259 if (!slab(a.x, dx, r.x, r.x + r.w)) return false;
260 if (!slab(a.y, dy, r.y, r.y + r.h)) return false;
261 return t1 >= t0;
262}