anvilsign in

collin/mahjong

1import type { Tile } from '../game/tiles';
2import type { SeatId } from '../game/types';
3
4/**
5 * The tiles in the middle of the table, as things with weight.
6 *
7 * Pure and deterministic: no DOM, no clock, no randomness. Where the world's
8 * measurements come from is `geometry.ts`; what gets thrown into it and when is
9 * `pool.ts`; drawing it is `ui/Pool.tsx`. Anything random — the scatter on a
10 * placed tile, where a rebuilt pile's tiles sit — is decided by the caller and
11 * arrives as a spawn impulse, which is what lets the same hand come back to the
12 * same pile after a refresh.
13 *
14 * Tiles are rectangles and they are solved as rectangles: two of them can lean
15 * against each other at any angle but never share the same ground. Everything is
16 * in CSS pixels, table-local, and seconds.
17 */
18
19/** One fixed step. Small enough that a hard flick can't tunnel a wall. */
20export const FIXED_DT = 1 / 120;
21/**
22 * Most catch-up a single frame will simulate. A tab that was in the background
23 * for a minute comes back to a settled pile, not to a spin through 7200 steps.
24 */
25const MAX_SUBSTEPS = 8;
26
27/** Falls onto the felt in about half a second from a normal throw. */
28const GRAVITY = 2600;
29/** Tiles are dense and land flat; they do not bounce much. */
30const Z_RESTITUTION = 0.34;
31/** Below this the tile is flat on the felt: sliding, and in the way of others. */
32const ON_FELT = 8;
33/**
34 * How high a standing stack of two reaches. A tile still above this sails over
35 * the wall — which is exactly what a *placed* tile does, and what a thrown one
36 * must not need to do.
37 */
38export const WALL_HEIGHT = 30;
39
40/**
41 * Felt friction: an exponential part that kills speed, and a constant part that
42 * actually brings it to a stop rather than to an asymptote.
43 *
44 * Deliberately light. A tile thrown hard should cross the square, come off the
45 * far side and barge through what is already lying there before it settles —
46 * heavier friction ate the throw in the first few inches and every discard
47 * ended up looking the same however it was let go of.
48 */
49const FELT_DAMP = 2.6;
50const FELT_STOP = 70;
51const SPIN_DAMP = 3.4;
52const SPIN_STOP = 0.9;
53
54/**
55 * Roughly how much longer a tile keeps travelling after it lands, as a time.
56 * Aiming a throw means solving for where it comes to *rest*, not where it first
57 * touches down, so `pool.ts` adds this to the flight time.
58 */
59export const SLIDE_TIME = 1 / FELT_DAMP;
60
61/** Off the inside of the wall square, and off another tile. Bouncy enough that
62 * a hard throw ricochets instead of sticking where it first lands. */
63const BOUND_RESTITUTION = 0.55;
64const BOUND_FRICTION = 0.9;
65const TILE_RESTITUTION = 0.42;
66/** How much of a glancing blow becomes spin. Tiles are light and skate. */
67const SPIN_TRANSFER = 0.06;
68
69/** Asleep after this many consecutive steps of going nowhere. */
70const SLEEP_SPEED = 7;
71const SLEEP_SPIN = 0.2;
72const SLEEP_STEPS = 10;
73/**
74 * Overlap small enough to live with. Without this a crowded pool never sleeps:
75 * a tile squeezed between its neighbours and the pool's edge gets pushed out of
76 * contact and shoved back into it on every step, for ever. A fifth of a pixel is
77 * not something you can see, and it is what lets the pile go quiet.
78 */
79const CONTACT_SLOP = 0.2;
80/**
81 * A body moving this slowly for this long is put to sleep whatever it thinks it
82 * is doing. The backstop that guarantees the pile always settles — counted from
83 * when it last woke, not from when it was thrown.
84 */
85const AWAKE_LIMIT = 600;
86
87/** Pulls a tile that landed short of the pool in towards the rest of them. */
88const ENTRY_PULL = 700;
89/**
90 * How long a tile gets to find its own way into the pool before it is simply
91 * put there. A discard is game state made visible — it has to be in the middle
92 * where it can be seen and counted — so a tile that has got itself wedged
93 * against a standing stack, or is bouncing between two of them, cannot be left
94 * out there. Two seconds is far longer than any real throw takes to settle.
95 */
96const ENTRY_GRACE = 240;
97
98/**
99 * How hard a tile that merely *arrived* counts as having arrived: enough for
100 * the seat it came in past to notice, deliberately under the threshold the
101 * renderer plays a clack at. Nothing was hit, so nothing should be heard.
102 */
103const ARRIVED = 0.1;
104
105/** How fast a tile drawn at hand size shrinks to the size it is in the pool. */
106const SCALE_EASE = 6;
107
108/** Washing the tiles about: how much of a finger's speed a tile takes on, how
109 * hard it is nudged clear, and the fastest shove it will pass on. */
110const STIR_DRAG = 0.55;
111const STIR_NUDGE = 30;
112const STIR_MAX_SPEED = 1500;
113
114export const TAU = Math.PI * 2;
115/**
116 * How quickly whatever is left of a tumble is taken up once the tile is down.
117 * A thrown tile turns over in the air a whole number of times, so it should be
118 * face up as it lands — but a bounce or a shove can leave it part-way round, and
119 * a mahjong tile on a table is never resting on its face. This takes up the
120 * remainder, and `sleep` guarantees the rest.
121 */
122const FLIP_SETTLE = 14;
123
124export interface Rect {
125 x: number;
126 y: number;
127 w: number;
128 h: number;
129}
130
131/** Anything the collision routines can treat as a rotated rectangle. */
132interface Box {
133 x: number;
134 y: number;
135 w: number;
136 h: number;
137 angle: number;
138}
139
140export interface Body {
141 tile: Tile;
142 /** Who threw it — for the fly-out when it is claimed, not for any marking. */
143 seat: SeatId;
144 /** Centre on the felt plane. */
145 x: number;
146 y: number;
147 vx: number;
148 vy: number;
149 /** Height above the felt, and its rate. Only ever >= 0. */
150 z: number;
151 vz: number;
152 angle: number;
153 spin: number;
154 /**
155 * Turning over in the air, about an axis lying in the table — what a thrown
156 * tile does, as opposed to `angle`, which is it turning flat on the cloth.
157 * Zero, or any whole number of turns, is face up.
158 */
159 flip: number;
160 flipSpin: number;
161 /** Which way that axis points: a tile tumbles across its line of travel. */
162 flipAxis: number;
163 w: number;
164 h: number;
165 /**
166 * Render-only: what to multiply the drawn size by, easing to 1. A tile is
167 * drawn big in a hand so it can be read, and small in the pool because that is
168 * the size it is in the wall, so a thrown one has to settle from one to the
169 * other. Eased here rather than in the renderer so it does not run at a
170 * different speed on a different frame rate.
171 */
172 scale: number;
173 /**
174 * Whether it has ever been inside the pool. Until it has, it is free to fly
175 * over the wall from a seat's edge; once it has, the pool keeps it.
176 */
177 entered: boolean;
178 /**
179 * Which side of the table it is still on its way in over. Every tile is
180 * thrown from outside, so every tile has one until it lands; it is what the
181 * table reports when the tile finally gets in, since by then there is no
182 * longer an edge to read off its position.
183 */
184 over?: Edge;
185 resting: boolean;
186 /** Consecutive slow steps, counting towards sleep. */
187 still: number;
188 /** Steps lived, for the grace period on getting into the pool. */
189 age: number;
190 /** Steps since it last woke, for the backstop on settling. */
191 awake: number;
192}
193
194/**
195 * Which edge of the middle a tile ran into. The middle stops where the four
196 * players' tiles start, so an edge is somebody's hand: a tile that reaches one
197 * hard has been thrown into their tiles, and they have something to say about
198 * it. Seats are the caller's business; this only says which way it went off.
199 */
200export type Edge = 'left' | 'right' | 'top' | 'bottom';
201
202/** A collision loud enough to hear. `strength` is 0..1. */
203export interface Impact {
204 x: number;
205 y: number;
206 strength: number;
207 /** Set when it was the edge of the table it hit, not a wall or another tile. */
208 edge?: Edge;
209 /** Whose tiles it ran into, where what it hit belonged to somebody. */
210 into?: SeatId;
211 /** Whose discard it was — you cannot be barged by your own tile. */
212 seat?: SeatId;
213}
214
215/**
216 * Something solid on the table. Everything that stops a tile is another tile:
217 * the stacks still standing in the wall, the sets people have laid down, and
218 * the sixteen everyone is holding. `seat` is whose it is, where it is somebody's
219 * — a tile thrown into a hand is a thing that hand's owner answers.
220 */
221export interface Barrier {
222 rect: Rect;
223 seat?: SeatId;
224}
225
226export interface World {
227 /** Where tiles come to rest — inside the wall square. */
228 bounds: Rect;
229 /** Stacks of two still standing. Half and spent stacks are not obstacles. */
230 walls: Barrier[];
231 bodies: Body[];
232 /** Left-over time from the last frame, so steps stay a fixed size. */
233 carry: number;
234 /**
235 * Overlaps pushed apart in the last step. The pile is not settled while this
236 * is non-zero, however still everything looks — two tiles asleep inside each
237 * other would otherwise stay that way for the rest of the hand, because a
238 * pile that has stopped moving stops being stepped.
239 */
240 contacts: number;
241 /** Steps spent untangling a pile that is otherwise asleep, so it cannot spin. */
242 relaxed: number;
243}
244
245export interface Spawn {
246 tile: Tile;
247 seat: SeatId;
248 x: number;
249 y: number;
250 vx: number;
251 vy: number;
252 z: number;
253 vz: number;
254 angle: number;
255 spin: number;
256 /** Whole turns to make in the air. It lands face up whatever this is. */
257 flipTurns?: number;
258 /** Seconds of flight those turns are spread over. */
259 flipOver?: number;
260 flipAxis?: number;
261 w: number;
262 h: number;
263 /** Drawn this much bigger to start with, easing to its pool size. */
264 scale?: number;
265 /** Already settled — a pile being rebuilt after a reload or an undo. */
266 atRest?: boolean;
267}
268
269export function createWorld(bounds: Rect, walls: Barrier[] = []): World {
270 return { bounds, walls, bodies: [], carry: 0, contacts: 0, relaxed: 0 };
271}
272
273export function addBody(world: World, s: Spawn): Body {
274 const body: Body = {
275 tile: s.tile,
276 seat: s.seat,
277 x: s.x,
278 y: s.y,
279 vx: s.atRest ? 0 : s.vx,
280 vy: s.atRest ? 0 : s.vy,
281 z: s.atRest ? 0 : s.z,
282 vz: s.atRest ? 0 : s.vz,
283 angle: s.angle,
284 spin: s.atRest ? 0 : s.spin,
285 flip: 0,
286 // Spread the turns over the flight, so the tile comes down as it comes back
287 // round to face up rather than being snapped there on landing.
288 flipSpin:
289 s.atRest || !s.flipTurns || !s.flipOver ? 0 : (TAU * s.flipTurns) / s.flipOver,
290 flipAxis: s.flipAxis ?? 0,
291 w: s.w,
292 h: s.h,
293 scale: s.atRest ? 1 : s.scale ?? 1,
294 entered: !!s.atRest,
295 resting: !!s.atRest,
296 still: s.atRest ? SLEEP_STEPS : 0,
297 age: 0,
298 awake: 0,
299 };
300 world.bodies.push(body);
301 if (s.atRest) {
302 // A tile dropped straight into a settled pile still has to make room. This
303 // is a first shove only — the relaxing below finishes the job, which matters
304 // for a whole pile rebuilt at once when a saved game is picked up.
305 separate(world, body);
306 world.contacts++;
307 }
308 return body;
309}
310
311// ---- rotated rectangles ---------------------------------------------------
312
313/** Distance from a box's centre to its edge, measured along `ax`. */
314function reach(b: Box, ax: { x: number; y: number }): number {
315 const c = Math.cos(b.angle);
316 const s = Math.sin(b.angle);
317 return (
318 Math.abs(c * ax.x + s * ax.y) * (b.w / 2) + Math.abs(-s * ax.x + c * ax.y) * (b.h / 2)
319 );
320}
321
322/** The rotated rectangle's own bounding box, for the pool's straight edges. */
323function aabbHalf(b: Box) {
324 const c = Math.abs(Math.cos(b.angle));
325 const s = Math.abs(Math.sin(b.angle));
326 return { x: (b.w / 2) * c + (b.h / 2) * s, y: (b.w / 2) * s + (b.h / 2) * c };
327}
328
329/** Enough to skip a pair without doing the real work. */
330const circumradius = (b: Box) => Math.hypot(b.w, b.h) / 2;
331
332/**
333 * Separating axis test between two rectangles at any angle. Returns the
334 * shallowest way out — the direction to push `b` away from `a`, and by how much
335 * — or null if they are clear of each other.
336 *
337 * Four axes is all a pair of rectangles needs: each box's two edge normals.
338 */
339function overlapOf(a: Box, b: Box): { nx: number; ny: number; depth: number } | null {
340 const ca = Math.cos(a.angle);
341 const sa = Math.sin(a.angle);
342 const cb = Math.cos(b.angle);
343 const sb = Math.sin(b.angle);
344 const axes = [
345 { x: ca, y: sa },
346 { x: -sa, y: ca },
347 { x: cb, y: sb },
348 { x: -sb, y: cb },
349 ];
350
351 const dx = b.x - a.x;
352 const dy = b.y - a.y;
353 let depth = Infinity;
354 let nx = 0;
355 let ny = 0;
356
357 for (const ax of axes) {
358 const gap = reach(a, ax) + reach(b, ax) - Math.abs(dx * ax.x + dy * ax.y);
359 if (gap <= 0) return null;
360 if (gap < depth) {
361 depth = gap;
362 // Always pointing from a towards b, so callers need not guess.
363 const sign = dx * ax.x + dy * ax.y < 0 ? -1 : 1;
364 nx = ax.x * sign;
365 ny = ax.y * sign;
366 }
367 }
368 return { nx, ny, depth };
369}
370
371/** A standing stack, as something the tests above can chew on. */
372const boxOf = (r: Rect): Box => ({
373 x: r.x + r.w / 2,
374 y: r.y + r.h / 2,
375 w: r.w,
376 h: r.h,
377 angle: 0,
378});
379
380// ---- stepping -------------------------------------------------------------
381
382/**
383 * Where a tile's *centre* may be for the whole of it to be inside `r`.
384 *
385 * One place rather than three, because the three have to agree: the edge holds
386 * a tile at these limits, and the moment it starts holding it is the moment the
387 * tile reaches them. Deciding that on the centre instead would mean the tile is
388 * declared in while it is still half out, and the first thing the edge did
389 * would be to shove it the rest of the way — half a tile, in one frame, at a
390 * line that is nowhere near the one you can see.
391 *
392 * A pool narrower than a tile would otherwise fight itself, so it centres.
393 */
394function limitsOf(r: Rect, b: Box) {
395 const half = aabbHalf(b);
396 return {
397 minX: r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + half.x,
398 maxX: r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + r.w - half.x,
399 minY: r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + half.y,
400 maxY: r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + r.h - half.y,
401 };
402}
403
404/** Whether the whole tile has made it in — the edge's own test for `entered`. */
405function wholly(r: Rect, b: Body): boolean {
406 const l = limitsOf(r, b);
407 return b.x >= l.minX && b.x <= l.maxX && b.y >= l.minY && b.y <= l.maxY;
408}
409
410/**
411 * Whose side of the table a tile has ended up off, if it is off any of them.
412 * The furthest it is out, so a tile that overshot a corner belongs to whichever
413 * of the two it went past by more.
414 */
415function outsideEdge(r: Rect, b: Body): Edge | undefined {
416 const out: [Edge, number][] = [
417 ['left', r.x - b.x],
418 ['right', b.x - (r.x + r.w)],
419 ['top', r.y - b.y],
420 ['bottom', b.y - (r.y + r.h)],
421 ];
422 let worst: [Edge, number] = out[0];
423 for (const one of out) if (one[1] > worst[1]) worst = one;
424 return worst[1] > 0 ? worst[0] : undefined;
425}
426
427/**
428 * Run the world forward. `elapsed` is real seconds since the last call; it is
429 * consumed in fixed steps so the result does not depend on the frame rate.
430 * Returns the impacts worth a sound.
431 */
432export function advance(world: World, elapsed: number): Impact[] {
433 world.carry += Math.max(0, elapsed);
434 let steps = Math.floor(world.carry / FIXED_DT);
435 if (steps > MAX_SUBSTEPS) {
436 // Drop the backlog rather than working through it.
437 world.carry = 0;
438 steps = MAX_SUBSTEPS;
439 } else {
440 world.carry -= steps * FIXED_DT;
441 }
442
443 const impacts: Impact[] = [];
444 for (let i = 0; i < steps; i++) step(world, impacts);
445 return impacts;
446}
447
448/** One fixed step. Exported for the tests, which drive it directly. */
449export function step(world: World, impacts: Impact[] = []): Impact[] {
450 const dt = FIXED_DT;
451 world.contacts = 0;
452
453 for (const b of world.bodies) {
454 if (b.scale !== 1) {
455 b.scale += (1 - b.scale) * Math.min(1, SCALE_EASE * dt);
456 if (Math.abs(b.scale - 1) < 0.002) b.scale = 1;
457 }
458 if (b.resting) continue;
459 b.age++;
460 b.awake++;
461
462 // --- through the air ---
463 if (b.z > 0 || b.vz !== 0) {
464 b.vz -= GRAVITY * dt;
465 b.z += b.vz * dt;
466 if (b.z <= 0) {
467 const landing = Math.abs(b.vz);
468 b.z = 0;
469 // Below a knock it stops dead rather than shivering out a bounce.
470 b.vz = landing > 40 ? landing * Z_RESTITUTION : 0;
471 const strength = Math.min(1, landing / 900);
472 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
473 }
474 }
475
476 b.x += b.vx * dt;
477 b.y += b.vy * dt;
478 b.angle += b.spin * dt;
479
480 // Turning over. In the air it tumbles; once it is down, whatever is left of
481 // the turn is taken up so it ends flat on its back with its face showing.
482 if (b.flipSpin !== 0) {
483 if (b.z > 0) {
484 b.flip += b.flipSpin * dt;
485 } else {
486 const target = Math.round(b.flip / TAU) * TAU;
487 b.flip += (target - b.flip) * Math.min(1, FLIP_SETTLE * dt);
488 if (Math.abs(target - b.flip) < 0.01) {
489 b.flip = target;
490 b.flipSpin = 0;
491 }
492 }
493 }
494
495 if (!b.entered) {
496 // Kept from step to step: on the step it finally gets in it is inside
497 // already, and there would be nothing left to read.
498 b.over = outsideEdge(world.bounds, b) ?? b.over;
499 // In means all of it in. Anything less and keepInBounds below would
500 // finish the job in a single frame, which is a collision with nothing.
501 if (wholly(world.bounds, b)) {
502 b.entered = true;
503 // It came in over somebody's side of the table. Said quietly — nothing
504 // was struck, so there is nothing to hear — but said, because a tile
505 // arriving past a seat is that seat's to complain about. Its own
506 // thrower's edge is every tile's way in, and the caller drops that one.
507 if (b.over) {
508 impacts.push({ x: b.x, y: b.y, strength: ARRIVED, edge: b.over, seat: b.seat });
509 }
510 b.over = undefined;
511 } else if (b.age > ENTRY_GRACE) {
512 // Out of time going the long way round. Put it in, gently — but this is
513 // still a tile that ended up off the table on somebody's side.
514 if (b.over) {
515 impacts.push({ x: b.x, y: b.y, strength: ARRIVED, edge: b.over, seat: b.seat });
516 }
517 b.entered = true;
518 b.over = undefined;
519 b.z = 0;
520 b.vz = 0;
521 clampInto(world.bounds, b);
522 }
523 }
524
525 // --- on the felt ---
526 // Strictly z <= 0, not ON_FELT: friction is between the tile and the cloth,
527 // so a tile still in the air keeps the speed it was thrown with. ON_FELT is
528 // only about being low enough to be in another tile's way.
529 if (b.z <= 0) {
530 damp(b, dt);
531 // A tile that fell short skids in rather than sitting outside the pool.
532 if (!b.entered) pullIn(world, b, dt);
533 }
534
535 // A tile still above the wall is clear of it.
536 if (b.z < WALL_HEIGHT) {
537 for (const wall of world.walls) hitWall(b, wall, impacts);
538 }
539
540 // The pool's edge is the inside face of the wall, and it is only as tall as
541 // the wall — a tile lobbed high is over the top of it, not stopped by it.
542 if (b.entered && b.z < WALL_HEIGHT) keepInBounds(world, b, impacts);
543 }
544
545 collideTiles(world, impacts);
546 // Being shoved by a neighbour can put a tile back over the edge, and a tile
547 // that then fell asleep out there would stay out there. Only awake ones need
548 // it: resolvePair never moves a tile that has settled.
549 // Resting tiles included: they get pushed about by the untangling above, and
550 // a tile shoved over the edge must not be left there just because it is asleep.
551 for (const b of world.bodies) {
552 if (b.entered && b.z < WALL_HEIGHT) clampInto(world.bounds, b);
553 }
554 // Deciding to sleep comes last, so it judges where the step actually left
555 // things — before, a contact resolved after the decision would undo it and a
556 // crowded pool would stay awake for ever.
557 for (const b of world.bodies) if (!b.resting) trySleep(b);
558
559 // A pile that has stopped moving but is still untangling itself keeps being
560 // stepped, up to a point. Without the limit a configuration that cannot quite
561 // be resolved would keep the loop running for the rest of the hand.
562 world.relaxed = world.contacts > 0 && world.bodies.every((b) => b.resting) ? world.relaxed + 1 : 0;
563 return impacts;
564}
565
566/**
567 * The table has been re-measured — the window resized, or the wall was eaten
568 * further back. The tiles keep where they are, but a pool that shrank must not
569 * leave any of them stranded outside it, and the ones it moves have to wake up
570 * so they can settle again.
571 */
572export function reshape(world: World, bounds: Rect, walls: Barrier[]) {
573 world.bounds = bounds;
574 world.walls = walls;
575 for (const b of world.bodies) {
576 if (!b.entered) continue;
577 const x = b.x;
578 const y = b.y;
579 clampInto(bounds, b);
580 if (b.x !== x || b.y !== y) wake(b);
581 }
582}
583
584function damp(b: Body, dt: number) {
585 const k = Math.exp(-FELT_DAMP * dt);
586 b.vx *= k;
587 b.vy *= k;
588 b.spin *= Math.exp(-SPIN_DAMP * dt);
589
590 const speed = Math.hypot(b.vx, b.vy);
591 if (speed > 0) {
592 const next = Math.max(0, speed - FELT_STOP * dt);
593 b.vx = (b.vx / speed) * next;
594 b.vy = (b.vy / speed) * next;
595 }
596 const spin = Math.abs(b.spin);
597 if (spin > 0) b.spin = Math.sign(b.spin) * Math.max(0, spin - SPIN_STOP * dt);
598}
599
600/** Nudges a tile that landed outside the pool towards the rest of them. */
601function pullIn(world: World, b: Body, dt: number) {
602 const cx = world.bounds.x + world.bounds.w / 2;
603 const cy = world.bounds.y + world.bounds.h / 2;
604 const dx = cx - b.x;
605 const dy = cy - b.y;
606 const d = Math.hypot(dx, dy) || 1;
607 b.vx += (dx / d) * ENTRY_PULL * dt;
608 b.vy += (dy / d) * ENTRY_PULL * dt;
609}
610
611/** Bounce off whatever is standing there, corner to corner if that is how it
612 * hits — a stack of the wall, a laid-down set, somebody's hand. */
613function hitWall(b: Body, wall: Barrier, impacts: Impact[]) {
614 const hit = overlapOf(boxOf(wall.rect), b);
615 if (!hit || hit.depth <= CONTACT_SLOP) return;
616
617 const speed = Math.hypot(b.vx, b.vy);
618 b.x += hit.nx * hit.depth;
619 b.y += hit.ny * hit.depth;
620 // Reflect whatever was heading into the wall; keep what was sliding along it.
621 const into = b.vx * hit.nx + b.vy * hit.ny;
622 if (into < 0) {
623 b.vx -= hit.nx * into * (1 + BOUND_RESTITUTION);
624 b.vy -= hit.ny * into * (1 + BOUND_RESTITUTION);
625 }
626 b.spin *= 0.7;
627 b.resting = false;
628 b.still = 0;
629 const strength = Math.min(1, speed / 1100);
630 if (wall.seat !== undefined) {
631 // Into somebody's tiles. Reported however gently it arrived — their row is
632 // theirs, and a discard rolling into it is an event whatever speed it got
633 // there at. Which of them are loud enough to hear is the caller's business.
634 if (speed > SLEEP_SPEED) {
635 impacts.push({ x: b.x, y: b.y, strength, into: wall.seat, seat: b.seat });
636 }
637 } else if (strength > 0.12) {
638 impacts.push({ x: b.x, y: b.y, strength });
639 }
640}
641
642/** The pool's edge. Once a tile is in, it stays in — this is the invariant the
643 * tests pin, since a discard that slid off the table would be lost. */
644function keepInBounds(world: World, b: Body, impacts: Impact[]) {
645 const { minX, maxX, minY, maxY } = limitsOf(world.bounds, b);
646
647 let hit = 0;
648 let edge: Edge | undefined;
649 if (b.x < minX) {
650 b.x = minX;
651 hit = Math.max(hit, Math.abs(b.vx));
652 edge = 'left';
653 b.vx = Math.abs(b.vx) * BOUND_RESTITUTION;
654 b.vy *= BOUND_FRICTION;
655 } else if (b.x > maxX) {
656 b.x = maxX;
657 hit = Math.max(hit, Math.abs(b.vx));
658 edge = 'right';
659 b.vx = -Math.abs(b.vx) * BOUND_RESTITUTION;
660 b.vy *= BOUND_FRICTION;
661 }
662 if (b.y < minY) {
663 b.y = minY;
664 if (Math.abs(b.vy) > hit) edge = 'top';
665 hit = Math.max(hit, Math.abs(b.vy));
666 b.vy = Math.abs(b.vy) * BOUND_RESTITUTION;
667 b.vx *= BOUND_FRICTION;
668 } else if (b.y > maxY) {
669 b.y = maxY;
670 if (Math.abs(b.vy) > hit) edge = 'bottom';
671 hit = Math.max(hit, Math.abs(b.vy));
672 b.vy = -Math.abs(b.vy) * BOUND_RESTITUTION;
673 b.vx *= BOUND_FRICTION;
674 }
675 // Only a real knock counts as being disturbed. A tile held against the edge
676 // by its neighbours is clamped every single step, and treating that as a knock
677 // would keep the whole pool awake for ever.
678 //
679 // Anything that does arrive under its own steam is reported, however gently:
680 // the edge is where somebody's tiles are, so a discard rolling into them is
681 // an event whatever speed it got there at. Which of them are loud enough to
682 // be worth a sound is the caller's business.
683 if (hit > SLEEP_SPEED) {
684 b.still = 0;
685 impacts.push({ x: b.x, y: b.y, strength: Math.min(1, hit / 1100), edge, seat: b.seat });
686 }
687}
688
689/**
690 * Tile against tile.
691 *
692 * Only tiles flat on the felt take part, so a thrown tile passes over the pile
693 * instead of shouldering through it, and a cheap circle test throws out the pairs
694 * that are nowhere near before the real rectangle test runs. Pairs where both
695 * tiles have settled are left alone entirely, which is nearly all of them.
696 */
697function collideTiles(world: World, impacts: Impact[]) {
698 const bodies = world.bodies;
699 for (let i = 0; i < bodies.length; i++) {
700 const a = bodies[i];
701 if (a.z > ON_FELT) continue;
702 for (let j = i + 1; j < bodies.length; j++) {
703 const b = bodies[j];
704 if (b.z > ON_FELT) continue;
705 if (Math.hypot(b.x - a.x, b.y - a.y) > circumradius(a) + circumradius(b)) continue;
706 // Two tiles that have both settled are still pushed apart if they are
707 // inside each other — they are just not woken up for it. Skipping the pair
708 // outright was how a pile could end up with tiles sharing ground and stay
709 // that way, since nothing steps a pile that has stopped moving.
710 resolvePair(a, b, impacts, world);
711 }
712 }
713}
714
715function resolvePair(a: Body, b: Body, impacts: Impact[], world: World) {
716 const hit = overlapOf(a, b);
717 if (!hit) return;
718 // Resting in contact is not a collision. See CONTACT_SLOP.
719 const depth = hit.depth - CONTACT_SLOP;
720 if (depth <= 0) return;
721 const { nx, ny } = hit;
722
723 world.contacts++;
724 // Push apart. A tile that has settled is the heavy one: a tile thrown into a
725 // pool shoulders in, rather than the pool scattering out of its way.
726 const aShare = a.resting === b.resting ? 0.5 : a.resting ? 0 : 1;
727 const bShare = 1 - aShare;
728 a.x -= nx * depth * aShare;
729 a.y -= ny * depth * aShare;
730 b.x += nx * depth * bShare;
731 b.y += ny * depth * bShare;
732
733 // Impulse along the way out, plus a spin kick off what is left over.
734 //
735 // Only a genuine approach speed counts, and only that wakes anything. Nudging
736 // two touching tiles apart is not a collision: a jammed corner of the pool is
737 // corrected by a fraction of a pixel every step for as long as it is jammed,
738 // and treating each of those as a shove would keep the pile awake for ever.
739 const rvx = b.vx - a.vx;
740 const rvy = b.vy - a.vy;
741 const along = rvx * nx + rvy * ny;
742 if (along >= -SLEEP_SPEED) return;
743
744 const jolt = -along * (1 + TILE_RESTITUTION) * 0.5;
745 a.vx -= nx * jolt;
746 a.vy -= ny * jolt;
747 b.vx += nx * jolt;
748 b.vy += ny * jolt;
749
750 const tangent = rvx * -ny + rvy * nx;
751 a.spin -= tangent * SPIN_TRANSFER * 0.06;
752 b.spin += tangent * SPIN_TRANSFER * 0.06;
753
754 const strength = Math.min(1, Math.abs(along) / 900);
755 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
756
757 // Whatever was asleep has been shoved, so it is awake now.
758 wake(a);
759 wake(b);
760}
761
762function wake(b: Body) {
763 if (b.resting) b.awake = 0;
764 b.resting = false;
765 b.still = 0;
766}
767
768function sleep(b: Body) {
769 b.vx = 0;
770 b.vy = 0;
771 b.spin = 0;
772 b.z = 0;
773 b.vz = 0;
774 // Face up, always. A tile lying face down in the discards would be a tile
775 // nobody can read, so this is a guarantee and not an easing.
776 b.flip = Math.round(b.flip / TAU) * TAU;
777 b.flipSpin = 0;
778 b.resting = true;
779 b.awake = 0;
780}
781
782function trySleep(b: Body) {
783 const speed = Math.hypot(b.vx, b.vy);
784 const slow =
785 b.entered &&
786 b.z <= 0 &&
787 b.vz === 0 &&
788 b.flipSpin === 0 &&
789 speed < SLEEP_SPEED &&
790 Math.abs(b.spin) < SLEEP_SPIN;
791 if (slow && ++b.still >= SLEEP_STEPS) return sleep(b);
792 if (!slow) b.still = 0;
793 // Backstop: shuffling about in a crowded pool for this long is settled enough.
794 if (b.entered && b.awake > AWAKE_LIMIT && speed < SLEEP_SPEED * 4) sleep(b);
795}
796
797/**
798 * Make room for a tile placed straight into a settled pile, without running
799 * time. Used when a pile is rebuilt — a reload, an undo — where the tiles have
800 * to be somewhere sensible immediately and nothing should appear to move.
801 */
802function separate(world: World, body: Body, passes = 16) {
803 // Which way to go when two tiles are exactly on top of each other. Stepping
804 // by the golden angle fans successive tiles out in every direction, where a
805 // fixed axis would march them all one way and pack them against a pool edge.
806 const escape = world.bodies.indexOf(body) * 2.39996;
807
808 for (let p = 0; p < passes; p++) {
809 let moved = false;
810 for (const other of world.bodies) {
811 if (other === body) continue;
812 const hit = overlapOf(other, body);
813 if (!hit || hit.depth <= CONTACT_SLOP) continue;
814 if (Math.hypot(body.x - other.x, body.y - other.y) < 0.0001) {
815 body.x += Math.cos(escape + p) * hit.depth;
816 body.y += Math.sin(escape + p) * hit.depth;
817 } else {
818 body.x += hit.nx * hit.depth;
819 body.y += hit.ny * hit.depth;
820 }
821 moved = true;
822 }
823 clampInto(world.bounds, body);
824 if (!moved) break;
825 }
826}
827
828function clampInto(r: Rect, b: Body) {
829 const { minX, maxX, minY, maxY } = limitsOf(r, b);
830 b.x = Math.min(maxX, Math.max(minX, b.x));
831 b.y = Math.min(maxY, Math.max(minY, b.y));
832}
833
834/**
835 * How long a motionless pile is allowed to keep untangling itself before the
836 * result is accepted as good enough. Anything still overlapping after this is
837 * doing so by a fraction of a pixel, and the loop has better things to do than
838 * keep running over it.
839 */
840const RELAX_LIMIT = 90;
841
842/** Whether everything has settled — what the render loop idles on. */
843export const settled = (world: World) =>
844 world.bodies.every((b) => b.resting && b.scale === 1) &&
845 (world.contacts === 0 || world.relaxed > RELAX_LIMIT);
846
847/** How square-on the face is: 1 flat on its back, 0 edge-on, negative face down.
848 * The renderer squashes the tile by this along its tumbling axis. */
849export const faceOn = (b: Body) => Math.cos(b.flip);
850
851/**
852 * A tile's own bounding box, upright. Not what it collides with — that is the
853 * rotated rectangle — but what the felt's straight edges are worked out from,
854 * so the overlay draws both and the difference is visible.
855 */
856export function aabbOf(b: Body): Rect {
857 const half = aabbHalf(b);
858 return { x: b.x - half.x, y: b.y - half.y, w: half.x * 2, h: half.y * 2 };
859}
860
861/**
862 * Where this tile's *centre* is allowed to be, which is the edge less its own
863 * half. This is the line a bounce actually happens at, and it sits half a tile
864 * inside the one you can see — which is why a tile looks like it turned around
865 * early. For the overlay; the real work is `limitsOf`.
866 */
867export function centreLimits(r: Rect, b: Body): Rect {
868 const l = limitsOf(r, b);
869 return { x: l.minX, y: l.minY, w: l.maxX - l.minX, h: l.maxY - l.minY };
870}
871
872/** How far outside the pool a tile is sitting. The tests' invariant. */
873export function outside(b: Body, pool: Rect): number {
874 const half = aabbHalf(b);
875 return Math.max(
876 0,
877 pool.x + half.x - b.x,
878 b.x - (pool.x + pool.w - half.x),
879 pool.y + half.y - b.y,
880 b.y - (pool.y + pool.h - half.y),
881 );
882}
883
884/**
885 * A finger, or a cursor, pushing the tiles about in the middle — 洗牌, the thing
886 * everybody does to a pool of discards while waiting for their turn.
887 *
888 * Modelled as a circle that simply cannot be inside a tile: anything it touches
889 * is shoved clear of it and handed some of the speed it was moving at. It has no
890 * mass and takes no impulse back, which is what a finger on a table is.
891 */
892export function stir(
893 world: World,
894 x: number,
895 y: number,
896 vx: number,
897 vy: number,
898 radius: number,
899) {
900 // A frantic swipe should not fire tiles off like bullets.
901 const speed = Math.hypot(vx, vy);
902 const trim = speed > STIR_MAX_SPEED ? STIR_MAX_SPEED / speed : 1;
903
904 for (const b of world.bodies) {
905 if (b.z > ON_FELT) continue;
906 const dx = b.x - x;
907 const dy = b.y - y;
908 const clear = radius + circumradius(b);
909 const d = Math.hypot(dx, dy);
910 if (d > clear) continue;
911
912 const nx = d < 0.001 ? 1 : dx / d;
913 const ny = d < 0.001 ? 0 : dy / d;
914 b.x = x + nx * clear;
915 b.y = y + ny * clear;
916 b.vx += vx * trim * STIR_DRAG + nx * STIR_NUDGE;
917 b.vy += vy * trim * STIR_DRAG + ny * STIR_NUDGE;
918 // Dragged past off-centre, a tile turns under your finger.
919 b.spin += (vx * trim * ny - vy * trim * nx) * 0.0016;
920 wake(b);
921 }
922}
923
924/** Whether two tiles are sharing ground, which they must never do at rest. */
925export function overlapping(a: Body, b: Body): number {
926 const hit = overlapOf(a, b);
927 return hit ? hit.depth : 0;
928}
929
930/** Scale a tile is drawn at, given how high it is. Sells the arc on a flat
931 * canvas; the renderer offsets the shadow by the same height. */
932export const zScale = (z: number) => 1 + z * 0.0016;
933
934/**
935 * The upward kick that puts a tile back on the felt after `seconds` in the air.
936 * How a throw is aimed: pick how long it should take, and the horizontal speed
937 * follows from the distance.
938 */
939export const liftFor = (seconds: number) => (GRAVITY * seconds) / 2;
940
941/** How high that kick gets — worth checking against WALL_HEIGHT. */
942export const peakOf = (vz: number) => (vz * vz) / (2 * GRAVITY);