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/** How fast a tile drawn at hand size shrinks to the size it is in the pool. */
99const SCALE_EASE = 6;
100
101/** Washing the tiles about: how much of a finger's speed a tile takes on, how
102 * hard it is nudged clear, and the fastest shove it will pass on. */
103const STIR_DRAG = 0.55;
104const STIR_NUDGE = 30;
105const STIR_MAX_SPEED = 1500;
106
107export const TAU = Math.PI * 2;
108/**
109 * How quickly whatever is left of a tumble is taken up once the tile is down.
110 * A thrown tile turns over in the air a whole number of times, so it should be
111 * face up as it lands — but a bounce or a shove can leave it part-way round, and
112 * a mahjong tile on a table is never resting on its face. This takes up the
113 * remainder, and `sleep` guarantees the rest.
114 */
115const FLIP_SETTLE = 14;
116
117export interface Rect {
118 x: number;
119 y: number;
120 w: number;
121 h: number;
122}
123
124/** Anything the collision routines can treat as a rotated rectangle. */
125interface Box {
126 x: number;
127 y: number;
128 w: number;
129 h: number;
130 angle: number;
131}
132
133export interface Body {
134 tile: Tile;
135 /** Who threw it — for the fly-out when it is claimed, not for any marking. */
136 seat: SeatId;
137 /** Centre on the felt plane. */
138 x: number;
139 y: number;
140 vx: number;
141 vy: number;
142 /** Height above the felt, and its rate. Only ever >= 0. */
143 z: number;
144 vz: number;
145 angle: number;
146 spin: number;
147 /**
148 * Turning over in the air, about an axis lying in the table — what a thrown
149 * tile does, as opposed to `angle`, which is it turning flat on the cloth.
150 * Zero, or any whole number of turns, is face up.
151 */
152 flip: number;
153 flipSpin: number;
154 /** Which way that axis points: a tile tumbles across its line of travel. */
155 flipAxis: number;
156 w: number;
157 h: number;
158 /**
159 * Render-only: what to multiply the drawn size by, easing to 1. A tile is
160 * drawn big in a hand so it can be read, and small in the pool because that is
161 * the size it is in the wall, so a thrown one has to settle from one to the
162 * other. Eased here rather than in the renderer so it does not run at a
163 * different speed on a different frame rate.
164 */
165 scale: number;
166 /**
167 * Whether it has ever been inside the pool. Until it has, it is free to fly
168 * over the wall from a seat's edge; once it has, the pool keeps it.
169 */
170 entered: boolean;
171 resting: boolean;
172 /** Consecutive slow steps, counting towards sleep. */
173 still: number;
174 /** Steps lived, for the grace period on getting into the pool. */
175 age: number;
176 /** Steps since it last woke, for the backstop on settling. */
177 awake: number;
178}
179
180/**
181 * Which edge of the middle a tile ran into. The middle stops where the four
182 * players' tiles start, so an edge is somebody's hand: a tile that reaches one
183 * hard has been thrown into their tiles, and they have something to say about
184 * it. Seats are the caller's business; this only says which way it went off.
185 */
186export type Edge = 'left' | 'right' | 'top' | 'bottom';
187
188/** A collision loud enough to hear. `strength` is 0..1. */
189export interface Impact {
190 x: number;
191 y: number;
192 strength: number;
193 /** Set when it was the edge of the table it hit, not a wall or another tile. */
194 edge?: Edge;
195 /** Whose discard it was, for an edge — you cannot be barged by your own tile. */
196 seat?: SeatId;
197}
198
199export interface World {
200 /** Where tiles come to rest — inside the wall square. */
201 bounds: Rect;
202 /** Stacks of two still standing. Half and spent stacks are not obstacles. */
203 walls: Rect[];
204 bodies: Body[];
205 /** Left-over time from the last frame, so steps stay a fixed size. */
206 carry: number;
207 /**
208 * Overlaps pushed apart in the last step. The pile is not settled while this
209 * is non-zero, however still everything looks — two tiles asleep inside each
210 * other would otherwise stay that way for the rest of the hand, because a
211 * pile that has stopped moving stops being stepped.
212 */
213 contacts: number;
214 /** Steps spent untangling a pile that is otherwise asleep, so it cannot spin. */
215 relaxed: number;
216}
217
218export interface Spawn {
219 tile: Tile;
220 seat: SeatId;
221 x: number;
222 y: number;
223 vx: number;
224 vy: number;
225 z: number;
226 vz: number;
227 angle: number;
228 spin: number;
229 /** Whole turns to make in the air. It lands face up whatever this is. */
230 flipTurns?: number;
231 /** Seconds of flight those turns are spread over. */
232 flipOver?: number;
233 flipAxis?: number;
234 w: number;
235 h: number;
236 /** Drawn this much bigger to start with, easing to its pool size. */
237 scale?: number;
238 /** Already settled — a pile being rebuilt after a reload or an undo. */
239 atRest?: boolean;
240}
241
242export function createWorld(bounds: Rect, walls: Rect[] = []): World {
243 return { bounds, walls, bodies: [], carry: 0, contacts: 0, relaxed: 0 };
244}
245
246export function addBody(world: World, s: Spawn): Body {
247 const body: Body = {
248 tile: s.tile,
249 seat: s.seat,
250 x: s.x,
251 y: s.y,
252 vx: s.atRest ? 0 : s.vx,
253 vy: s.atRest ? 0 : s.vy,
254 z: s.atRest ? 0 : s.z,
255 vz: s.atRest ? 0 : s.vz,
256 angle: s.angle,
257 spin: s.atRest ? 0 : s.spin,
258 flip: 0,
259 // Spread the turns over the flight, so the tile comes down as it comes back
260 // round to face up rather than being snapped there on landing.
261 flipSpin:
262 s.atRest || !s.flipTurns || !s.flipOver ? 0 : (TAU * s.flipTurns) / s.flipOver,
263 flipAxis: s.flipAxis ?? 0,
264 w: s.w,
265 h: s.h,
266 scale: s.atRest ? 1 : s.scale ?? 1,
267 entered: !!s.atRest,
268 resting: !!s.atRest,
269 still: s.atRest ? SLEEP_STEPS : 0,
270 age: 0,
271 awake: 0,
272 };
273 world.bodies.push(body);
274 if (s.atRest) {
275 // A tile dropped straight into a settled pile still has to make room. This
276 // is a first shove only — the relaxing below finishes the job, which matters
277 // for a whole pile rebuilt at once when a saved game is picked up.
278 separate(world, body);
279 world.contacts++;
280 }
281 return body;
282}
283
284// ---- rotated rectangles ---------------------------------------------------
285
286/** Distance from a box's centre to its edge, measured along `ax`. */
287function reach(b: Box, ax: { x: number; y: number }): number {
288 const c = Math.cos(b.angle);
289 const s = Math.sin(b.angle);
290 return (
291 Math.abs(c * ax.x + s * ax.y) * (b.w / 2) + Math.abs(-s * ax.x + c * ax.y) * (b.h / 2)
292 );
293}
294
295/** The rotated rectangle's own bounding box, for the pool's straight edges. */
296function aabbHalf(b: Box) {
297 const c = Math.abs(Math.cos(b.angle));
298 const s = Math.abs(Math.sin(b.angle));
299 return { x: (b.w / 2) * c + (b.h / 2) * s, y: (b.w / 2) * s + (b.h / 2) * c };
300}
301
302/** Enough to skip a pair without doing the real work. */
303const circumradius = (b: Box) => Math.hypot(b.w, b.h) / 2;
304
305/**
306 * Separating axis test between two rectangles at any angle. Returns the
307 * shallowest way out — the direction to push `b` away from `a`, and by how much
308 * — or null if they are clear of each other.
309 *
310 * Four axes is all a pair of rectangles needs: each box's two edge normals.
311 */
312function overlapOf(a: Box, b: Box): { nx: number; ny: number; depth: number } | null {
313 const ca = Math.cos(a.angle);
314 const sa = Math.sin(a.angle);
315 const cb = Math.cos(b.angle);
316 const sb = Math.sin(b.angle);
317 const axes = [
318 { x: ca, y: sa },
319 { x: -sa, y: ca },
320 { x: cb, y: sb },
321 { x: -sb, y: cb },
322 ];
323
324 const dx = b.x - a.x;
325 const dy = b.y - a.y;
326 let depth = Infinity;
327 let nx = 0;
328 let ny = 0;
329
330 for (const ax of axes) {
331 const gap = reach(a, ax) + reach(b, ax) - Math.abs(dx * ax.x + dy * ax.y);
332 if (gap <= 0) return null;
333 if (gap < depth) {
334 depth = gap;
335 // Always pointing from a towards b, so callers need not guess.
336 const sign = dx * ax.x + dy * ax.y < 0 ? -1 : 1;
337 nx = ax.x * sign;
338 ny = ax.y * sign;
339 }
340 }
341 return { nx, ny, depth };
342}
343
344/** A standing stack, as something the tests above can chew on. */
345const boxOf = (r: Rect): Box => ({
346 x: r.x + r.w / 2,
347 y: r.y + r.h / 2,
348 w: r.w,
349 h: r.h,
350 angle: 0,
351});
352
353// ---- stepping -------------------------------------------------------------
354
355const inside = (r: Rect, x: number, y: number) =>
356 x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
357
358/**
359 * Run the world forward. `elapsed` is real seconds since the last call; it is
360 * consumed in fixed steps so the result does not depend on the frame rate.
361 * Returns the impacts worth a sound.
362 */
363export function advance(world: World, elapsed: number): Impact[] {
364 world.carry += Math.max(0, elapsed);
365 let steps = Math.floor(world.carry / FIXED_DT);
366 if (steps > MAX_SUBSTEPS) {
367 // Drop the backlog rather than working through it.
368 world.carry = 0;
369 steps = MAX_SUBSTEPS;
370 } else {
371 world.carry -= steps * FIXED_DT;
372 }
373
374 const impacts: Impact[] = [];
375 for (let i = 0; i < steps; i++) step(world, impacts);
376 return impacts;
377}
378
379/** One fixed step. Exported for the tests, which drive it directly. */
380export function step(world: World, impacts: Impact[] = []): Impact[] {
381 const dt = FIXED_DT;
382 world.contacts = 0;
383
384 for (const b of world.bodies) {
385 if (b.scale !== 1) {
386 b.scale += (1 - b.scale) * Math.min(1, SCALE_EASE * dt);
387 if (Math.abs(b.scale - 1) < 0.002) b.scale = 1;
388 }
389 if (b.resting) continue;
390 b.age++;
391 b.awake++;
392
393 // --- through the air ---
394 if (b.z > 0 || b.vz !== 0) {
395 b.vz -= GRAVITY * dt;
396 b.z += b.vz * dt;
397 if (b.z <= 0) {
398 const landing = Math.abs(b.vz);
399 b.z = 0;
400 // Below a knock it stops dead rather than shivering out a bounce.
401 b.vz = landing > 40 ? landing * Z_RESTITUTION : 0;
402 const strength = Math.min(1, landing / 900);
403 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
404 }
405 }
406
407 b.x += b.vx * dt;
408 b.y += b.vy * dt;
409 b.angle += b.spin * dt;
410
411 // Turning over. In the air it tumbles; once it is down, whatever is left of
412 // the turn is taken up so it ends flat on its back with its face showing.
413 if (b.flipSpin !== 0) {
414 if (b.z > 0) {
415 b.flip += b.flipSpin * dt;
416 } else {
417 const target = Math.round(b.flip / TAU) * TAU;
418 b.flip += (target - b.flip) * Math.min(1, FLIP_SETTLE * dt);
419 if (Math.abs(target - b.flip) < 0.01) {
420 b.flip = target;
421 b.flipSpin = 0;
422 }
423 }
424 }
425
426 if (inside(world.bounds, b.x, b.y)) b.entered = true;
427 else if (b.age > ENTRY_GRACE) {
428 // Out of time going the long way round. Put it in, gently.
429 b.entered = true;
430 b.z = 0;
431 b.vz = 0;
432 clampInto(world.bounds, b);
433 }
434
435 // --- on the felt ---
436 // Strictly z <= 0, not ON_FELT: friction is between the tile and the cloth,
437 // so a tile still in the air keeps the speed it was thrown with. ON_FELT is
438 // only about being low enough to be in another tile's way.
439 if (b.z <= 0) {
440 damp(b, dt);
441 // A tile that fell short skids in rather than sitting outside the pool.
442 if (!b.entered) pullIn(world, b, dt);
443 }
444
445 // A tile still above the wall is clear of it.
446 if (b.z < WALL_HEIGHT) {
447 for (const wall of world.walls) hitWall(b, wall, impacts);
448 }
449
450 // The pool's edge is the inside face of the wall, and it is only as tall as
451 // the wall — a tile lobbed high is over the top of it, not stopped by it.
452 if (b.entered && b.z < WALL_HEIGHT) keepInBounds(world, b, impacts);
453 }
454
455 collideTiles(world, impacts);
456 // Being shoved by a neighbour can put a tile back over the edge, and a tile
457 // that then fell asleep out there would stay out there. Only awake ones need
458 // it: resolvePair never moves a tile that has settled.
459 // Resting tiles included: they get pushed about by the untangling above, and
460 // a tile shoved over the edge must not be left there just because it is asleep.
461 for (const b of world.bodies) {
462 if (b.entered && b.z < WALL_HEIGHT) clampInto(world.bounds, b);
463 }
464 // Deciding to sleep comes last, so it judges where the step actually left
465 // things — before, a contact resolved after the decision would undo it and a
466 // crowded pool would stay awake for ever.
467 for (const b of world.bodies) if (!b.resting) trySleep(b);
468
469 // A pile that has stopped moving but is still untangling itself keeps being
470 // stepped, up to a point. Without the limit a configuration that cannot quite
471 // be resolved would keep the loop running for the rest of the hand.
472 world.relaxed = world.contacts > 0 && world.bodies.every((b) => b.resting) ? world.relaxed + 1 : 0;
473 return impacts;
474}
475
476/**
477 * The table has been re-measured — the window resized, or the wall was eaten
478 * further back. The tiles keep where they are, but a pool that shrank must not
479 * leave any of them stranded outside it, and the ones it moves have to wake up
480 * so they can settle again.
481 */
482export function reshape(world: World, bounds: Rect, walls: Rect[]) {
483 world.bounds = bounds;
484 world.walls = walls;
485 for (const b of world.bodies) {
486 if (!b.entered) continue;
487 const x = b.x;
488 const y = b.y;
489 clampInto(bounds, b);
490 if (b.x !== x || b.y !== y) wake(b);
491 }
492}
493
494function damp(b: Body, dt: number) {
495 const k = Math.exp(-FELT_DAMP * dt);
496 b.vx *= k;
497 b.vy *= k;
498 b.spin *= Math.exp(-SPIN_DAMP * dt);
499
500 const speed = Math.hypot(b.vx, b.vy);
501 if (speed > 0) {
502 const next = Math.max(0, speed - FELT_STOP * dt);
503 b.vx = (b.vx / speed) * next;
504 b.vy = (b.vy / speed) * next;
505 }
506 const spin = Math.abs(b.spin);
507 if (spin > 0) b.spin = Math.sign(b.spin) * Math.max(0, spin - SPIN_STOP * dt);
508}
509
510/** Nudges a tile that landed outside the pool towards the rest of them. */
511function pullIn(world: World, b: Body, dt: number) {
512 const cx = world.bounds.x + world.bounds.w / 2;
513 const cy = world.bounds.y + world.bounds.h / 2;
514 const dx = cx - b.x;
515 const dy = cy - b.y;
516 const d = Math.hypot(dx, dy) || 1;
517 b.vx += (dx / d) * ENTRY_PULL * dt;
518 b.vy += (dy / d) * ENTRY_PULL * dt;
519}
520
521/** Bounce off a standing stack, corner to corner if that is how it hits. */
522function hitWall(b: Body, wall: Rect, impacts: Impact[]) {
523 const hit = overlapOf(boxOf(wall), b);
524 if (!hit || hit.depth <= CONTACT_SLOP) return;
525
526 const speed = Math.hypot(b.vx, b.vy);
527 b.x += hit.nx * hit.depth;
528 b.y += hit.ny * hit.depth;
529 // Reflect whatever was heading into the wall; keep what was sliding along it.
530 const into = b.vx * hit.nx + b.vy * hit.ny;
531 if (into < 0) {
532 b.vx -= hit.nx * into * (1 + BOUND_RESTITUTION);
533 b.vy -= hit.ny * into * (1 + BOUND_RESTITUTION);
534 }
535 b.spin *= 0.7;
536 b.resting = false;
537 b.still = 0;
538 const strength = Math.min(1, speed / 1100);
539 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
540}
541
542/** The pool's edge. Once a tile is in, it stays in — this is the invariant the
543 * tests pin, since a discard that slid off the table would be lost. */
544function keepInBounds(world: World, b: Body, impacts: Impact[]) {
545 const half = aabbHalf(b);
546 const { x, y, w, h } = world.bounds;
547 // A pool narrower than a tile would otherwise fight itself; centre instead.
548 const minX = w <= half.x * 2 ? x + w / 2 : x + half.x;
549 const maxX = w <= half.x * 2 ? x + w / 2 : x + w - half.x;
550 const minY = h <= half.y * 2 ? y + h / 2 : y + half.y;
551 const maxY = h <= half.y * 2 ? y + h / 2 : y + h - half.y;
552
553 let hit = 0;
554 let edge: Edge | undefined;
555 if (b.x < minX) {
556 b.x = minX;
557 hit = Math.max(hit, Math.abs(b.vx));
558 edge = 'left';
559 b.vx = Math.abs(b.vx) * BOUND_RESTITUTION;
560 b.vy *= BOUND_FRICTION;
561 } else if (b.x > maxX) {
562 b.x = maxX;
563 hit = Math.max(hit, Math.abs(b.vx));
564 edge = 'right';
565 b.vx = -Math.abs(b.vx) * BOUND_RESTITUTION;
566 b.vy *= BOUND_FRICTION;
567 }
568 if (b.y < minY) {
569 b.y = minY;
570 if (Math.abs(b.vy) > hit) edge = 'top';
571 hit = Math.max(hit, Math.abs(b.vy));
572 b.vy = Math.abs(b.vy) * BOUND_RESTITUTION;
573 b.vx *= BOUND_FRICTION;
574 } else if (b.y > maxY) {
575 b.y = maxY;
576 if (Math.abs(b.vy) > hit) edge = 'bottom';
577 hit = Math.max(hit, Math.abs(b.vy));
578 b.vy = -Math.abs(b.vy) * BOUND_RESTITUTION;
579 b.vx *= BOUND_FRICTION;
580 }
581 // Only a real knock counts as being disturbed. A tile held against the edge
582 // by its neighbours is clamped every single step, and treating that as a knock
583 // would keep the whole pool awake for ever.
584 if (hit > SLEEP_SPEED) {
585 b.still = 0;
586 const strength = Math.min(1, hit / 1100);
587 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength, edge, seat: b.seat });
588 }
589}
590
591/**
592 * Tile against tile.
593 *
594 * Only tiles flat on the felt take part, so a thrown tile passes over the pile
595 * instead of shouldering through it, and a cheap circle test throws out the pairs
596 * that are nowhere near before the real rectangle test runs. Pairs where both
597 * tiles have settled are left alone entirely, which is nearly all of them.
598 */
599function collideTiles(world: World, impacts: Impact[]) {
600 const bodies = world.bodies;
601 for (let i = 0; i < bodies.length; i++) {
602 const a = bodies[i];
603 if (a.z > ON_FELT) continue;
604 for (let j = i + 1; j < bodies.length; j++) {
605 const b = bodies[j];
606 if (b.z > ON_FELT) continue;
607 if (Math.hypot(b.x - a.x, b.y - a.y) > circumradius(a) + circumradius(b)) continue;
608 // Two tiles that have both settled are still pushed apart if they are
609 // inside each other — they are just not woken up for it. Skipping the pair
610 // outright was how a pile could end up with tiles sharing ground and stay
611 // that way, since nothing steps a pile that has stopped moving.
612 resolvePair(a, b, impacts, world);
613 }
614 }
615}
616
617function resolvePair(a: Body, b: Body, impacts: Impact[], world: World) {
618 const hit = overlapOf(a, b);
619 if (!hit) return;
620 // Resting in contact is not a collision. See CONTACT_SLOP.
621 const depth = hit.depth - CONTACT_SLOP;
622 if (depth <= 0) return;
623 const { nx, ny } = hit;
624
625 world.contacts++;
626 // Push apart. A tile that has settled is the heavy one: a tile thrown into a
627 // pool shoulders in, rather than the pool scattering out of its way.
628 const aShare = a.resting === b.resting ? 0.5 : a.resting ? 0 : 1;
629 const bShare = 1 - aShare;
630 a.x -= nx * depth * aShare;
631 a.y -= ny * depth * aShare;
632 b.x += nx * depth * bShare;
633 b.y += ny * depth * bShare;
634
635 // Impulse along the way out, plus a spin kick off what is left over.
636 //
637 // Only a genuine approach speed counts, and only that wakes anything. Nudging
638 // two touching tiles apart is not a collision: a jammed corner of the pool is
639 // corrected by a fraction of a pixel every step for as long as it is jammed,
640 // and treating each of those as a shove would keep the pile awake for ever.
641 const rvx = b.vx - a.vx;
642 const rvy = b.vy - a.vy;
643 const along = rvx * nx + rvy * ny;
644 if (along >= -SLEEP_SPEED) return;
645
646 const jolt = -along * (1 + TILE_RESTITUTION) * 0.5;
647 a.vx -= nx * jolt;
648 a.vy -= ny * jolt;
649 b.vx += nx * jolt;
650 b.vy += ny * jolt;
651
652 const tangent = rvx * -ny + rvy * nx;
653 a.spin -= tangent * SPIN_TRANSFER * 0.06;
654 b.spin += tangent * SPIN_TRANSFER * 0.06;
655
656 const strength = Math.min(1, Math.abs(along) / 900);
657 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
658
659 // Whatever was asleep has been shoved, so it is awake now.
660 wake(a);
661 wake(b);
662}
663
664function wake(b: Body) {
665 if (b.resting) b.awake = 0;
666 b.resting = false;
667 b.still = 0;
668}
669
670function sleep(b: Body) {
671 b.vx = 0;
672 b.vy = 0;
673 b.spin = 0;
674 b.z = 0;
675 b.vz = 0;
676 // Face up, always. A tile lying face down in the discards would be a tile
677 // nobody can read, so this is a guarantee and not an easing.
678 b.flip = Math.round(b.flip / TAU) * TAU;
679 b.flipSpin = 0;
680 b.resting = true;
681 b.awake = 0;
682}
683
684function trySleep(b: Body) {
685 const speed = Math.hypot(b.vx, b.vy);
686 const slow =
687 b.entered &&
688 b.z <= 0 &&
689 b.vz === 0 &&
690 b.flipSpin === 0 &&
691 speed < SLEEP_SPEED &&
692 Math.abs(b.spin) < SLEEP_SPIN;
693 if (slow && ++b.still >= SLEEP_STEPS) return sleep(b);
694 if (!slow) b.still = 0;
695 // Backstop: shuffling about in a crowded pool for this long is settled enough.
696 if (b.entered && b.awake > AWAKE_LIMIT && speed < SLEEP_SPEED * 4) sleep(b);
697}
698
699/**
700 * Make room for a tile placed straight into a settled pile, without running
701 * time. Used when a pile is rebuilt — a reload, an undo — where the tiles have
702 * to be somewhere sensible immediately and nothing should appear to move.
703 */
704function separate(world: World, body: Body, passes = 16) {
705 // Which way to go when two tiles are exactly on top of each other. Stepping
706 // by the golden angle fans successive tiles out in every direction, where a
707 // fixed axis would march them all one way and pack them against a pool edge.
708 const escape = world.bodies.indexOf(body) * 2.39996;
709
710 for (let p = 0; p < passes; p++) {
711 let moved = false;
712 for (const other of world.bodies) {
713 if (other === body) continue;
714 const hit = overlapOf(other, body);
715 if (!hit || hit.depth <= CONTACT_SLOP) continue;
716 if (Math.hypot(body.x - other.x, body.y - other.y) < 0.0001) {
717 body.x += Math.cos(escape + p) * hit.depth;
718 body.y += Math.sin(escape + p) * hit.depth;
719 } else {
720 body.x += hit.nx * hit.depth;
721 body.y += hit.ny * hit.depth;
722 }
723 moved = true;
724 }
725 clampInto(world.bounds, body);
726 if (!moved) break;
727 }
728}
729
730function clampInto(r: Rect, b: Body) {
731 const half = aabbHalf(b);
732 const minX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + half.x;
733 const maxX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + r.w - half.x;
734 const minY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + half.y;
735 const maxY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + r.h - half.y;
736 b.x = Math.min(maxX, Math.max(minX, b.x));
737 b.y = Math.min(maxY, Math.max(minY, b.y));
738}
739
740/**
741 * How long a motionless pile is allowed to keep untangling itself before the
742 * result is accepted as good enough. Anything still overlapping after this is
743 * doing so by a fraction of a pixel, and the loop has better things to do than
744 * keep running over it.
745 */
746const RELAX_LIMIT = 90;
747
748/** Whether everything has settled — what the render loop idles on. */
749export const settled = (world: World) =>
750 world.bodies.every((b) => b.resting && b.scale === 1) &&
751 (world.contacts === 0 || world.relaxed > RELAX_LIMIT);
752
753/** How square-on the face is: 1 flat on its back, 0 edge-on, negative face down.
754 * The renderer squashes the tile by this along its tumbling axis. */
755export const faceOn = (b: Body) => Math.cos(b.flip);
756
757/** How far outside the pool a tile is sitting. The tests' invariant. */
758export function outside(b: Body, pool: Rect): number {
759 const half = aabbHalf(b);
760 return Math.max(
761 0,
762 pool.x + half.x - b.x,
763 b.x - (pool.x + pool.w - half.x),
764 pool.y + half.y - b.y,
765 b.y - (pool.y + pool.h - half.y),
766 );
767}
768
769/**
770 * A finger, or a cursor, pushing the tiles about in the middle — 洗牌, the thing
771 * everybody does to a pool of discards while waiting for their turn.
772 *
773 * Modelled as a circle that simply cannot be inside a tile: anything it touches
774 * is shoved clear of it and handed some of the speed it was moving at. It has no
775 * mass and takes no impulse back, which is what a finger on a table is.
776 */
777export function stir(
778 world: World,
779 x: number,
780 y: number,
781 vx: number,
782 vy: number,
783 radius: number,
784) {
785 // A frantic swipe should not fire tiles off like bullets.
786 const speed = Math.hypot(vx, vy);
787 const trim = speed > STIR_MAX_SPEED ? STIR_MAX_SPEED / speed : 1;
788
789 for (const b of world.bodies) {
790 if (b.z > ON_FELT) continue;
791 const dx = b.x - x;
792 const dy = b.y - y;
793 const clear = radius + circumradius(b);
794 const d = Math.hypot(dx, dy);
795 if (d > clear) continue;
796
797 const nx = d < 0.001 ? 1 : dx / d;
798 const ny = d < 0.001 ? 0 : dy / d;
799 b.x = x + nx * clear;
800 b.y = y + ny * clear;
801 b.vx += vx * trim * STIR_DRAG + nx * STIR_NUDGE;
802 b.vy += vy * trim * STIR_DRAG + ny * STIR_NUDGE;
803 // Dragged past off-centre, a tile turns under your finger.
804 b.spin += (vx * trim * ny - vy * trim * nx) * 0.0016;
805 wake(b);
806 }
807}
808
809/** Whether two tiles are sharing ground, which they must never do at rest. */
810export function overlapping(a: Body, b: Body): number {
811 const hit = overlapOf(a, b);
812 return hit ? hit.depth : 0;
813}
814
815/** Scale a tile is drawn at, given how high it is. Sells the arc on a flat
816 * canvas; the renderer offsets the shadow by the same height. */
817export const zScale = (z: number) => 1 + z * 0.0016;
818
819/**
820 * The upward kick that puts a tile back on the felt after `seconds` in the air.
821 * How a throw is aimed: pick how long it should take, and the horizontal speed
822 * follows from the distance.
823 */
824export const liftFor = (seconds: number) => (GRAVITY * seconds) / 2;
825
826/** How high that kick gets — worth checking against WALL_HEIGHT. */
827export const peakOf = (vz: number) => (vz * vz) / (2 * GRAVITY);