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 discard it was, for an edge — you cannot be barged by your own tile. */
210 seat?: SeatId;
211}
212
213export interface World {
214 /** Where tiles come to rest — inside the wall square. */
215 bounds: Rect;
216 /** Stacks of two still standing. Half and spent stacks are not obstacles. */
217 walls: Rect[];
218 bodies: Body[];
219 /** Left-over time from the last frame, so steps stay a fixed size. */
220 carry: number;
221 /**
222 * Overlaps pushed apart in the last step. The pile is not settled while this
223 * is non-zero, however still everything looks — two tiles asleep inside each
224 * other would otherwise stay that way for the rest of the hand, because a
225 * pile that has stopped moving stops being stepped.
226 */
227 contacts: number;
228 /** Steps spent untangling a pile that is otherwise asleep, so it cannot spin. */
229 relaxed: number;
230}
231
232export interface Spawn {
233 tile: Tile;
234 seat: SeatId;
235 x: number;
236 y: number;
237 vx: number;
238 vy: number;
239 z: number;
240 vz: number;
241 angle: number;
242 spin: number;
243 /** Whole turns to make in the air. It lands face up whatever this is. */
244 flipTurns?: number;
245 /** Seconds of flight those turns are spread over. */
246 flipOver?: number;
247 flipAxis?: number;
248 w: number;
249 h: number;
250 /** Drawn this much bigger to start with, easing to its pool size. */
251 scale?: number;
252 /** Already settled — a pile being rebuilt after a reload or an undo. */
253 atRest?: boolean;
254}
255
256export function createWorld(bounds: Rect, walls: Rect[] = []): World {
257 return { bounds, walls, bodies: [], carry: 0, contacts: 0, relaxed: 0 };
258}
259
260export function addBody(world: World, s: Spawn): Body {
261 const body: Body = {
262 tile: s.tile,
263 seat: s.seat,
264 x: s.x,
265 y: s.y,
266 vx: s.atRest ? 0 : s.vx,
267 vy: s.atRest ? 0 : s.vy,
268 z: s.atRest ? 0 : s.z,
269 vz: s.atRest ? 0 : s.vz,
270 angle: s.angle,
271 spin: s.atRest ? 0 : s.spin,
272 flip: 0,
273 // Spread the turns over the flight, so the tile comes down as it comes back
274 // round to face up rather than being snapped there on landing.
275 flipSpin:
276 s.atRest || !s.flipTurns || !s.flipOver ? 0 : (TAU * s.flipTurns) / s.flipOver,
277 flipAxis: s.flipAxis ?? 0,
278 w: s.w,
279 h: s.h,
280 scale: s.atRest ? 1 : s.scale ?? 1,
281 entered: !!s.atRest,
282 resting: !!s.atRest,
283 still: s.atRest ? SLEEP_STEPS : 0,
284 age: 0,
285 awake: 0,
286 };
287 world.bodies.push(body);
288 if (s.atRest) {
289 // A tile dropped straight into a settled pile still has to make room. This
290 // is a first shove only — the relaxing below finishes the job, which matters
291 // for a whole pile rebuilt at once when a saved game is picked up.
292 separate(world, body);
293 world.contacts++;
294 }
295 return body;
296}
297
298// ---- rotated rectangles ---------------------------------------------------
299
300/** Distance from a box's centre to its edge, measured along `ax`. */
301function reach(b: Box, ax: { x: number; y: number }): number {
302 const c = Math.cos(b.angle);
303 const s = Math.sin(b.angle);
304 return (
305 Math.abs(c * ax.x + s * ax.y) * (b.w / 2) + Math.abs(-s * ax.x + c * ax.y) * (b.h / 2)
306 );
307}
308
309/** The rotated rectangle's own bounding box, for the pool's straight edges. */
310function aabbHalf(b: Box) {
311 const c = Math.abs(Math.cos(b.angle));
312 const s = Math.abs(Math.sin(b.angle));
313 return { x: (b.w / 2) * c + (b.h / 2) * s, y: (b.w / 2) * s + (b.h / 2) * c };
314}
315
316/** Enough to skip a pair without doing the real work. */
317const circumradius = (b: Box) => Math.hypot(b.w, b.h) / 2;
318
319/**
320 * Separating axis test between two rectangles at any angle. Returns the
321 * shallowest way out — the direction to push `b` away from `a`, and by how much
322 * — or null if they are clear of each other.
323 *
324 * Four axes is all a pair of rectangles needs: each box's two edge normals.
325 */
326function overlapOf(a: Box, b: Box): { nx: number; ny: number; depth: number } | null {
327 const ca = Math.cos(a.angle);
328 const sa = Math.sin(a.angle);
329 const cb = Math.cos(b.angle);
330 const sb = Math.sin(b.angle);
331 const axes = [
332 { x: ca, y: sa },
333 { x: -sa, y: ca },
334 { x: cb, y: sb },
335 { x: -sb, y: cb },
336 ];
337
338 const dx = b.x - a.x;
339 const dy = b.y - a.y;
340 let depth = Infinity;
341 let nx = 0;
342 let ny = 0;
343
344 for (const ax of axes) {
345 const gap = reach(a, ax) + reach(b, ax) - Math.abs(dx * ax.x + dy * ax.y);
346 if (gap <= 0) return null;
347 if (gap < depth) {
348 depth = gap;
349 // Always pointing from a towards b, so callers need not guess.
350 const sign = dx * ax.x + dy * ax.y < 0 ? -1 : 1;
351 nx = ax.x * sign;
352 ny = ax.y * sign;
353 }
354 }
355 return { nx, ny, depth };
356}
357
358/** A standing stack, as something the tests above can chew on. */
359const boxOf = (r: Rect): Box => ({
360 x: r.x + r.w / 2,
361 y: r.y + r.h / 2,
362 w: r.w,
363 h: r.h,
364 angle: 0,
365});
366
367// ---- stepping -------------------------------------------------------------
368
369/**
370 * Where a tile's *centre* may be for the whole of it to be inside `r`.
371 *
372 * One place rather than three, because the three have to agree: the edge holds
373 * a tile at these limits, and the moment it starts holding it is the moment the
374 * tile reaches them. Deciding that on the centre instead would mean the tile is
375 * declared in while it is still half out, and the first thing the edge did
376 * would be to shove it the rest of the way — half a tile, in one frame, at a
377 * line that is nowhere near the one you can see.
378 *
379 * A pool narrower than a tile would otherwise fight itself, so it centres.
380 */
381function limitsOf(r: Rect, b: Box) {
382 const half = aabbHalf(b);
383 return {
384 minX: r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + half.x,
385 maxX: r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + r.w - half.x,
386 minY: r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + half.y,
387 maxY: r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + r.h - half.y,
388 };
389}
390
391/** Whether the whole tile has made it in — the edge's own test for `entered`. */
392function wholly(r: Rect, b: Body): boolean {
393 const l = limitsOf(r, b);
394 return b.x >= l.minX && b.x <= l.maxX && b.y >= l.minY && b.y <= l.maxY;
395}
396
397/**
398 * Whose side of the table a tile has ended up off, if it is off any of them.
399 * The furthest it is out, so a tile that overshot a corner belongs to whichever
400 * of the two it went past by more.
401 */
402function outsideEdge(r: Rect, b: Body): Edge | undefined {
403 const out: [Edge, number][] = [
404 ['left', r.x - b.x],
405 ['right', b.x - (r.x + r.w)],
406 ['top', r.y - b.y],
407 ['bottom', b.y - (r.y + r.h)],
408 ];
409 let worst: [Edge, number] = out[0];
410 for (const one of out) if (one[1] > worst[1]) worst = one;
411 return worst[1] > 0 ? worst[0] : undefined;
412}
413
414/**
415 * Run the world forward. `elapsed` is real seconds since the last call; it is
416 * consumed in fixed steps so the result does not depend on the frame rate.
417 * Returns the impacts worth a sound.
418 */
419export function advance(world: World, elapsed: number): Impact[] {
420 world.carry += Math.max(0, elapsed);
421 let steps = Math.floor(world.carry / FIXED_DT);
422 if (steps > MAX_SUBSTEPS) {
423 // Drop the backlog rather than working through it.
424 world.carry = 0;
425 steps = MAX_SUBSTEPS;
426 } else {
427 world.carry -= steps * FIXED_DT;
428 }
429
430 const impacts: Impact[] = [];
431 for (let i = 0; i < steps; i++) step(world, impacts);
432 return impacts;
433}
434
435/** One fixed step. Exported for the tests, which drive it directly. */
436export function step(world: World, impacts: Impact[] = []): Impact[] {
437 const dt = FIXED_DT;
438 world.contacts = 0;
439
440 for (const b of world.bodies) {
441 if (b.scale !== 1) {
442 b.scale += (1 - b.scale) * Math.min(1, SCALE_EASE * dt);
443 if (Math.abs(b.scale - 1) < 0.002) b.scale = 1;
444 }
445 if (b.resting) continue;
446 b.age++;
447 b.awake++;
448
449 // --- through the air ---
450 if (b.z > 0 || b.vz !== 0) {
451 b.vz -= GRAVITY * dt;
452 b.z += b.vz * dt;
453 if (b.z <= 0) {
454 const landing = Math.abs(b.vz);
455 b.z = 0;
456 // Below a knock it stops dead rather than shivering out a bounce.
457 b.vz = landing > 40 ? landing * Z_RESTITUTION : 0;
458 const strength = Math.min(1, landing / 900);
459 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
460 }
461 }
462
463 b.x += b.vx * dt;
464 b.y += b.vy * dt;
465 b.angle += b.spin * dt;
466
467 // Turning over. In the air it tumbles; once it is down, whatever is left of
468 // the turn is taken up so it ends flat on its back with its face showing.
469 if (b.flipSpin !== 0) {
470 if (b.z > 0) {
471 b.flip += b.flipSpin * dt;
472 } else {
473 const target = Math.round(b.flip / TAU) * TAU;
474 b.flip += (target - b.flip) * Math.min(1, FLIP_SETTLE * dt);
475 if (Math.abs(target - b.flip) < 0.01) {
476 b.flip = target;
477 b.flipSpin = 0;
478 }
479 }
480 }
481
482 if (!b.entered) {
483 // Kept from step to step: on the step it finally gets in it is inside
484 // already, and there would be nothing left to read.
485 b.over = outsideEdge(world.bounds, b) ?? b.over;
486 // In means all of it in. Anything less and keepInBounds below would
487 // finish the job in a single frame, which is a collision with nothing.
488 if (wholly(world.bounds, b)) {
489 b.entered = true;
490 // It came in over somebody's side of the table. Said quietly — nothing
491 // was struck, so there is nothing to hear — but said, because a tile
492 // arriving past a seat is that seat's to complain about. Its own
493 // thrower's edge is every tile's way in, and the caller drops that one.
494 if (b.over) {
495 impacts.push({ x: b.x, y: b.y, strength: ARRIVED, edge: b.over, seat: b.seat });
496 }
497 b.over = undefined;
498 } else if (b.age > ENTRY_GRACE) {
499 // Out of time going the long way round. Put it in, gently — but this is
500 // still a tile that ended up off the table on somebody's side.
501 if (b.over) {
502 impacts.push({ x: b.x, y: b.y, strength: ARRIVED, edge: b.over, seat: b.seat });
503 }
504 b.entered = true;
505 b.over = undefined;
506 b.z = 0;
507 b.vz = 0;
508 clampInto(world.bounds, b);
509 }
510 }
511
512 // --- on the felt ---
513 // Strictly z <= 0, not ON_FELT: friction is between the tile and the cloth,
514 // so a tile still in the air keeps the speed it was thrown with. ON_FELT is
515 // only about being low enough to be in another tile's way.
516 if (b.z <= 0) {
517 damp(b, dt);
518 // A tile that fell short skids in rather than sitting outside the pool.
519 if (!b.entered) pullIn(world, b, dt);
520 }
521
522 // A tile still above the wall is clear of it.
523 if (b.z < WALL_HEIGHT) {
524 for (const wall of world.walls) hitWall(b, wall, impacts);
525 }
526
527 // The pool's edge is the inside face of the wall, and it is only as tall as
528 // the wall — a tile lobbed high is over the top of it, not stopped by it.
529 if (b.entered && b.z < WALL_HEIGHT) keepInBounds(world, b, impacts);
530 }
531
532 collideTiles(world, impacts);
533 // Being shoved by a neighbour can put a tile back over the edge, and a tile
534 // that then fell asleep out there would stay out there. Only awake ones need
535 // it: resolvePair never moves a tile that has settled.
536 // Resting tiles included: they get pushed about by the untangling above, and
537 // a tile shoved over the edge must not be left there just because it is asleep.
538 for (const b of world.bodies) {
539 if (b.entered && b.z < WALL_HEIGHT) clampInto(world.bounds, b);
540 }
541 // Deciding to sleep comes last, so it judges where the step actually left
542 // things — before, a contact resolved after the decision would undo it and a
543 // crowded pool would stay awake for ever.
544 for (const b of world.bodies) if (!b.resting) trySleep(b);
545
546 // A pile that has stopped moving but is still untangling itself keeps being
547 // stepped, up to a point. Without the limit a configuration that cannot quite
548 // be resolved would keep the loop running for the rest of the hand.
549 world.relaxed = world.contacts > 0 && world.bodies.every((b) => b.resting) ? world.relaxed + 1 : 0;
550 return impacts;
551}
552
553/**
554 * The table has been re-measured — the window resized, or the wall was eaten
555 * further back. The tiles keep where they are, but a pool that shrank must not
556 * leave any of them stranded outside it, and the ones it moves have to wake up
557 * so they can settle again.
558 */
559export function reshape(world: World, bounds: Rect, walls: Rect[]) {
560 world.bounds = bounds;
561 world.walls = walls;
562 for (const b of world.bodies) {
563 if (!b.entered) continue;
564 const x = b.x;
565 const y = b.y;
566 clampInto(bounds, b);
567 if (b.x !== x || b.y !== y) wake(b);
568 }
569}
570
571function damp(b: Body, dt: number) {
572 const k = Math.exp(-FELT_DAMP * dt);
573 b.vx *= k;
574 b.vy *= k;
575 b.spin *= Math.exp(-SPIN_DAMP * dt);
576
577 const speed = Math.hypot(b.vx, b.vy);
578 if (speed > 0) {
579 const next = Math.max(0, speed - FELT_STOP * dt);
580 b.vx = (b.vx / speed) * next;
581 b.vy = (b.vy / speed) * next;
582 }
583 const spin = Math.abs(b.spin);
584 if (spin > 0) b.spin = Math.sign(b.spin) * Math.max(0, spin - SPIN_STOP * dt);
585}
586
587/** Nudges a tile that landed outside the pool towards the rest of them. */
588function pullIn(world: World, b: Body, dt: number) {
589 const cx = world.bounds.x + world.bounds.w / 2;
590 const cy = world.bounds.y + world.bounds.h / 2;
591 const dx = cx - b.x;
592 const dy = cy - b.y;
593 const d = Math.hypot(dx, dy) || 1;
594 b.vx += (dx / d) * ENTRY_PULL * dt;
595 b.vy += (dy / d) * ENTRY_PULL * dt;
596}
597
598/** Bounce off a standing stack, corner to corner if that is how it hits. */
599function hitWall(b: Body, wall: Rect, impacts: Impact[]) {
600 const hit = overlapOf(boxOf(wall), b);
601 if (!hit || hit.depth <= CONTACT_SLOP) return;
602
603 const speed = Math.hypot(b.vx, b.vy);
604 b.x += hit.nx * hit.depth;
605 b.y += hit.ny * hit.depth;
606 // Reflect whatever was heading into the wall; keep what was sliding along it.
607 const into = b.vx * hit.nx + b.vy * hit.ny;
608 if (into < 0) {
609 b.vx -= hit.nx * into * (1 + BOUND_RESTITUTION);
610 b.vy -= hit.ny * into * (1 + BOUND_RESTITUTION);
611 }
612 b.spin *= 0.7;
613 b.resting = false;
614 b.still = 0;
615 const strength = Math.min(1, speed / 1100);
616 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
617}
618
619/** The pool's edge. Once a tile is in, it stays in — this is the invariant the
620 * tests pin, since a discard that slid off the table would be lost. */
621function keepInBounds(world: World, b: Body, impacts: Impact[]) {
622 const { minX, maxX, minY, maxY } = limitsOf(world.bounds, b);
623
624 let hit = 0;
625 let edge: Edge | undefined;
626 if (b.x < minX) {
627 b.x = minX;
628 hit = Math.max(hit, Math.abs(b.vx));
629 edge = 'left';
630 b.vx = Math.abs(b.vx) * BOUND_RESTITUTION;
631 b.vy *= BOUND_FRICTION;
632 } else if (b.x > maxX) {
633 b.x = maxX;
634 hit = Math.max(hit, Math.abs(b.vx));
635 edge = 'right';
636 b.vx = -Math.abs(b.vx) * BOUND_RESTITUTION;
637 b.vy *= BOUND_FRICTION;
638 }
639 if (b.y < minY) {
640 b.y = minY;
641 if (Math.abs(b.vy) > hit) edge = 'top';
642 hit = Math.max(hit, Math.abs(b.vy));
643 b.vy = Math.abs(b.vy) * BOUND_RESTITUTION;
644 b.vx *= BOUND_FRICTION;
645 } else if (b.y > maxY) {
646 b.y = maxY;
647 if (Math.abs(b.vy) > hit) edge = 'bottom';
648 hit = Math.max(hit, Math.abs(b.vy));
649 b.vy = -Math.abs(b.vy) * BOUND_RESTITUTION;
650 b.vx *= BOUND_FRICTION;
651 }
652 // Only a real knock counts as being disturbed. A tile held against the edge
653 // by its neighbours is clamped every single step, and treating that as a knock
654 // would keep the whole pool awake for ever.
655 //
656 // Anything that does arrive under its own steam is reported, however gently:
657 // the edge is where somebody's tiles are, so a discard rolling into them is
658 // an event whatever speed it got there at. Which of them are loud enough to
659 // be worth a sound is the caller's business.
660 if (hit > SLEEP_SPEED) {
661 b.still = 0;
662 impacts.push({ x: b.x, y: b.y, strength: Math.min(1, hit / 1100), edge, seat: b.seat });
663 }
664}
665
666/**
667 * Tile against tile.
668 *
669 * Only tiles flat on the felt take part, so a thrown tile passes over the pile
670 * instead of shouldering through it, and a cheap circle test throws out the pairs
671 * that are nowhere near before the real rectangle test runs. Pairs where both
672 * tiles have settled are left alone entirely, which is nearly all of them.
673 */
674function collideTiles(world: World, impacts: Impact[]) {
675 const bodies = world.bodies;
676 for (let i = 0; i < bodies.length; i++) {
677 const a = bodies[i];
678 if (a.z > ON_FELT) continue;
679 for (let j = i + 1; j < bodies.length; j++) {
680 const b = bodies[j];
681 if (b.z > ON_FELT) continue;
682 if (Math.hypot(b.x - a.x, b.y - a.y) > circumradius(a) + circumradius(b)) continue;
683 // Two tiles that have both settled are still pushed apart if they are
684 // inside each other — they are just not woken up for it. Skipping the pair
685 // outright was how a pile could end up with tiles sharing ground and stay
686 // that way, since nothing steps a pile that has stopped moving.
687 resolvePair(a, b, impacts, world);
688 }
689 }
690}
691
692function resolvePair(a: Body, b: Body, impacts: Impact[], world: World) {
693 const hit = overlapOf(a, b);
694 if (!hit) return;
695 // Resting in contact is not a collision. See CONTACT_SLOP.
696 const depth = hit.depth - CONTACT_SLOP;
697 if (depth <= 0) return;
698 const { nx, ny } = hit;
699
700 world.contacts++;
701 // Push apart. A tile that has settled is the heavy one: a tile thrown into a
702 // pool shoulders in, rather than the pool scattering out of its way.
703 const aShare = a.resting === b.resting ? 0.5 : a.resting ? 0 : 1;
704 const bShare = 1 - aShare;
705 a.x -= nx * depth * aShare;
706 a.y -= ny * depth * aShare;
707 b.x += nx * depth * bShare;
708 b.y += ny * depth * bShare;
709
710 // Impulse along the way out, plus a spin kick off what is left over.
711 //
712 // Only a genuine approach speed counts, and only that wakes anything. Nudging
713 // two touching tiles apart is not a collision: a jammed corner of the pool is
714 // corrected by a fraction of a pixel every step for as long as it is jammed,
715 // and treating each of those as a shove would keep the pile awake for ever.
716 const rvx = b.vx - a.vx;
717 const rvy = b.vy - a.vy;
718 const along = rvx * nx + rvy * ny;
719 if (along >= -SLEEP_SPEED) return;
720
721 const jolt = -along * (1 + TILE_RESTITUTION) * 0.5;
722 a.vx -= nx * jolt;
723 a.vy -= ny * jolt;
724 b.vx += nx * jolt;
725 b.vy += ny * jolt;
726
727 const tangent = rvx * -ny + rvy * nx;
728 a.spin -= tangent * SPIN_TRANSFER * 0.06;
729 b.spin += tangent * SPIN_TRANSFER * 0.06;
730
731 const strength = Math.min(1, Math.abs(along) / 900);
732 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
733
734 // Whatever was asleep has been shoved, so it is awake now.
735 wake(a);
736 wake(b);
737}
738
739function wake(b: Body) {
740 if (b.resting) b.awake = 0;
741 b.resting = false;
742 b.still = 0;
743}
744
745function sleep(b: Body) {
746 b.vx = 0;
747 b.vy = 0;
748 b.spin = 0;
749 b.z = 0;
750 b.vz = 0;
751 // Face up, always. A tile lying face down in the discards would be a tile
752 // nobody can read, so this is a guarantee and not an easing.
753 b.flip = Math.round(b.flip / TAU) * TAU;
754 b.flipSpin = 0;
755 b.resting = true;
756 b.awake = 0;
757}
758
759function trySleep(b: Body) {
760 const speed = Math.hypot(b.vx, b.vy);
761 const slow =
762 b.entered &&
763 b.z <= 0 &&
764 b.vz === 0 &&
765 b.flipSpin === 0 &&
766 speed < SLEEP_SPEED &&
767 Math.abs(b.spin) < SLEEP_SPIN;
768 if (slow && ++b.still >= SLEEP_STEPS) return sleep(b);
769 if (!slow) b.still = 0;
770 // Backstop: shuffling about in a crowded pool for this long is settled enough.
771 if (b.entered && b.awake > AWAKE_LIMIT && speed < SLEEP_SPEED * 4) sleep(b);
772}
773
774/**
775 * Make room for a tile placed straight into a settled pile, without running
776 * time. Used when a pile is rebuilt — a reload, an undo — where the tiles have
777 * to be somewhere sensible immediately and nothing should appear to move.
778 */
779function separate(world: World, body: Body, passes = 16) {
780 // Which way to go when two tiles are exactly on top of each other. Stepping
781 // by the golden angle fans successive tiles out in every direction, where a
782 // fixed axis would march them all one way and pack them against a pool edge.
783 const escape = world.bodies.indexOf(body) * 2.39996;
784
785 for (let p = 0; p < passes; p++) {
786 let moved = false;
787 for (const other of world.bodies) {
788 if (other === body) continue;
789 const hit = overlapOf(other, body);
790 if (!hit || hit.depth <= CONTACT_SLOP) continue;
791 if (Math.hypot(body.x - other.x, body.y - other.y) < 0.0001) {
792 body.x += Math.cos(escape + p) * hit.depth;
793 body.y += Math.sin(escape + p) * hit.depth;
794 } else {
795 body.x += hit.nx * hit.depth;
796 body.y += hit.ny * hit.depth;
797 }
798 moved = true;
799 }
800 clampInto(world.bounds, body);
801 if (!moved) break;
802 }
803}
804
805function clampInto(r: Rect, b: Body) {
806 const { minX, maxX, minY, maxY } = limitsOf(r, b);
807 b.x = Math.min(maxX, Math.max(minX, b.x));
808 b.y = Math.min(maxY, Math.max(minY, b.y));
809}
810
811/**
812 * How long a motionless pile is allowed to keep untangling itself before the
813 * result is accepted as good enough. Anything still overlapping after this is
814 * doing so by a fraction of a pixel, and the loop has better things to do than
815 * keep running over it.
816 */
817const RELAX_LIMIT = 90;
818
819/** Whether everything has settled — what the render loop idles on. */
820export const settled = (world: World) =>
821 world.bodies.every((b) => b.resting && b.scale === 1) &&
822 (world.contacts === 0 || world.relaxed > RELAX_LIMIT);
823
824/** How square-on the face is: 1 flat on its back, 0 edge-on, negative face down.
825 * The renderer squashes the tile by this along its tumbling axis. */
826export const faceOn = (b: Body) => Math.cos(b.flip);
827
828/**
829 * A tile's own bounding box, upright. Not what it collides with — that is the
830 * rotated rectangle — but what the felt's straight edges are worked out from,
831 * so the overlay draws both and the difference is visible.
832 */
833export function aabbOf(b: Body): Rect {
834 const half = aabbHalf(b);
835 return { x: b.x - half.x, y: b.y - half.y, w: half.x * 2, h: half.y * 2 };
836}
837
838/**
839 * Where this tile's *centre* is allowed to be, which is the edge less its own
840 * half. This is the line a bounce actually happens at, and it sits half a tile
841 * inside the one you can see — which is why a tile looks like it turned around
842 * early. For the overlay; the real work is `limitsOf`.
843 */
844export function centreLimits(r: Rect, b: Body): Rect {
845 const l = limitsOf(r, b);
846 return { x: l.minX, y: l.minY, w: l.maxX - l.minX, h: l.maxY - l.minY };
847}
848
849/** How far outside the pool a tile is sitting. The tests' invariant. */
850export function outside(b: Body, pool: Rect): number {
851 const half = aabbHalf(b);
852 return Math.max(
853 0,
854 pool.x + half.x - b.x,
855 b.x - (pool.x + pool.w - half.x),
856 pool.y + half.y - b.y,
857 b.y - (pool.y + pool.h - half.y),
858 );
859}
860
861/**
862 * A finger, or a cursor, pushing the tiles about in the middle — 洗牌, the thing
863 * everybody does to a pool of discards while waiting for their turn.
864 *
865 * Modelled as a circle that simply cannot be inside a tile: anything it touches
866 * is shoved clear of it and handed some of the speed it was moving at. It has no
867 * mass and takes no impulse back, which is what a finger on a table is.
868 */
869export function stir(
870 world: World,
871 x: number,
872 y: number,
873 vx: number,
874 vy: number,
875 radius: number,
876) {
877 // A frantic swipe should not fire tiles off like bullets.
878 const speed = Math.hypot(vx, vy);
879 const trim = speed > STIR_MAX_SPEED ? STIR_MAX_SPEED / speed : 1;
880
881 for (const b of world.bodies) {
882 if (b.z > ON_FELT) continue;
883 const dx = b.x - x;
884 const dy = b.y - y;
885 const clear = radius + circumradius(b);
886 const d = Math.hypot(dx, dy);
887 if (d > clear) continue;
888
889 const nx = d < 0.001 ? 1 : dx / d;
890 const ny = d < 0.001 ? 0 : dy / d;
891 b.x = x + nx * clear;
892 b.y = y + ny * clear;
893 b.vx += vx * trim * STIR_DRAG + nx * STIR_NUDGE;
894 b.vy += vy * trim * STIR_DRAG + ny * STIR_NUDGE;
895 // Dragged past off-centre, a tile turns under your finger.
896 b.spin += (vx * trim * ny - vy * trim * nx) * 0.0016;
897 wake(b);
898 }
899}
900
901/** Whether two tiles are sharing ground, which they must never do at rest. */
902export function overlapping(a: Body, b: Body): number {
903 const hit = overlapOf(a, b);
904 return hit ? hit.depth : 0;
905}
906
907/** Scale a tile is drawn at, given how high it is. Sells the arc on a flat
908 * canvas; the renderer offsets the shadow by the same height. */
909export const zScale = (z: number) => 1 + z * 0.0016;
910
911/**
912 * The upward kick that puts a tile back on the felt after `seconds` in the air.
913 * How a throw is aimed: pick how long it should take, and the horizontal speed
914 * follows from the distance.
915 */
916export const liftFor = (seconds: number) => (GRAVITY * seconds) / 2;
917
918/** How high that kick gets — worth checking against WALL_HEIGHT. */
919export const peakOf = (vz: number) => (vz * vz) / (2 * GRAVITY);