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 * Whose side of the table a tile has ended up off, if it is off any of them.
360 * The furthest it is out, so a tile that overshot a corner belongs to whichever
361 * of the two it went past by more.
362 */
363function outsideEdge(r: Rect, b: Body): Edge | undefined {
364 const out: [Edge, number][] = [
365 ['left', r.x - b.x],
366 ['right', b.x - (r.x + r.w)],
367 ['top', r.y - b.y],
368 ['bottom', b.y - (r.y + r.h)],
369 ];
370 let worst: [Edge, number] = out[0];
371 for (const one of out) if (one[1] > worst[1]) worst = one;
372 return worst[1] > 0 ? worst[0] : undefined;
373}
374
375/**
376 * Run the world forward. `elapsed` is real seconds since the last call; it is
377 * consumed in fixed steps so the result does not depend on the frame rate.
378 * Returns the impacts worth a sound.
379 */
380export function advance(world: World, elapsed: number): Impact[] {
381 world.carry += Math.max(0, elapsed);
382 let steps = Math.floor(world.carry / FIXED_DT);
383 if (steps > MAX_SUBSTEPS) {
384 // Drop the backlog rather than working through it.
385 world.carry = 0;
386 steps = MAX_SUBSTEPS;
387 } else {
388 world.carry -= steps * FIXED_DT;
389 }
390
391 const impacts: Impact[] = [];
392 for (let i = 0; i < steps; i++) step(world, impacts);
393 return impacts;
394}
395
396/** One fixed step. Exported for the tests, which drive it directly. */
397export function step(world: World, impacts: Impact[] = []): Impact[] {
398 const dt = FIXED_DT;
399 world.contacts = 0;
400
401 for (const b of world.bodies) {
402 if (b.scale !== 1) {
403 b.scale += (1 - b.scale) * Math.min(1, SCALE_EASE * dt);
404 if (Math.abs(b.scale - 1) < 0.002) b.scale = 1;
405 }
406 if (b.resting) continue;
407 b.age++;
408 b.awake++;
409
410 // --- through the air ---
411 if (b.z > 0 || b.vz !== 0) {
412 b.vz -= GRAVITY * dt;
413 b.z += b.vz * dt;
414 if (b.z <= 0) {
415 const landing = Math.abs(b.vz);
416 b.z = 0;
417 // Below a knock it stops dead rather than shivering out a bounce.
418 b.vz = landing > 40 ? landing * Z_RESTITUTION : 0;
419 const strength = Math.min(1, landing / 900);
420 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
421 }
422 }
423
424 b.x += b.vx * dt;
425 b.y += b.vy * dt;
426 b.angle += b.spin * dt;
427
428 // Turning over. In the air it tumbles; once it is down, whatever is left of
429 // the turn is taken up so it ends flat on its back with its face showing.
430 if (b.flipSpin !== 0) {
431 if (b.z > 0) {
432 b.flip += b.flipSpin * dt;
433 } else {
434 const target = Math.round(b.flip / TAU) * TAU;
435 b.flip += (target - b.flip) * Math.min(1, FLIP_SETTLE * dt);
436 if (Math.abs(target - b.flip) < 0.01) {
437 b.flip = target;
438 b.flipSpin = 0;
439 }
440 }
441 }
442
443 if (inside(world.bounds, b.x, b.y)) b.entered = true;
444 else if (b.age > ENTRY_GRACE) {
445 // Out of time going the long way round. Put it in, gently — but this is a
446 // tile that ended up off the table on somebody's side, which is worth
447 // saying so even though nothing was actually struck.
448 const edge = outsideEdge(world.bounds, b);
449 if (edge) impacts.push({ x: b.x, y: b.y, strength: 0.3, edge, seat: b.seat });
450 b.entered = true;
451 b.z = 0;
452 b.vz = 0;
453 clampInto(world.bounds, b);
454 }
455
456 // --- on the felt ---
457 // Strictly z <= 0, not ON_FELT: friction is between the tile and the cloth,
458 // so a tile still in the air keeps the speed it was thrown with. ON_FELT is
459 // only about being low enough to be in another tile's way.
460 if (b.z <= 0) {
461 damp(b, dt);
462 // A tile that fell short skids in rather than sitting outside the pool.
463 if (!b.entered) pullIn(world, b, dt);
464 }
465
466 // A tile still above the wall is clear of it.
467 if (b.z < WALL_HEIGHT) {
468 for (const wall of world.walls) hitWall(b, wall, impacts);
469 }
470
471 // The pool's edge is the inside face of the wall, and it is only as tall as
472 // the wall — a tile lobbed high is over the top of it, not stopped by it.
473 if (b.entered && b.z < WALL_HEIGHT) keepInBounds(world, b, impacts);
474 }
475
476 collideTiles(world, impacts);
477 // Being shoved by a neighbour can put a tile back over the edge, and a tile
478 // that then fell asleep out there would stay out there. Only awake ones need
479 // it: resolvePair never moves a tile that has settled.
480 // Resting tiles included: they get pushed about by the untangling above, and
481 // a tile shoved over the edge must not be left there just because it is asleep.
482 for (const b of world.bodies) {
483 if (b.entered && b.z < WALL_HEIGHT) clampInto(world.bounds, b);
484 }
485 // Deciding to sleep comes last, so it judges where the step actually left
486 // things — before, a contact resolved after the decision would undo it and a
487 // crowded pool would stay awake for ever.
488 for (const b of world.bodies) if (!b.resting) trySleep(b);
489
490 // A pile that has stopped moving but is still untangling itself keeps being
491 // stepped, up to a point. Without the limit a configuration that cannot quite
492 // be resolved would keep the loop running for the rest of the hand.
493 world.relaxed = world.contacts > 0 && world.bodies.every((b) => b.resting) ? world.relaxed + 1 : 0;
494 return impacts;
495}
496
497/**
498 * The table has been re-measured — the window resized, or the wall was eaten
499 * further back. The tiles keep where they are, but a pool that shrank must not
500 * leave any of them stranded outside it, and the ones it moves have to wake up
501 * so they can settle again.
502 */
503export function reshape(world: World, bounds: Rect, walls: Rect[]) {
504 world.bounds = bounds;
505 world.walls = walls;
506 for (const b of world.bodies) {
507 if (!b.entered) continue;
508 const x = b.x;
509 const y = b.y;
510 clampInto(bounds, b);
511 if (b.x !== x || b.y !== y) wake(b);
512 }
513}
514
515function damp(b: Body, dt: number) {
516 const k = Math.exp(-FELT_DAMP * dt);
517 b.vx *= k;
518 b.vy *= k;
519 b.spin *= Math.exp(-SPIN_DAMP * dt);
520
521 const speed = Math.hypot(b.vx, b.vy);
522 if (speed > 0) {
523 const next = Math.max(0, speed - FELT_STOP * dt);
524 b.vx = (b.vx / speed) * next;
525 b.vy = (b.vy / speed) * next;
526 }
527 const spin = Math.abs(b.spin);
528 if (spin > 0) b.spin = Math.sign(b.spin) * Math.max(0, spin - SPIN_STOP * dt);
529}
530
531/** Nudges a tile that landed outside the pool towards the rest of them. */
532function pullIn(world: World, b: Body, dt: number) {
533 const cx = world.bounds.x + world.bounds.w / 2;
534 const cy = world.bounds.y + world.bounds.h / 2;
535 const dx = cx - b.x;
536 const dy = cy - b.y;
537 const d = Math.hypot(dx, dy) || 1;
538 b.vx += (dx / d) * ENTRY_PULL * dt;
539 b.vy += (dy / d) * ENTRY_PULL * dt;
540}
541
542/** Bounce off a standing stack, corner to corner if that is how it hits. */
543function hitWall(b: Body, wall: Rect, impacts: Impact[]) {
544 const hit = overlapOf(boxOf(wall), b);
545 if (!hit || hit.depth <= CONTACT_SLOP) return;
546
547 const speed = Math.hypot(b.vx, b.vy);
548 b.x += hit.nx * hit.depth;
549 b.y += hit.ny * hit.depth;
550 // Reflect whatever was heading into the wall; keep what was sliding along it.
551 const into = b.vx * hit.nx + b.vy * hit.ny;
552 if (into < 0) {
553 b.vx -= hit.nx * into * (1 + BOUND_RESTITUTION);
554 b.vy -= hit.ny * into * (1 + BOUND_RESTITUTION);
555 }
556 b.spin *= 0.7;
557 b.resting = false;
558 b.still = 0;
559 const strength = Math.min(1, speed / 1100);
560 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
561}
562
563/** The pool's edge. Once a tile is in, it stays in — this is the invariant the
564 * tests pin, since a discard that slid off the table would be lost. */
565function keepInBounds(world: World, b: Body, impacts: Impact[]) {
566 const half = aabbHalf(b);
567 const { x, y, w, h } = world.bounds;
568 // A pool narrower than a tile would otherwise fight itself; centre instead.
569 const minX = w <= half.x * 2 ? x + w / 2 : x + half.x;
570 const maxX = w <= half.x * 2 ? x + w / 2 : x + w - half.x;
571 const minY = h <= half.y * 2 ? y + h / 2 : y + half.y;
572 const maxY = h <= half.y * 2 ? y + h / 2 : y + h - half.y;
573
574 let hit = 0;
575 let edge: Edge | undefined;
576 if (b.x < minX) {
577 b.x = minX;
578 hit = Math.max(hit, Math.abs(b.vx));
579 edge = 'left';
580 b.vx = Math.abs(b.vx) * BOUND_RESTITUTION;
581 b.vy *= BOUND_FRICTION;
582 } else if (b.x > maxX) {
583 b.x = maxX;
584 hit = Math.max(hit, Math.abs(b.vx));
585 edge = 'right';
586 b.vx = -Math.abs(b.vx) * BOUND_RESTITUTION;
587 b.vy *= BOUND_FRICTION;
588 }
589 if (b.y < minY) {
590 b.y = minY;
591 if (Math.abs(b.vy) > hit) edge = 'top';
592 hit = Math.max(hit, Math.abs(b.vy));
593 b.vy = Math.abs(b.vy) * BOUND_RESTITUTION;
594 b.vx *= BOUND_FRICTION;
595 } else if (b.y > maxY) {
596 b.y = maxY;
597 if (Math.abs(b.vy) > hit) edge = 'bottom';
598 hit = Math.max(hit, Math.abs(b.vy));
599 b.vy = -Math.abs(b.vy) * BOUND_RESTITUTION;
600 b.vx *= BOUND_FRICTION;
601 }
602 // Only a real knock counts as being disturbed. A tile held against the edge
603 // by its neighbours is clamped every single step, and treating that as a knock
604 // would keep the whole pool awake for ever.
605 //
606 // Anything that does arrive under its own steam is reported, however gently:
607 // the edge is where somebody's tiles are, so a discard rolling into them is
608 // an event whatever speed it got there at. Which of them are loud enough to
609 // be worth a sound is the caller's business.
610 if (hit > SLEEP_SPEED) {
611 b.still = 0;
612 impacts.push({ x: b.x, y: b.y, strength: Math.min(1, hit / 1100), edge, seat: b.seat });
613 }
614}
615
616/**
617 * Tile against tile.
618 *
619 * Only tiles flat on the felt take part, so a thrown tile passes over the pile
620 * instead of shouldering through it, and a cheap circle test throws out the pairs
621 * that are nowhere near before the real rectangle test runs. Pairs where both
622 * tiles have settled are left alone entirely, which is nearly all of them.
623 */
624function collideTiles(world: World, impacts: Impact[]) {
625 const bodies = world.bodies;
626 for (let i = 0; i < bodies.length; i++) {
627 const a = bodies[i];
628 if (a.z > ON_FELT) continue;
629 for (let j = i + 1; j < bodies.length; j++) {
630 const b = bodies[j];
631 if (b.z > ON_FELT) continue;
632 if (Math.hypot(b.x - a.x, b.y - a.y) > circumradius(a) + circumradius(b)) continue;
633 // Two tiles that have both settled are still pushed apart if they are
634 // inside each other — they are just not woken up for it. Skipping the pair
635 // outright was how a pile could end up with tiles sharing ground and stay
636 // that way, since nothing steps a pile that has stopped moving.
637 resolvePair(a, b, impacts, world);
638 }
639 }
640}
641
642function resolvePair(a: Body, b: Body, impacts: Impact[], world: World) {
643 const hit = overlapOf(a, b);
644 if (!hit) return;
645 // Resting in contact is not a collision. See CONTACT_SLOP.
646 const depth = hit.depth - CONTACT_SLOP;
647 if (depth <= 0) return;
648 const { nx, ny } = hit;
649
650 world.contacts++;
651 // Push apart. A tile that has settled is the heavy one: a tile thrown into a
652 // pool shoulders in, rather than the pool scattering out of its way.
653 const aShare = a.resting === b.resting ? 0.5 : a.resting ? 0 : 1;
654 const bShare = 1 - aShare;
655 a.x -= nx * depth * aShare;
656 a.y -= ny * depth * aShare;
657 b.x += nx * depth * bShare;
658 b.y += ny * depth * bShare;
659
660 // Impulse along the way out, plus a spin kick off what is left over.
661 //
662 // Only a genuine approach speed counts, and only that wakes anything. Nudging
663 // two touching tiles apart is not a collision: a jammed corner of the pool is
664 // corrected by a fraction of a pixel every step for as long as it is jammed,
665 // and treating each of those as a shove would keep the pile awake for ever.
666 const rvx = b.vx - a.vx;
667 const rvy = b.vy - a.vy;
668 const along = rvx * nx + rvy * ny;
669 if (along >= -SLEEP_SPEED) return;
670
671 const jolt = -along * (1 + TILE_RESTITUTION) * 0.5;
672 a.vx -= nx * jolt;
673 a.vy -= ny * jolt;
674 b.vx += nx * jolt;
675 b.vy += ny * jolt;
676
677 const tangent = rvx * -ny + rvy * nx;
678 a.spin -= tangent * SPIN_TRANSFER * 0.06;
679 b.spin += tangent * SPIN_TRANSFER * 0.06;
680
681 const strength = Math.min(1, Math.abs(along) / 900);
682 if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength });
683
684 // Whatever was asleep has been shoved, so it is awake now.
685 wake(a);
686 wake(b);
687}
688
689function wake(b: Body) {
690 if (b.resting) b.awake = 0;
691 b.resting = false;
692 b.still = 0;
693}
694
695function sleep(b: Body) {
696 b.vx = 0;
697 b.vy = 0;
698 b.spin = 0;
699 b.z = 0;
700 b.vz = 0;
701 // Face up, always. A tile lying face down in the discards would be a tile
702 // nobody can read, so this is a guarantee and not an easing.
703 b.flip = Math.round(b.flip / TAU) * TAU;
704 b.flipSpin = 0;
705 b.resting = true;
706 b.awake = 0;
707}
708
709function trySleep(b: Body) {
710 const speed = Math.hypot(b.vx, b.vy);
711 const slow =
712 b.entered &&
713 b.z <= 0 &&
714 b.vz === 0 &&
715 b.flipSpin === 0 &&
716 speed < SLEEP_SPEED &&
717 Math.abs(b.spin) < SLEEP_SPIN;
718 if (slow && ++b.still >= SLEEP_STEPS) return sleep(b);
719 if (!slow) b.still = 0;
720 // Backstop: shuffling about in a crowded pool for this long is settled enough.
721 if (b.entered && b.awake > AWAKE_LIMIT && speed < SLEEP_SPEED * 4) sleep(b);
722}
723
724/**
725 * Make room for a tile placed straight into a settled pile, without running
726 * time. Used when a pile is rebuilt — a reload, an undo — where the tiles have
727 * to be somewhere sensible immediately and nothing should appear to move.
728 */
729function separate(world: World, body: Body, passes = 16) {
730 // Which way to go when two tiles are exactly on top of each other. Stepping
731 // by the golden angle fans successive tiles out in every direction, where a
732 // fixed axis would march them all one way and pack them against a pool edge.
733 const escape = world.bodies.indexOf(body) * 2.39996;
734
735 for (let p = 0; p < passes; p++) {
736 let moved = false;
737 for (const other of world.bodies) {
738 if (other === body) continue;
739 const hit = overlapOf(other, body);
740 if (!hit || hit.depth <= CONTACT_SLOP) continue;
741 if (Math.hypot(body.x - other.x, body.y - other.y) < 0.0001) {
742 body.x += Math.cos(escape + p) * hit.depth;
743 body.y += Math.sin(escape + p) * hit.depth;
744 } else {
745 body.x += hit.nx * hit.depth;
746 body.y += hit.ny * hit.depth;
747 }
748 moved = true;
749 }
750 clampInto(world.bounds, body);
751 if (!moved) break;
752 }
753}
754
755function clampInto(r: Rect, b: Body) {
756 const half = aabbHalf(b);
757 const minX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + half.x;
758 const maxX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + r.w - half.x;
759 const minY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + half.y;
760 const maxY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + r.h - half.y;
761 b.x = Math.min(maxX, Math.max(minX, b.x));
762 b.y = Math.min(maxY, Math.max(minY, b.y));
763}
764
765/**
766 * How long a motionless pile is allowed to keep untangling itself before the
767 * result is accepted as good enough. Anything still overlapping after this is
768 * doing so by a fraction of a pixel, and the loop has better things to do than
769 * keep running over it.
770 */
771const RELAX_LIMIT = 90;
772
773/** Whether everything has settled — what the render loop idles on. */
774export const settled = (world: World) =>
775 world.bodies.every((b) => b.resting && b.scale === 1) &&
776 (world.contacts === 0 || world.relaxed > RELAX_LIMIT);
777
778/** How square-on the face is: 1 flat on its back, 0 edge-on, negative face down.
779 * The renderer squashes the tile by this along its tumbling axis. */
780export const faceOn = (b: Body) => Math.cos(b.flip);
781
782/** How far outside the pool a tile is sitting. The tests' invariant. */
783export function outside(b: Body, pool: Rect): number {
784 const half = aabbHalf(b);
785 return Math.max(
786 0,
787 pool.x + half.x - b.x,
788 b.x - (pool.x + pool.w - half.x),
789 pool.y + half.y - b.y,
790 b.y - (pool.y + pool.h - half.y),
791 );
792}
793
794/**
795 * A finger, or a cursor, pushing the tiles about in the middle — 洗牌, the thing
796 * everybody does to a pool of discards while waiting for their turn.
797 *
798 * Modelled as a circle that simply cannot be inside a tile: anything it touches
799 * is shoved clear of it and handed some of the speed it was moving at. It has no
800 * mass and takes no impulse back, which is what a finger on a table is.
801 */
802export function stir(
803 world: World,
804 x: number,
805 y: number,
806 vx: number,
807 vy: number,
808 radius: number,
809) {
810 // A frantic swipe should not fire tiles off like bullets.
811 const speed = Math.hypot(vx, vy);
812 const trim = speed > STIR_MAX_SPEED ? STIR_MAX_SPEED / speed : 1;
813
814 for (const b of world.bodies) {
815 if (b.z > ON_FELT) continue;
816 const dx = b.x - x;
817 const dy = b.y - y;
818 const clear = radius + circumradius(b);
819 const d = Math.hypot(dx, dy);
820 if (d > clear) continue;
821
822 const nx = d < 0.001 ? 1 : dx / d;
823 const ny = d < 0.001 ? 0 : dy / d;
824 b.x = x + nx * clear;
825 b.y = y + ny * clear;
826 b.vx += vx * trim * STIR_DRAG + nx * STIR_NUDGE;
827 b.vy += vy * trim * STIR_DRAG + ny * STIR_NUDGE;
828 // Dragged past off-centre, a tile turns under your finger.
829 b.spin += (vx * trim * ny - vy * trim * nx) * 0.0016;
830 wake(b);
831 }
832}
833
834/** Whether two tiles are sharing ground, which they must never do at rest. */
835export function overlapping(a: Body, b: Body): number {
836 const hit = overlapOf(a, b);
837 return hit ? hit.depth : 0;
838}
839
840/** Scale a tile is drawn at, given how high it is. Sells the arc on a flat
841 * canvas; the renderer offsets the shadow by the same height. */
842export const zScale = (z: number) => 1 + z * 0.0016;
843
844/**
845 * The upward kick that puts a tile back on the felt after `seconds` in the air.
846 * How a throw is aimed: pick how long it should take, and the horizontal speed
847 * follows from the distance.
848 */
849export const liftFor = (seconds: number) => (GRAVITY * seconds) / 2;
850
851/** How high that kick gets — worth checking against WALL_HEIGHT. */
852export const peakOf = (vz: number) => (vz * vz) / (2 * GRAVITY);