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