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