| 1 | import type { Tile } from '../game/tiles'; |
| 2 | import 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. */ |
| 20 | export 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 | */ |
| 25 | const MAX_SUBSTEPS = 8; |
| 26 | |
| 27 | /** Falls onto the felt in about half a second from a normal throw. */ |
| 28 | const GRAVITY = 2600; |
| 29 | /** Tiles are dense and land flat; they do not bounce much. */ |
| 30 | const Z_RESTITUTION = 0.34; |
| 31 | /** Below this the tile is flat on the felt: sliding, and in the way of others. */ |
| 32 | const 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 | */ |
| 38 | export const WALL_HEIGHT = 30; |
| 39 | |
| 40 | /** Felt friction: an exponential part that kills speed, and a constant part |
| 41 | * that actually brings it to a stop rather than to an asymptote. */ |
| 42 | const FELT_DAMP = 4.2; |
| 43 | const FELT_STOP = 90; |
| 44 | const SPIN_DAMP = 5; |
| 45 | const SPIN_STOP = 1.2; |
| 46 | |
| 47 | /** |
| 48 | * Roughly how much longer a tile keeps travelling after it lands, as a time. |
| 49 | * Aiming a throw means solving for where it comes to *rest*, not where it first |
| 50 | * touches down, so `pool.ts` adds this to the flight time. |
| 51 | */ |
| 52 | export const SLIDE_TIME = 1 / FELT_DAMP; |
| 53 | |
| 54 | const BOUND_RESTITUTION = 0.42; |
| 55 | const BOUND_FRICTION = 0.86; |
| 56 | const TILE_RESTITUTION = 0.32; |
| 57 | /** How much of a glancing blow becomes spin. Tiles are light and skate. */ |
| 58 | const SPIN_TRANSFER = 0.06; |
| 59 | |
| 60 | /** Asleep after this many consecutive steps of going nowhere. */ |
| 61 | const SLEEP_SPEED = 7; |
| 62 | const SLEEP_SPIN = 0.2; |
| 63 | const SLEEP_STEPS = 10; |
| 64 | /** |
| 65 | * Overlap small enough to live with. Without this a crowded pool never sleeps: |
| 66 | * a tile squeezed between its neighbours and the pool's edge gets pushed out of |
| 67 | * contact and shoved back into it on every step, for ever. A fifth of a pixel is |
| 68 | * not something you can see, and it is what lets the pile go quiet. |
| 69 | */ |
| 70 | const CONTACT_SLOP = 0.2; |
| 71 | /** |
| 72 | * A body moving this slowly for this long is put to sleep whatever it thinks it |
| 73 | * is doing. The backstop that guarantees the pile always settles — counted from |
| 74 | * when it last woke, not from when it was thrown. |
| 75 | */ |
| 76 | const AWAKE_LIMIT = 600; |
| 77 | |
| 78 | /** Pulls a tile that landed short of the pool in towards the rest of them. */ |
| 79 | const ENTRY_PULL = 700; |
| 80 | /** |
| 81 | * How long a tile gets to find its own way into the pool before it is simply |
| 82 | * put there. A discard is game state made visible — it has to be in the middle |
| 83 | * where it can be seen and counted — so a tile that has got itself wedged |
| 84 | * against a standing stack, or is bouncing between two of them, cannot be left |
| 85 | * out there. Two seconds is far longer than any real throw takes to settle. |
| 86 | */ |
| 87 | const ENTRY_GRACE = 240; |
| 88 | |
| 89 | /** How fast a tile drawn at hand size shrinks to the size it is in the pool. */ |
| 90 | const SCALE_EASE = 6; |
| 91 | |
| 92 | export interface Rect { |
| 93 | x: number; |
| 94 | y: number; |
| 95 | w: number; |
| 96 | h: number; |
| 97 | } |
| 98 | |
| 99 | /** Anything the collision routines can treat as a rotated rectangle. */ |
| 100 | interface Box { |
| 101 | x: number; |
| 102 | y: number; |
| 103 | w: number; |
| 104 | h: number; |
| 105 | angle: number; |
| 106 | } |
| 107 | |
| 108 | export interface Body { |
| 109 | tile: Tile; |
| 110 | /** Who threw it — for the fly-out when it is claimed, not for any marking. */ |
| 111 | seat: SeatId; |
| 112 | /** Centre on the felt plane. */ |
| 113 | x: number; |
| 114 | y: number; |
| 115 | vx: number; |
| 116 | vy: number; |
| 117 | /** Height above the felt, and its rate. Only ever >= 0. */ |
| 118 | z: number; |
| 119 | vz: number; |
| 120 | angle: number; |
| 121 | spin: number; |
| 122 | w: number; |
| 123 | h: number; |
| 124 | /** |
| 125 | * Render-only: what to multiply the drawn size by, easing to 1. A tile is |
| 126 | * drawn big in a hand so it can be read, and small in the pool because that is |
| 127 | * the size it is in the wall, so a thrown one has to settle from one to the |
| 128 | * other. Eased here rather than in the renderer so it does not run at a |
| 129 | * different speed on a different frame rate. |
| 130 | */ |
| 131 | scale: number; |
| 132 | /** |
| 133 | * Whether it has ever been inside the pool. Until it has, it is free to fly |
| 134 | * over the wall from a seat's edge; once it has, the pool keeps it. |
| 135 | */ |
| 136 | entered: boolean; |
| 137 | resting: boolean; |
| 138 | /** Consecutive slow steps, counting towards sleep. */ |
| 139 | still: number; |
| 140 | /** Steps lived, for the grace period on getting into the pool. */ |
| 141 | age: number; |
| 142 | /** Steps since it last woke, for the backstop on settling. */ |
| 143 | awake: number; |
| 144 | } |
| 145 | |
| 146 | /** A collision loud enough to hear. `strength` is 0..1. */ |
| 147 | export interface Impact { |
| 148 | x: number; |
| 149 | y: number; |
| 150 | strength: number; |
| 151 | } |
| 152 | |
| 153 | export interface World { |
| 154 | /** Where tiles come to rest — inside the wall square. */ |
| 155 | bounds: Rect; |
| 156 | /** Stacks of two still standing. Half and spent stacks are not obstacles. */ |
| 157 | walls: Rect[]; |
| 158 | bodies: Body[]; |
| 159 | /** Left-over time from the last frame, so steps stay a fixed size. */ |
| 160 | carry: number; |
| 161 | } |
| 162 | |
| 163 | export interface Spawn { |
| 164 | tile: Tile; |
| 165 | seat: SeatId; |
| 166 | x: number; |
| 167 | y: number; |
| 168 | vx: number; |
| 169 | vy: number; |
| 170 | z: number; |
| 171 | vz: number; |
| 172 | angle: number; |
| 173 | spin: number; |
| 174 | w: number; |
| 175 | h: number; |
| 176 | /** Drawn this much bigger to start with, easing to its pool size. */ |
| 177 | scale?: number; |
| 178 | /** Already settled — a pile being rebuilt after a reload or an undo. */ |
| 179 | atRest?: boolean; |
| 180 | } |
| 181 | |
| 182 | export function createWorld(bounds: Rect, walls: Rect[] = []): World { |
| 183 | return { bounds, walls, bodies: [], carry: 0 }; |
| 184 | } |
| 185 | |
| 186 | export function addBody(world: World, s: Spawn): Body { |
| 187 | const body: Body = { |
| 188 | tile: s.tile, |
| 189 | seat: s.seat, |
| 190 | x: s.x, |
| 191 | y: s.y, |
| 192 | vx: s.atRest ? 0 : s.vx, |
| 193 | vy: s.atRest ? 0 : s.vy, |
| 194 | z: s.atRest ? 0 : s.z, |
| 195 | vz: s.atRest ? 0 : s.vz, |
| 196 | angle: s.angle, |
| 197 | spin: s.atRest ? 0 : s.spin, |
| 198 | w: s.w, |
| 199 | h: s.h, |
| 200 | scale: s.atRest ? 1 : s.scale ?? 1, |
| 201 | entered: !!s.atRest, |
| 202 | resting: !!s.atRest, |
| 203 | still: s.atRest ? SLEEP_STEPS : 0, |
| 204 | age: 0, |
| 205 | awake: 0, |
| 206 | }; |
| 207 | world.bodies.push(body); |
| 208 | // A tile dropped straight into a settled pile still has to make room. |
| 209 | if (s.atRest) separate(world, body); |
| 210 | return body; |
| 211 | } |
| 212 | |
| 213 | // ---- rotated rectangles --------------------------------------------------- |
| 214 | |
| 215 | /** Distance from a box's centre to its edge, measured along `ax`. */ |
| 216 | function reach(b: Box, ax: { x: number; y: number }): number { |
| 217 | const c = Math.cos(b.angle); |
| 218 | const s = Math.sin(b.angle); |
| 219 | return ( |
| 220 | Math.abs(c * ax.x + s * ax.y) * (b.w / 2) + Math.abs(-s * ax.x + c * ax.y) * (b.h / 2) |
| 221 | ); |
| 222 | } |
| 223 | |
| 224 | /** The rotated rectangle's own bounding box, for the pool's straight edges. */ |
| 225 | function aabbHalf(b: Box) { |
| 226 | const c = Math.abs(Math.cos(b.angle)); |
| 227 | const s = Math.abs(Math.sin(b.angle)); |
| 228 | return { x: (b.w / 2) * c + (b.h / 2) * s, y: (b.w / 2) * s + (b.h / 2) * c }; |
| 229 | } |
| 230 | |
| 231 | /** Enough to skip a pair without doing the real work. */ |
| 232 | const circumradius = (b: Box) => Math.hypot(b.w, b.h) / 2; |
| 233 | |
| 234 | /** |
| 235 | * Separating axis test between two rectangles at any angle. Returns the |
| 236 | * shallowest way out — the direction to push `b` away from `a`, and by how much |
| 237 | * — or null if they are clear of each other. |
| 238 | * |
| 239 | * Four axes is all a pair of rectangles needs: each box's two edge normals. |
| 240 | */ |
| 241 | function overlapOf(a: Box, b: Box): { nx: number; ny: number; depth: number } | null { |
| 242 | const ca = Math.cos(a.angle); |
| 243 | const sa = Math.sin(a.angle); |
| 244 | const cb = Math.cos(b.angle); |
| 245 | const sb = Math.sin(b.angle); |
| 246 | const axes = [ |
| 247 | { x: ca, y: sa }, |
| 248 | { x: -sa, y: ca }, |
| 249 | { x: cb, y: sb }, |
| 250 | { x: -sb, y: cb }, |
| 251 | ]; |
| 252 | |
| 253 | const dx = b.x - a.x; |
| 254 | const dy = b.y - a.y; |
| 255 | let depth = Infinity; |
| 256 | let nx = 0; |
| 257 | let ny = 0; |
| 258 | |
| 259 | for (const ax of axes) { |
| 260 | const gap = reach(a, ax) + reach(b, ax) - Math.abs(dx * ax.x + dy * ax.y); |
| 261 | if (gap <= 0) return null; |
| 262 | if (gap < depth) { |
| 263 | depth = gap; |
| 264 | // Always pointing from a towards b, so callers need not guess. |
| 265 | const sign = dx * ax.x + dy * ax.y < 0 ? -1 : 1; |
| 266 | nx = ax.x * sign; |
| 267 | ny = ax.y * sign; |
| 268 | } |
| 269 | } |
| 270 | return { nx, ny, depth }; |
| 271 | } |
| 272 | |
| 273 | /** A standing stack, as something the tests above can chew on. */ |
| 274 | const boxOf = (r: Rect): Box => ({ |
| 275 | x: r.x + r.w / 2, |
| 276 | y: r.y + r.h / 2, |
| 277 | w: r.w, |
| 278 | h: r.h, |
| 279 | angle: 0, |
| 280 | }); |
| 281 | |
| 282 | // ---- stepping ------------------------------------------------------------- |
| 283 | |
| 284 | const inside = (r: Rect, x: number, y: number) => |
| 285 | x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h; |
| 286 | |
| 287 | /** |
| 288 | * Run the world forward. `elapsed` is real seconds since the last call; it is |
| 289 | * consumed in fixed steps so the result does not depend on the frame rate. |
| 290 | * Returns the impacts worth a sound. |
| 291 | */ |
| 292 | export function advance(world: World, elapsed: number): Impact[] { |
| 293 | world.carry += Math.max(0, elapsed); |
| 294 | let steps = Math.floor(world.carry / FIXED_DT); |
| 295 | if (steps > MAX_SUBSTEPS) { |
| 296 | // Drop the backlog rather than working through it. |
| 297 | world.carry = 0; |
| 298 | steps = MAX_SUBSTEPS; |
| 299 | } else { |
| 300 | world.carry -= steps * FIXED_DT; |
| 301 | } |
| 302 | |
| 303 | const impacts: Impact[] = []; |
| 304 | for (let i = 0; i < steps; i++) step(world, impacts); |
| 305 | return impacts; |
| 306 | } |
| 307 | |
| 308 | /** One fixed step. Exported for the tests, which drive it directly. */ |
| 309 | export function step(world: World, impacts: Impact[] = []): Impact[] { |
| 310 | const dt = FIXED_DT; |
| 311 | |
| 312 | for (const b of world.bodies) { |
| 313 | if (b.scale !== 1) { |
| 314 | b.scale += (1 - b.scale) * Math.min(1, SCALE_EASE * dt); |
| 315 | if (Math.abs(b.scale - 1) < 0.002) b.scale = 1; |
| 316 | } |
| 317 | if (b.resting) continue; |
| 318 | b.age++; |
| 319 | b.awake++; |
| 320 | |
| 321 | // --- through the air --- |
| 322 | if (b.z > 0 || b.vz !== 0) { |
| 323 | b.vz -= GRAVITY * dt; |
| 324 | b.z += b.vz * dt; |
| 325 | if (b.z <= 0) { |
| 326 | const landing = Math.abs(b.vz); |
| 327 | b.z = 0; |
| 328 | // Below a knock it stops dead rather than shivering out a bounce. |
| 329 | b.vz = landing > 40 ? landing * Z_RESTITUTION : 0; |
| 330 | const strength = Math.min(1, landing / 900); |
| 331 | if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength }); |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | b.x += b.vx * dt; |
| 336 | b.y += b.vy * dt; |
| 337 | b.angle += b.spin * dt; |
| 338 | |
| 339 | if (inside(world.bounds, b.x, b.y)) b.entered = true; |
| 340 | else if (b.age > ENTRY_GRACE) { |
| 341 | // Out of time going the long way round. Put it in, gently. |
| 342 | b.entered = true; |
| 343 | b.z = 0; |
| 344 | b.vz = 0; |
| 345 | clampInto(world.bounds, b); |
| 346 | } |
| 347 | |
| 348 | // --- on the felt --- |
| 349 | // Strictly z <= 0, not ON_FELT: friction is between the tile and the cloth, |
| 350 | // so a tile still in the air keeps the speed it was thrown with. ON_FELT is |
| 351 | // only about being low enough to be in another tile's way. |
| 352 | if (b.z <= 0) { |
| 353 | damp(b, dt); |
| 354 | // A tile that fell short skids in rather than sitting outside the pool. |
| 355 | if (!b.entered) pullIn(world, b, dt); |
| 356 | } |
| 357 | |
| 358 | // A tile still above the wall is clear of it. |
| 359 | if (b.z < WALL_HEIGHT) { |
| 360 | for (const wall of world.walls) hitWall(b, wall, impacts); |
| 361 | } |
| 362 | |
| 363 | if (b.entered) keepInBounds(world, b, impacts); |
| 364 | } |
| 365 | |
| 366 | collideTiles(world, impacts); |
| 367 | // Being shoved by a neighbour can put a tile back over the edge, and a tile |
| 368 | // that then fell asleep out there would stay out there. Only awake ones need |
| 369 | // it: resolvePair never moves a tile that has settled. |
| 370 | for (const b of world.bodies) { |
| 371 | if (b.entered && !b.resting) clampInto(world.bounds, b); |
| 372 | } |
| 373 | // Deciding to sleep comes last, so it judges where the step actually left |
| 374 | // things — before, a contact resolved after the decision would undo it and a |
| 375 | // crowded pool would stay awake for ever. |
| 376 | for (const b of world.bodies) if (!b.resting) trySleep(b); |
| 377 | return impacts; |
| 378 | } |
| 379 | |
| 380 | /** |
| 381 | * The table has been re-measured — the window resized, or the wall was eaten |
| 382 | * further back. The tiles keep where they are, but a pool that shrank must not |
| 383 | * leave any of them stranded outside it, and the ones it moves have to wake up |
| 384 | * so they can settle again. |
| 385 | */ |
| 386 | export function reshape(world: World, bounds: Rect, walls: Rect[]) { |
| 387 | world.bounds = bounds; |
| 388 | world.walls = walls; |
| 389 | for (const b of world.bodies) { |
| 390 | if (!b.entered) continue; |
| 391 | const x = b.x; |
| 392 | const y = b.y; |
| 393 | clampInto(bounds, b); |
| 394 | if (b.x !== x || b.y !== y) wake(b); |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | function damp(b: Body, dt: number) { |
| 399 | const k = Math.exp(-FELT_DAMP * dt); |
| 400 | b.vx *= k; |
| 401 | b.vy *= k; |
| 402 | b.spin *= Math.exp(-SPIN_DAMP * dt); |
| 403 | |
| 404 | const speed = Math.hypot(b.vx, b.vy); |
| 405 | if (speed > 0) { |
| 406 | const next = Math.max(0, speed - FELT_STOP * dt); |
| 407 | b.vx = (b.vx / speed) * next; |
| 408 | b.vy = (b.vy / speed) * next; |
| 409 | } |
| 410 | const spin = Math.abs(b.spin); |
| 411 | if (spin > 0) b.spin = Math.sign(b.spin) * Math.max(0, spin - SPIN_STOP * dt); |
| 412 | } |
| 413 | |
| 414 | /** Nudges a tile that landed outside the pool towards the rest of them. */ |
| 415 | function pullIn(world: World, b: Body, dt: number) { |
| 416 | const cx = world.bounds.x + world.bounds.w / 2; |
| 417 | const cy = world.bounds.y + world.bounds.h / 2; |
| 418 | const dx = cx - b.x; |
| 419 | const dy = cy - b.y; |
| 420 | const d = Math.hypot(dx, dy) || 1; |
| 421 | b.vx += (dx / d) * ENTRY_PULL * dt; |
| 422 | b.vy += (dy / d) * ENTRY_PULL * dt; |
| 423 | } |
| 424 | |
| 425 | /** Bounce off a standing stack, corner to corner if that is how it hits. */ |
| 426 | function hitWall(b: Body, wall: Rect, impacts: Impact[]) { |
| 427 | const hit = overlapOf(boxOf(wall), b); |
| 428 | if (!hit || hit.depth <= CONTACT_SLOP) return; |
| 429 | |
| 430 | const speed = Math.hypot(b.vx, b.vy); |
| 431 | b.x += hit.nx * hit.depth; |
| 432 | b.y += hit.ny * hit.depth; |
| 433 | // Reflect whatever was heading into the wall; keep what was sliding along it. |
| 434 | const into = b.vx * hit.nx + b.vy * hit.ny; |
| 435 | if (into < 0) { |
| 436 | b.vx -= hit.nx * into * (1 + BOUND_RESTITUTION); |
| 437 | b.vy -= hit.ny * into * (1 + BOUND_RESTITUTION); |
| 438 | } |
| 439 | b.spin *= 0.7; |
| 440 | b.resting = false; |
| 441 | b.still = 0; |
| 442 | const strength = Math.min(1, speed / 1100); |
| 443 | if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength }); |
| 444 | } |
| 445 | |
| 446 | /** The pool's edge. Once a tile is in, it stays in — this is the invariant the |
| 447 | * tests pin, since a discard that slid off the table would be lost. */ |
| 448 | function keepInBounds(world: World, b: Body, impacts: Impact[]) { |
| 449 | const half = aabbHalf(b); |
| 450 | const { x, y, w, h } = world.bounds; |
| 451 | // A pool narrower than a tile would otherwise fight itself; centre instead. |
| 452 | const minX = w <= half.x * 2 ? x + w / 2 : x + half.x; |
| 453 | const maxX = w <= half.x * 2 ? x + w / 2 : x + w - half.x; |
| 454 | const minY = h <= half.y * 2 ? y + h / 2 : y + half.y; |
| 455 | const maxY = h <= half.y * 2 ? y + h / 2 : y + h - half.y; |
| 456 | |
| 457 | let hit = 0; |
| 458 | if (b.x < minX) { |
| 459 | b.x = minX; |
| 460 | hit = Math.max(hit, Math.abs(b.vx)); |
| 461 | b.vx = Math.abs(b.vx) * BOUND_RESTITUTION; |
| 462 | b.vy *= BOUND_FRICTION; |
| 463 | } else if (b.x > maxX) { |
| 464 | b.x = maxX; |
| 465 | hit = Math.max(hit, Math.abs(b.vx)); |
| 466 | b.vx = -Math.abs(b.vx) * BOUND_RESTITUTION; |
| 467 | b.vy *= BOUND_FRICTION; |
| 468 | } |
| 469 | if (b.y < minY) { |
| 470 | b.y = minY; |
| 471 | hit = Math.max(hit, Math.abs(b.vy)); |
| 472 | b.vy = Math.abs(b.vy) * BOUND_RESTITUTION; |
| 473 | b.vx *= BOUND_FRICTION; |
| 474 | } else if (b.y > maxY) { |
| 475 | b.y = maxY; |
| 476 | hit = Math.max(hit, Math.abs(b.vy)); |
| 477 | b.vy = -Math.abs(b.vy) * BOUND_RESTITUTION; |
| 478 | b.vx *= BOUND_FRICTION; |
| 479 | } |
| 480 | // Only a real knock counts as being disturbed. A tile held against the edge |
| 481 | // by its neighbours is clamped every single step, and treating that as a knock |
| 482 | // would keep the whole pool awake for ever. |
| 483 | if (hit > SLEEP_SPEED) { |
| 484 | b.still = 0; |
| 485 | const strength = Math.min(1, hit / 1100); |
| 486 | if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength }); |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | /** |
| 491 | * Tile against tile. |
| 492 | * |
| 493 | * Only tiles flat on the felt take part, so a thrown tile passes over the pile |
| 494 | * instead of shouldering through it, and a cheap circle test throws out the pairs |
| 495 | * that are nowhere near before the real rectangle test runs. Pairs where both |
| 496 | * tiles have settled are left alone entirely, which is nearly all of them. |
| 497 | */ |
| 498 | function collideTiles(world: World, impacts: Impact[]) { |
| 499 | const bodies = world.bodies; |
| 500 | for (let i = 0; i < bodies.length; i++) { |
| 501 | const a = bodies[i]; |
| 502 | if (a.z > ON_FELT) continue; |
| 503 | for (let j = i + 1; j < bodies.length; j++) { |
| 504 | const b = bodies[j]; |
| 505 | if (b.z > ON_FELT) continue; |
| 506 | if (a.resting && b.resting) continue; |
| 507 | if (Math.hypot(b.x - a.x, b.y - a.y) > circumradius(a) + circumradius(b)) continue; |
| 508 | resolvePair(a, b, impacts); |
| 509 | } |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | function resolvePair(a: Body, b: Body, impacts: Impact[]) { |
| 514 | const hit = overlapOf(a, b); |
| 515 | if (!hit) return; |
| 516 | // Resting in contact is not a collision. See CONTACT_SLOP. |
| 517 | const depth = hit.depth - CONTACT_SLOP; |
| 518 | if (depth <= 0) return; |
| 519 | const { nx, ny } = hit; |
| 520 | |
| 521 | // Push apart. A tile that has settled is the heavy one: a tile thrown into a |
| 522 | // pool shoulders in, rather than the pool scattering out of its way. |
| 523 | const aShare = a.resting === b.resting ? 0.5 : a.resting ? 0 : 1; |
| 524 | const bShare = 1 - aShare; |
| 525 | a.x -= nx * depth * aShare; |
| 526 | a.y -= ny * depth * aShare; |
| 527 | b.x += nx * depth * bShare; |
| 528 | b.y += ny * depth * bShare; |
| 529 | |
| 530 | // Impulse along the way out, plus a spin kick off what is left over. |
| 531 | // |
| 532 | // Only a genuine approach speed counts, and only that wakes anything. Nudging |
| 533 | // two touching tiles apart is not a collision: a jammed corner of the pool is |
| 534 | // corrected by a fraction of a pixel every step for as long as it is jammed, |
| 535 | // and treating each of those as a shove would keep the pile awake for ever. |
| 536 | const rvx = b.vx - a.vx; |
| 537 | const rvy = b.vy - a.vy; |
| 538 | const along = rvx * nx + rvy * ny; |
| 539 | if (along >= -SLEEP_SPEED) return; |
| 540 | |
| 541 | const jolt = -along * (1 + TILE_RESTITUTION) * 0.5; |
| 542 | a.vx -= nx * jolt; |
| 543 | a.vy -= ny * jolt; |
| 544 | b.vx += nx * jolt; |
| 545 | b.vy += ny * jolt; |
| 546 | |
| 547 | const tangent = rvx * -ny + rvy * nx; |
| 548 | a.spin -= tangent * SPIN_TRANSFER * 0.06; |
| 549 | b.spin += tangent * SPIN_TRANSFER * 0.06; |
| 550 | |
| 551 | const strength = Math.min(1, Math.abs(along) / 900); |
| 552 | if (strength > 0.12) impacts.push({ x: b.x, y: b.y, strength }); |
| 553 | |
| 554 | // Whatever was asleep has been shoved, so it is awake now. |
| 555 | wake(a); |
| 556 | wake(b); |
| 557 | } |
| 558 | |
| 559 | function wake(b: Body) { |
| 560 | if (b.resting) b.awake = 0; |
| 561 | b.resting = false; |
| 562 | b.still = 0; |
| 563 | } |
| 564 | |
| 565 | function sleep(b: Body) { |
| 566 | b.vx = 0; |
| 567 | b.vy = 0; |
| 568 | b.spin = 0; |
| 569 | b.z = 0; |
| 570 | b.vz = 0; |
| 571 | b.resting = true; |
| 572 | b.awake = 0; |
| 573 | } |
| 574 | |
| 575 | function trySleep(b: Body) { |
| 576 | const speed = Math.hypot(b.vx, b.vy); |
| 577 | const slow = |
| 578 | b.entered && b.z <= 0 && b.vz === 0 && speed < SLEEP_SPEED && Math.abs(b.spin) < SLEEP_SPIN; |
| 579 | if (slow && ++b.still >= SLEEP_STEPS) return sleep(b); |
| 580 | if (!slow) b.still = 0; |
| 581 | // Backstop: shuffling about in a crowded pool for this long is settled enough. |
| 582 | if (b.entered && b.awake > AWAKE_LIMIT && speed < SLEEP_SPEED * 4) sleep(b); |
| 583 | } |
| 584 | |
| 585 | /** |
| 586 | * Make room for a tile placed straight into a settled pile, without running |
| 587 | * time. Used when a pile is rebuilt — a reload, an undo — where the tiles have |
| 588 | * to be somewhere sensible immediately and nothing should appear to move. |
| 589 | */ |
| 590 | function separate(world: World, body: Body, passes = 16) { |
| 591 | // Which way to go when two tiles are exactly on top of each other. Stepping |
| 592 | // by the golden angle fans successive tiles out in every direction, where a |
| 593 | // fixed axis would march them all one way and pack them against a pool edge. |
| 594 | const escape = world.bodies.indexOf(body) * 2.39996; |
| 595 | |
| 596 | for (let p = 0; p < passes; p++) { |
| 597 | let moved = false; |
| 598 | for (const other of world.bodies) { |
| 599 | if (other === body) continue; |
| 600 | const hit = overlapOf(other, body); |
| 601 | if (!hit || hit.depth <= CONTACT_SLOP) continue; |
| 602 | if (Math.hypot(body.x - other.x, body.y - other.y) < 0.0001) { |
| 603 | body.x += Math.cos(escape + p) * hit.depth; |
| 604 | body.y += Math.sin(escape + p) * hit.depth; |
| 605 | } else { |
| 606 | body.x += hit.nx * hit.depth; |
| 607 | body.y += hit.ny * hit.depth; |
| 608 | } |
| 609 | moved = true; |
| 610 | } |
| 611 | clampInto(world.bounds, body); |
| 612 | if (!moved) break; |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | function clampInto(r: Rect, b: Body) { |
| 617 | const half = aabbHalf(b); |
| 618 | const minX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + half.x; |
| 619 | const maxX = r.w <= half.x * 2 ? r.x + r.w / 2 : r.x + r.w - half.x; |
| 620 | const minY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + half.y; |
| 621 | const maxY = r.h <= half.y * 2 ? r.y + r.h / 2 : r.y + r.h - half.y; |
| 622 | b.x = Math.min(maxX, Math.max(minX, b.x)); |
| 623 | b.y = Math.min(maxY, Math.max(minY, b.y)); |
| 624 | } |
| 625 | |
| 626 | /** Whether everything has settled — what the render loop idles on. */ |
| 627 | export const settled = (world: World) => |
| 628 | world.bodies.every((b) => b.resting && b.scale === 1); |
| 629 | |
| 630 | /** How far outside the pool a tile is sitting. The tests' invariant. */ |
| 631 | export function outside(b: Body, pool: Rect): number { |
| 632 | const half = aabbHalf(b); |
| 633 | return Math.max( |
| 634 | 0, |
| 635 | pool.x + half.x - b.x, |
| 636 | b.x - (pool.x + pool.w - half.x), |
| 637 | pool.y + half.y - b.y, |
| 638 | b.y - (pool.y + pool.h - half.y), |
| 639 | ); |
| 640 | } |
| 641 | |
| 642 | /** Whether two tiles are sharing ground, which they must never do at rest. */ |
| 643 | export function overlapping(a: Body, b: Body): number { |
| 644 | const hit = overlapOf(a, b); |
| 645 | return hit ? hit.depth : 0; |
| 646 | } |
| 647 | |
| 648 | /** Scale a tile is drawn at, given how high it is. Sells the arc on a flat |
| 649 | * canvas; the renderer offsets the shadow by the same height. */ |
| 650 | export const zScale = (z: number) => 1 + z * 0.0016; |
| 651 | |
| 652 | /** |
| 653 | * The upward kick that puts a tile back on the felt after `seconds` in the air. |
| 654 | * How a throw is aimed: pick how long it should take, and the horizontal speed |
| 655 | * follows from the distance. |
| 656 | */ |
| 657 | export const liftFor = (seconds: number) => (GRAVITY * seconds) / 2; |
| 658 | |
| 659 | /** How high that kick gets — worth checking against WALL_HEIGHT. */ |
| 660 | export const peakOf = (vz: number) => (vz * vz) / (2 * GRAVITY); |