← back to the page

workers/public/thirstday/pool/src/sim.rs

the pool table: integer physics, the same bits everywhere · 879 lines · compiled into this Worker from the repository as it is

1//! One shot, from a table at rest to the next table at rest: real pool
2//! physics, worked out the same way everywhere.
3//!
4//! Each ball has a velocity and a spin. The spin is kept as the speed the
5//! ball would roll at with it (`s`, m/s: the ball's angular velocity about
6//! the table's axes times R), so a ball rolls when `v == s` and slides
7//! otherwise. A shot hits the cue ball in the middle: it starts sliding
8//! with no spin.
9//!
10//! - Sliding: the cloth's friction ([`MU_SLIDE`]) acts against the slip
11//! `v - s`, slowing the ball and turning it over, until it rolls (after
12//! losing 2/7 of its speed, as a real ball does); a ball with spin left
13//! after a collision (stun, follow, draw) curves and speeds up or pulls
14//! back the same way.
15//! - Rolling: rolling resistance ([`MU_ROLL`]) slows it steadily.
16//! - Ball on ball: equal masses, an impulse along the line of centres with
17//! restitution [`E_BALL`]; spins pass through (a rolling cue ball hitting
18//! full stops, then its topspin pulls it on: natural follow).
19//! - Cushions (rails and the pockets' jaws): the speed into the cushion
20//! comes back times [`cushion_e`] (0.85 slow, less hard), the speed along
21//! it is kept, so the angle out is the mirror of the angle in, a little
22//! flatter; the spin into the cushion mostly dies there.
23//! - Pockets: a ball whose centre's path comes within a pocket's reach
24//! drops; the jaws in front of them are cushions, so a ball can rattle.
25//!
26//! Collisions are exact (continuous): within each step of 1/[`HZ`] s, the
27//! earliest contact of any pair or any ball and cushion is found (its time
28//! of impact, solving the motion's quadratic), everything moves to it, the
29//! contact is resolved, and the search goes on for the rest of the step.
30//! Nothing tunnels, however hard the shot, and a cut's angle comes out
31//! exactly as aimed, never off by where a step happened to land.
32//!
33//! Only `+ - * /` and `sqrt` (all exact IEEE operations) and [`trig`]'s
34//! own sine and cosine, in a fixed order (balls by number, pairs by number,
35//! cushions as listed; ties go to the first found), so the same table and
36//! shot give the same bits in the Room and in every browser.
37
38use crate::table::{m, um, Table, BALLS, CUSHIONS, POCKETS, R};
39use crate::trig;
40use serde::{Deserialize, Serialize};
41
42pub const HZ: u32 = 960;
43const DT: f64 = 1.0 / HZ as f64;
44/// The cue ball's speed at full power (m/s): a hard break.
45pub const VMAX: f64 = 8.0;
46/// Power in a shot: millionths of full.
47pub const FULL: u32 = 1_000_000;
48const G: f64 = 9.81;
49/// Ball on cloth: sliding friction, and rolling resistance.
50pub const MU_SLIDE: f64 = 0.2;
51pub const MU_ROLL: f64 = 0.012;
52/// Slower than this (and spinning slower), a ball stops (m/s).
53pub const STOP: f64 = 0.004;
54pub const E_BALL: f64 = 0.95;
55/// What's left of the spin into a cushion, turned back (the cushion's nose
56/// sits above the ball's middle and grips it).
57const CUSHION_SPIN: f64 = -0.4;
58/// A shot never runs longer than this (s); every ball has stopped long
59/// before (the tests check), but the loop must end.
60const MAX_SECS: u32 = 60;
61/// Contacts resolved in one step at most (a break's first step has a few
62/// dozen); past it the step just finishes moving.
63const MAX_HITS: u32 = 400;
64/// Frames for drawing: one every this many steps (120 a second).
65pub const FRAME_STEPS: u32 = 8;
66pub const FPS: f64 = HZ as f64 / FRAME_STEPS as f64;
67
68/// A cushion's restitution for a ball coming in at `vn` m/s: livelier
69/// slow, deader hard.
70pub fn cushion_e(vn: f64) -> f64 {
71 let e = 0.85 - 0.02 * vn;
72 if e < 0.7 { 0.7 } else { e }
73}
74
75/// A shot: which way (2⁻³² turns, 0 along +x, counter-clockwise towards
76/// +y: any `u32`) and how hard (millionths of full power, 1–[`FULL`]).
77/// On the wire `ang` and `pow` (older pages' `angle`/`power` were coarser
78/// units and are refused, never misread).
79#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
80pub struct Shot {
81 #[serde(rename = "ang")]
82 pub angle: u32,
83 #[serde(rename = "pow")]
84 pub power: u32,
85}
86
87impl Shot {
88 pub fn valid(&self) -> bool {
89 (1..=FULL).contains(&self.power)
90 }
91 /// The cue ball's speed: power squared, so a soft touch has as much
92 /// room on the slider as a break.
93 pub fn speed(&self) -> f64 {
94 let f = self.power as f64 / FULL as f64;
95 VMAX * f * f
96 }
97}
98
99/// Something heard during a shot, at a step: the cue striking, two balls
100/// clacking or a ball hitting a cushion (with how hard, m/s), a ball
101/// dropping.
102#[derive(Clone, Copy, Debug, PartialEq)]
103pub enum Event {
104 Cue { step: u32, speed: f64 },
105 Clack { step: u32, speed: f64 },
106 Rail { step: u32, speed: f64 },
107 Drop { step: u32, ball: u8 },
108}
109
110/// Every ball's place in one drawn frame (m, as f32), and which are on.
111#[derive(Clone, Copy, Debug, PartialEq)]
112pub struct Frame {
113 pub pos: [[f32; 2]; BALLS],
114 pub on: u16,
115}
116
117/// A shot played out.
118#[derive(Clone, Debug, PartialEq)]
119pub struct Sim {
120 /// The table at rest afterwards.
121 pub end: Table,
122 /// The first ball the cue ball touched.
123 pub first: Option<u8>,
124 /// Balls dropped, in order.
125 pub dropped: Vec<u8>,
126 /// Some ball touched a cushion after the cue ball's first contact.
127 pub rail_after: bool,
128 /// Steps until everything stopped.
129 pub steps: u32,
130 /// Only when asked for (drawing, sounds): frames every
131 /// [`FRAME_STEPS`] steps (the last one at rest) and events.
132 pub frames: Vec<Frame>,
133 pub events: Vec<Event>,
134}
135
136struct Ball {
137 p: [f64; 2],
138 v: [f64; 2],
139 /// Spin, as the speed it would roll at (m/s).
140 s: [f64; 2],
141 on: bool,
142}
143
144impl Ball {
145 fn still(&self) -> bool {
146 self.v[0] == 0.0 && self.v[1] == 0.0 && self.s[0] == 0.0 && self.s[1] == 0.0
147 }
148}
149
150fn dot(a: [f64; 2], b: [f64; 2]) -> f64 {
151 a[0] * b[0] + a[1] * b[1]
152}
153
154/// Plays `shot` on `t` (its cue ball where it is). `record`: keep frames
155/// and events.
156pub fn simulate(t: &Table, shot: Shot, record: bool) -> Sim {
157 let mut r = Run::new(t, shot, record);
158 while r.step < MAX_SECS * HZ && r.moving() {
159 r.advance();
160 }
161 r.finish()
162}
163
164/// What comes next within a step.
165#[derive(Clone, Copy)]
166enum Hit {
167 /// Balls `i < j`.
168 Pair(usize, usize),
169 /// Ball `i` against a cushion, pushed off along `n` (unit, from the
170 /// cushion towards the ball, at the touch).
171 Cushion(usize, [f64; 2]),
172}
173
174/// When (s from now) two balls `d` apart closing at `w` (relative
175/// velocity) touch, if they're closing at all; 0 if already touching.
176fn toi_pair(d: [f64; 2], w: [f64; 2], reach: f64) -> Option<f64> {
177 let b = dot(d, w);
178 if b >= 0.0 {
179 return None;
180 }
181 let c = dot(d, d) - reach * reach;
182 if c <= 0.0 {
183 return Some(0.0);
184 }
185 let a = dot(w, w);
186 let disc = b * b - a * c;
187 if disc < 0.0 {
188 return None;
189 }
190 // The smaller root, in the form that keeps its digits.
191 Some(c / (-b + disc.sqrt()))
192}
193
194/// The first touch of a ball at `p` moving at `v` with cushion `k` (a
195/// segment swept by R: its two sides and its two ends), within `left` s.
196fn toi_cushion(k: usize, p: [f64; 2], v: [f64; 2], left: f64) -> Option<(f64, [f64; 2])> {
197 let sg = &CUSHIONS[k];
198 let ab = [sg.b[0] - sg.a[0], sg.b[1] - sg.a[1]];
199 let len = dot(ab, ab).sqrt();
200 let u = [ab[0] / len, ab[1] / len];
201 let n = [-u[1], u[0]];
202 let ap = [p[0] - sg.a[0], p[1] - sg.a[1]];
203 let side = dot(ap, n);
204 let mut best: Option<(f64, [f64; 2])> = None;
205 if side != 0.0 {
206 let sign = if side > 0.0 { 1.0 } else { -1.0 };
207 let nn = [n[0] * sign, n[1] * sign];
208 let vn = dot(v, nn);
209 if vn < 0.0 {
210 let gap = side * sign - R;
211 let t = if gap <= 0.0 { 0.0 } else { gap / -vn };
212 if t <= left {
213 let along = dot([ap[0] + v[0] * t, ap[1] + v[1] * t], u);
214 if (0.0..=len).contains(&along) {
215 best = Some((t, nn));
216 }
217 }
218 }
219 }
220 for e in [sg.a, sg.b] {
221 let d = [p[0] - e[0], p[1] - e[1]];
222 if let Some(t) = toi_pair([-d[0], -d[1]], [-v[0], -v[1]], R) {
223 if t <= left && best.is_none_or(|(b, _)| t < b) {
224 let at = [d[0] + v[0] * t, d[1] + v[1] * t];
225 let l = dot(at, at).sqrt();
226 if l > 0.0 {
227 best = Some((t, [at[0] / l, at[1] / l]));
228 }
229 }
230 }
231 }
232 best
233}
234
235/// A shot being played, step by step.
236struct Run {
237 b: Vec<Ball>,
238 step: u32,
239 out: Sim,
240 record: bool,
241}
242
243impl Run {
244 fn new(t: &Table, shot: Shot, record: bool) -> Run {
245 let mut b: Vec<Ball> = (0..BALLS).map(|k| Ball { p: [m(t.pos[k][0]), m(t.pos[k][1])], v: [0.0, 0.0], s: [0.0, 0.0], on: t.is_on(k) }).collect();
246 let (c, s) = trig::dir(shot.angle);
247 let speed = shot.speed();
248 b[0].v = [c * speed, s * speed];
249 let mut out = Sim { end: *t, first: None, dropped: Vec::new(), rail_after: false, steps: 0, frames: Vec::new(), events: Vec::new() };
250 if record {
251 out.events.push(Event::Cue { step: 0, speed });
252 out.frames.push(frame(&b));
253 }
254 Run { b, step: 0, out, record }
255 }
256
257 fn moving(&self) -> bool {
258 self.b.iter().any(|x| x.on && !x.still())
259 }
260
261 /// The earliest contact within `left` s, if any.
262 fn next_hit(&self, left: f64) -> Option<(f64, Hit)> {
263 let b = &self.b;
264 let mut best: Option<(f64, Hit)> = None;
265 for (i, x) in b.iter().enumerate() {
266 if !x.on || (x.v[0] == 0.0 && x.v[1] == 0.0) {
267 continue;
268 }
269 for k in 0..CUSHIONS.len() {
270 if let Some((t, n)) = toi_cushion(k, x.p, x.v, left) {
271 if best.is_none_or(|(bt, _)| t < bt) {
272 best = Some((t, Hit::Cushion(i, n)));
273 }
274 }
275 }
276 }
277 for i in 0..BALLS {
278 if !b[i].on {
279 continue;
280 }
281 for j in i + 1..BALLS {
282 if !b[j].on {
283 continue;
284 }
285 let w = [b[j].v[0] - b[i].v[0], b[j].v[1] - b[i].v[1]];
286 if w[0] == 0.0 && w[1] == 0.0 {
287 continue;
288 }
289 let d = [b[j].p[0] - b[i].p[0], b[j].p[1] - b[i].p[1]];
290 if let Some(t) = toi_pair(d, w, 2.0 * R) {
291 if t <= left && best.is_none_or(|(bt, _)| t < bt) {
292 best = Some((t, Hit::Pair(i, j)));
293 }
294 }
295 }
296 }
297 best
298 }
299
300 /// Every ball on moves straight for `t` s; one whose centre passes
301 /// within a pocket's reach on the way drops there.
302 fn travel(&mut self, t: f64) {
303 let (b, out, step, record) = (&mut self.b, &mut self.out, self.step, self.record);
304 for (k, x) in b.iter_mut().enumerate() {
305 if !x.on || (x.v[0] == 0.0 && x.v[1] == 0.0) || t <= 0.0 {
306 continue;
307 }
308 let d = [x.v[0] * t, x.v[1] * t];
309 let to = [x.p[0] + d[0], x.p[1] + d[1]];
310 let dd = dot(d, d);
311 for p in &POCKETS {
312 // The point of the way nearest the pocket's centre.
313 let f = if dd > 0.0 { (dot([p.x - x.p[0], p.y - x.p[1]], d) / dd).clamp(0.0, 1.0) } else { 0.0 };
314 let q = [x.p[0] + d[0] * f, x.p[1] + d[1] * f];
315 let (dx, dy) = (q[0] - p.x, q[1] - p.y);
316 if dx * dx + dy * dy < p.r * p.r {
317 x.on = false;
318 x.p = q;
319 x.v = [0.0, 0.0];
320 x.s = [0.0, 0.0];
321 out.dropped.push(k as u8);
322 if record {
323 out.events.push(Event::Drop { step, ball: k as u8 });
324 }
325 break;
326 }
327 }
328 if x.on {
329 x.p = to;
330 }
331 }
332 }
333
334 fn resolve(&mut self, hit: Hit) {
335 let (b, out, step, record) = (&mut self.b, &mut self.out, self.step, self.record);
336 match hit {
337 Hit::Pair(i, j) => {
338 if !b[i].on || !b[j].on {
339 return;
340 }
341 let d = [b[j].p[0] - b[i].p[0], b[j].p[1] - b[i].p[1]];
342 let len = dot(d, d).sqrt();
343 if len == 0.0 {
344 return;
345 }
346 let n = [d[0] / len, d[1] / len];
347 let rel = dot([b[j].v[0] - b[i].v[0], b[j].v[1] - b[i].v[1]], n);
348 if rel >= 0.0 {
349 return;
350 }
351 let k = (1.0 + E_BALL) / 2.0 * rel;
352 b[i].v = [b[i].v[0] + n[0] * k, b[i].v[1] + n[1] * k];
353 b[j].v = [b[j].v[0] - n[0] * k, b[j].v[1] - n[1] * k];
354 if i == 0 && out.first.is_none() {
355 out.first = Some(j as u8);
356 }
357 if record {
358 out.events.push(Event::Clack { step, speed: -rel });
359 }
360 }
361 Hit::Cushion(i, n) => {
362 let x = &mut b[i];
363 if !x.on {
364 return;
365 }
366 let vn = dot(x.v, n);
367 if vn >= 0.0 {
368 return;
369 }
370 let e = cushion_e(-vn);
371 x.v = [x.v[0] - n[0] * vn * (1.0 + e), x.v[1] - n[1] * vn * (1.0 + e)];
372 let sn = dot(x.s, n);
373 x.s = [x.s[0] + n[0] * sn * (CUSHION_SPIN - 1.0), x.s[1] + n[1] * sn * (CUSHION_SPIN - 1.0)];
374 if out.first.is_some() {
375 out.rail_after = true;
376 }
377 if record {
378 out.events.push(Event::Rail { step, speed: -vn });
379 }
380 }
381 }
382 }
383
384 /// The cloth's friction over one step.
385 fn friction(&mut self) {
386 let slide = MU_SLIDE * G * DT;
387 let roll = MU_ROLL * G * DT;
388 for x in self.b.iter_mut().filter(|x| x.on) {
389 let u = [x.v[0] - x.s[0], x.v[1] - x.s[1]];
390 let ul = dot(u, u).sqrt();
391 if ul > 0.0 {
392 // Sliding: the slip shrinks at 7/2 μg.
393 if ul <= 3.5 * slide {
394 // It rolls within the step: at the speed the contact
395 // point's angular momentum gives.
396 let r = [(5.0 * x.v[0] + 2.0 * x.s[0]) / 7.0, (5.0 * x.v[1] + 2.0 * x.s[1]) / 7.0];
397 x.v = r;
398 x.s = r;
399 } else {
400 let h = [u[0] / ul, u[1] / ul];
401 x.v = [x.v[0] - h[0] * slide, x.v[1] - h[1] * slide];
402 x.s = [x.s[0] + h[0] * 2.5 * slide, x.s[1] + h[1] * 2.5 * slide];
403 }
404 } else {
405 let sp = dot(x.v, x.v).sqrt();
406 if sp <= roll {
407 x.v = [0.0, 0.0];
408 } else {
409 let f = (sp - roll) / sp;
410 x.v = [x.v[0] * f, x.v[1] * f];
411 }
412 x.s = x.v;
413 }
414 if dot(x.v, x.v) < STOP * STOP && dot(x.s, x.s) < STOP * STOP {
415 x.v = [0.0, 0.0];
416 x.s = [0.0, 0.0];
417 }
418 }
419 }
420
421 fn advance(&mut self) {
422 self.step += 1;
423 let mut left = DT;
424 let mut hits = 0;
425 while left > 0.0 {
426 let next = if hits < MAX_HITS { self.next_hit(left) } else { None };
427 let Some((t, hit)) = next else {
428 self.travel(left);
429 break;
430 };
431 self.travel(t);
432 left -= t;
433 self.resolve(hit);
434 hits += 1;
435 }
436 self.friction();
437 if self.record && self.step % FRAME_STEPS == 0 {
438 self.out.frames.push(frame(&self.b));
439 }
440 }
441
442 fn finish(mut self) -> Sim {
443 let mut end = self.out.end;
444 end.on = 0;
445 for (k, x) in self.b.iter().enumerate() {
446 end.pos[k] = [um(x.p[0]), um(x.p[1])];
447 if x.on {
448 end.on |= 1 << k;
449 }
450 }
451 self.out.end = end;
452 self.out.steps = self.step;
453 if self.record {
454 self.out.frames.push(frame(&self.b));
455 }
456 self.out
457 }
458}
459
460fn frame(b: &[Ball]) -> Frame {
461 let mut f = Frame { pos: [[0.0; 2]; BALLS], on: 0 };
462 for (k, x) in b.iter().enumerate() {
463 f.pos[k] = [x.p[0] as f32, x.p[1] as f32];
464 if x.on {
465 f.on |= 1 << k;
466 }
467 }
468 f
469}
470
471/// Where a shot first meets something, for the aim line: the cue ball's
472/// centre where it touches a ball (and that ball) or a cushion (and the
473/// way it comes off). Metres. Straight lines only, no drag.
474pub struct Aim {
475 pub hit: [f64; 2],
476 pub ball: Option<u8>,
477 /// After the touch: the object ball's way (a ball) or the cue ball's
478 /// (a cushion), as a unit vector.
479 pub then: [f64; 2],
480}
481
482pub fn aim(t: &Table, cue: [f64; 2], angle: u32) -> Aim {
483 let (c, s) = trig::dir(angle);
484 aim_dir(t, cue, [c, s])
485}
486
487/// [`aim`] along a unit vector `d` (any direction: the aim line follows
488/// the pointer exactly).
489/// Exact: the cue ball's centre against each ball (2R) and each cushion
490/// swept by R (two offset lines and the two ends).
491pub fn aim_dir(t: &Table, cue: [f64; 2], d: [f64; 2]) -> Aim {
492 let mut best = (f64::INFINITY, None::<u8>, [0.0, 0.0]);
493 for k in 1..BALLS {
494 if !t.is_on(k) {
495 continue;
496 }
497 let p = [m(t.pos[k][0]) - cue[0], m(t.pos[k][1]) - cue[1]];
498 let along = dot(p, d);
499 if along <= 0.0 {
500 continue;
501 }
502 let off2 = dot(p, p) - along * along;
503 let reach = 4.0 * R * R - off2;
504 if reach < 0.0 {
505 continue;
506 }
507 let at = along - reach.sqrt();
508 if at < best.0 {
509 let hit = [cue[0] + d[0] * at, cue[1] + d[1] * at];
510 let n = [m(t.pos[k][0]) - hit[0], m(t.pos[k][1]) - hit[1]];
511 let l = dot(n, n).sqrt().max(1e-9);
512 best = (at, Some(k as u8), [n[0] / l, n[1] / l]);
513 }
514 }
515 // Cushions: the first place the centre comes within R of one, moving in.
516 let mut wall: Option<(f64, [f64; 2])> = None;
517 let mut take = |at: f64, n: [f64; 2]| {
518 if at > 1e-9 && dot(d, n) < 0.0 && wall.is_none_or(|(w, _)| at < w) {
519 wall = Some((at, n));
520 }
521 };
522 for sg in &CUSHIONS {
523 let ab = [sg.b[0] - sg.a[0], sg.b[1] - sg.a[1]];
524 let len = dot(ab, ab).sqrt();
525 let u = [ab[0] / len, ab[1] / len];
526 let n = [-u[1], u[0]];
527 let ca = [cue[0] - sg.a[0], cue[1] - sg.a[1]];
528 let side = dot(ca, n);
529 let dn = dot(d, n);
530 if side.abs() >= R && dn != 0.0 {
531 let sign = side.signum();
532 let at = (sign * R - side) / dn;
533 let along = dot([ca[0] + d[0] * at, ca[1] + d[1] * at], u);
534 if (0.0..=len).contains(&along) {
535 take(at, [n[0] * sign, n[1] * sign]);
536 }
537 }
538 for e in [sg.a, sg.b] {
539 let ce = [cue[0] - e[0], cue[1] - e[1]];
540 let b = dot(ce, d);
541 let cc = dot(ce, ce) - R * R;
542 let disc = b * b - cc;
543 if cc > 0.0 && disc >= 0.0 {
544 let at = -b - disc.sqrt();
545 let hit = [ce[0] + d[0] * at, ce[1] + d[1] * at];
546 take(at, [hit[0] / R, hit[1] / R]);
547 }
548 }
549 }
550 if let Some((at, n)) = wall.filter(|(w, _)| *w < best.0) {
551 let vn = dot(d, n);
552 return Aim { hit: [cue[0] + d[0] * at, cue[1] + d[1] * at], ball: None, then: [d[0] - 2.0 * vn * n[0], d[1] - 2.0 * vn * n[1]] };
553 }
554 let at = if best.0.is_finite() { best.0 } else { 0.0 };
555 Aim { hit: [cue[0] + d[0] * at, cue[1] + d[1] * at], ball: best.1, then: best.2 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561 use crate::table::{FOOT_X, HEAD_X, LEN, WID};
562
563 const ORDER: [u8; 15] = [1, 9, 2, 10, 8, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
564
565 fn only(balls: &[(usize, f64, f64)]) -> Table {
566 let mut t = Table { pos: [[0, 0]; BALLS], on: 0 };
567 for &(k, x, y) in balls {
568 t.pos[k] = [um(x), um(y)];
569 t.on |= 1 << k;
570 }
571 t
572 }
573
574 /// Degrees (counter-clockwise from +x) as a shot's angle.
575 fn deg(d: f64) -> u32 {
576 ((d.rem_euclid(360.0) / 360.0 * trig::TURN as f64).round() as u64 % trig::TURN) as u32
577 }
578
579 /// The power for a cue ball speed (m/s).
580 fn at(speed: f64) -> u32 {
581 ((speed / VMAX).sqrt() * FULL as f64).round() as u32
582 }
583
584 /// Kinetic energy over half a ball's mass: moving and spinning (a
585 /// solid ball's I = 2/5 mR², so spinning adds 2/5 s²).
586 fn energy(b: &[Ball]) -> f64 {
587 b.iter().filter(|x| x.on).map(|x| dot(x.v, x.v) + 0.4 * dot(x.s, x.s)).sum()
588 }
589
590 fn rolled(s: &Sim, k: usize) -> f64 {
591 let first = s.frames[0].pos[k];
592 let last = s.frames[s.frames.len() - 1].pos[k];
593 ((last[0] - first[0]) as f64).hypot((last[1] - first[1]) as f64)
594 }
595
596 #[test]
597 fn same_shot_same_bits() {
598 let t = Table::racked(&ORDER);
599 let shot = Shot { angle: deg(0.37), power: FULL };
600 let a = simulate(&t, shot, true);
601 let b = simulate(&t, shot, false);
602 assert_eq!(a.end, b.end);
603 assert_eq!((a.first, &a.dropped, a.rail_after, a.steps), (b.first, &b.dropped, b.rail_after, b.steps));
604 assert_eq!(a, simulate(&t, shot, true));
605 // A hair's difference shows: the result really depends on the shot.
606 let c = simulate(&t, Shot { angle: shot.angle + 5000, power: FULL }, false);
607 assert_ne!(a.end, c.end);
608 }
609
610 /// Kinetic energy (moving and spinning, all masses equal) after every
611 /// step of several shots, the break among them: it never goes up.
612 #[test]
613 fn energy_never_increases() {
614 for (angle, power) in [(deg(0.0), FULL), (deg(1.3), FULL), (deg(33.0), 700_000), (deg(180.0), 400_000), (deg(271.0), FULL)] {
615 let mut r = Run::new(&Table::racked(&ORDER), Shot { angle, power }, false);
616 let mut prev = energy(&r.b);
617 while r.moving() {
618 r.advance();
619 let e = energy(&r.b);
620 assert!(e <= prev * (1.0 + 1e-12), "energy rose at step {}: {prev} -> {e}", r.step);
621 prev = e;
622 }
623 }
624 }
625
626 #[test]
627 fn everything_stops_well_within_the_cap() {
628 let t = Table::racked(&ORDER);
629 for k in 0..12u32 {
630 let a = k * (u32::MAX / 12);
631 let s = simulate(&t, Shot { angle: a, power: FULL }, false);
632 assert!(s.steps < 40 * HZ, "angle {a}: {} s", s.steps / HZ);
633 }
634 }
635
636 /// On the cloth, or in a pocket's mouth.
637 fn inside(x: f64, y: f64) -> bool {
638 let tol = 1e-6;
639 let cloth = x >= R - tol && x <= LEN - R + tol && y >= R - tol && y <= WID - R + tol;
640 cloth || POCKETS.iter().any(|p| (x - p.x).powi(2) + (y - p.y).powi(2) < 0.13 * 0.13)
641 }
642
643 #[test]
644 fn no_tunnelling_at_full_power() {
645 // Straight at a lone ball and every way at the cushions, at full
646 // power: the ball is hit, and nothing ever leaves the table except
647 // into a pocket.
648 let t = only(&[(0, 0.5, 0.6), (1, 1.3, 0.6)]);
649 let s = simulate(&t, Shot { angle: 0, power: FULL }, true);
650 assert_eq!(s.first, Some(1));
651 for k in 0..541u32 {
652 let a = k.wrapping_mul(7_939_067);
653 for from in [(1.0, 0.5), (0.2, 0.2), (2.3, 1.1), (LEN / 2.0, 0.1)] {
654 let t = only(&[(0, from.0, from.1), (7, 1.6, 0.7)]);
655 let s = simulate(&t, Shot { angle: a, power: FULL }, true);
656 for f in &s.frames {
657 for k in [0, 7] {
658 if f.on & (1 << k) != 0 {
659 let [x, y] = f.pos[k];
660 assert!(inside(x as f64, y as f64), "angle {a}: ball {k} out at {x},{y}");
661 }
662 }
663 }
664 for k in [0, 7] {
665 if s.end.is_on(k) {
666 assert!(inside(m(s.end.pos[k][0]), m(s.end.pos[k][1])));
667 }
668 }
669 }
670 }
671 }
672
673 /// A ball a hair thinner than the cue ball's whole step at full power
674 /// is still hit: contacts are found between steps, not at them.
675 #[test]
676 fn a_thin_graze_at_full_speed_is_felt() {
677 // Off the line by just under 2R: a graze.
678 let off = 2.0 * R - 1e-4;
679 let t = only(&[(0, 0.3, 0.6), (4, 2.0, 0.6 + off)]);
680 let s = simulate(&t, Shot { angle: 0, power: FULL }, false);
681 assert_eq!(s.first, Some(4));
682 let t = only(&[(0, 0.3, 0.6), (4, 2.0, 0.6 + 2.0 * R + 1e-4)]);
683 assert_eq!(simulate(&t, Shot { angle: 0, power: FULL }, false).first, None, "a miss by 0.1 mm");
684 }
685
686 #[test]
687 fn balls_never_overlap() {
688 let t = Table::racked(&ORDER);
689 for shot in [Shot { angle: deg(0.2), power: FULL }, Shot { angle: deg(-2.0), power: 600_000 }] {
690 let mut r = Run::new(&t, shot, false);
691 while r.moving() {
692 r.advance();
693 for a in 0..BALLS {
694 for b in a + 1..BALLS {
695 if r.b[a].on && r.b[b].on {
696 let d = (r.b[a].p[0] - r.b[b].p[0]).hypot(r.b[a].p[1] - r.b[b].p[1]);
697 assert!(d > 2.0 * R - 1e-9, "{a} {b} at step {}: {}", r.step, 2.0 * R - d);
698 }
699 }
700 }
701 }
702 }
703 }
704
705 #[test]
706 fn straight_into_each_pocket() {
707 // From the middle of the table, aimed at each pocket.
708 let from = (LEN / 2.0, WID / 2.0);
709 for p in &POCKETS {
710 let a = (p.y - from.1).atan2(p.x - from.0).to_degrees();
711 let t = only(&[(0, from.0, from.1)]);
712 let s = simulate(&t, Shot { angle: deg(a), power: at(2.5) }, false);
713 assert_eq!(s.dropped, vec![0], "pocket at {},{}", p.x, p.y);
714 }
715 }
716
717 #[test]
718 fn a_cut_into_the_corner() {
719 // Object ball near the corner; the cue ball sends it straight in.
720 let (ox, oy) = (0.3_f64, 0.3_f64);
721 let (px, py) = (-0.01_f64, -0.01_f64);
722 let l = ((ox - px) * (ox - px) + (oy - py) * (oy - py)).sqrt();
723 let (ux, uy) = ((ox - px) / l, (oy - py) / l);
724 let (cx, cy) = (ox + ux * 0.4, oy + uy * 0.4);
725 let t = only(&[(0, cx, cy), (3, ox, oy)]);
726 let s = simulate(&t, Shot { angle: deg(225.0), power: at(2.0) }, false);
727 assert_eq!(s.first, Some(3));
728 assert!(s.dropped.contains(&3));
729 }
730
731 /// A cut goes where the ghost ball says, to well under a tenth of a
732 /// degree, at any power and wherever the steps fall.
733 #[test]
734 fn cuts_go_where_the_aim_line_says() {
735 let t = only(&[(0, 0.5, 0.6), (6, 1.3, 0.65)]);
736 for (d, speed) in [(1.0, 1.0), (2.5, 3.0), (3.4, 6.0), (0.3, 8.0)] {
737 let angle = deg(d);
738 let (c, s) = trig::dir(angle);
739 let want = aim_dir(&t, [0.5, 0.6], [c, s]);
740 assert_eq!(want.ball, Some(6));
741 let mut r = Run::new(&t, Shot { angle, power: at(speed) }, false);
742 while r.out.first.is_none() {
743 r.advance();
744 }
745 let v = r.b[6].v;
746 let got = dot(v, want.then) / dot(v, v).sqrt();
747 assert!(got > (0.05_f64).to_radians().cos(), "{d}°: off by {}°", got.acos().to_degrees());
748 }
749 }
750
751 #[test]
752 fn cushions_bounce_with_restitution() {
753 // Sliding straight into the top rail: back at the cushion's e.
754 let mut r = Run::new(&only(&[(0, 1.0, WID - R - 0.001)]), Shot { angle: deg(90.0), power: at(1.0) }, true);
755 while r.out.events.iter().all(|e| !matches!(e, Event::Rail { .. })) {
756 r.advance();
757 }
758 let Event::Rail { speed, .. } = r.out.events[1] else { panic!() };
759 assert!((r.b[0].v[1] / speed + cushion_e(speed)).abs() < 0.005);
760 // In at an angle: out at the mirrored angle, a little flatter.
761 let mut r = Run::new(&only(&[(0, 1.0, WID - R - 0.001)]), Shot { angle: deg(45.0), power: at(1.0) }, true);
762 while r.out.events.len() < 2 {
763 r.advance();
764 }
765 let out = (-r.b[0].v[1]).atan2(r.b[0].v[0]).to_degrees();
766 assert!(out < 45.0 && out > 35.0, "{out}°");
767 // A rolling ball goes up the table and back, and stays on it.
768 let s = simulate(&only(&[(0, 1.0, 0.6)]), Shot { angle: deg(90.0), power: at(1.0) }, true);
769 let top = s.frames.iter().map(|f| f.pos[0][1]).fold(0.0_f32, f32::max);
770 assert!(top as f64 <= WID - R + 1e-6);
771 assert!((m(s.end.pos[0][1])) < top as f64 - 0.05);
772 assert!(s.end.is_on(0));
773 }
774
775 /// A centre-hit ball slides, then rolls at 5/7 of its speed, then
776 /// rolls on and slows steadily.
777 #[test]
778 fn slides_then_rolls() {
779 let mut r = Run::new(&only(&[(0, 0.3, 0.6)]), Shot { angle: 0, power: at(2.0) }, false);
780 let mut steps = 0;
781 while r.b[0].v != r.b[0].s {
782 r.advance();
783 steps += 1;
784 }
785 let v = r.b[0].v[0];
786 assert!((v - 2.0 * 5.0 / 7.0).abs() < 0.01, "rolls at {v}");
787 // Slip 2 m/s, gone at 7/2 μg.
788 let t = steps as f64 * DT;
789 assert!((t - 2.0 / (3.5 * MU_SLIDE * G)).abs() < 2.0 * DT, "{t}");
790 let before = r.b[0].v[0];
791 for _ in 0..HZ {
792 r.advance();
793 }
794 assert!((before - r.b[0].v[0] - MU_ROLL * G).abs() < 1e-6, "one second's rolling resistance");
795 }
796
797 #[test]
798 fn a_rail_skimming_ball_passes_the_side_pocket() {
799 let y = R + 0.0005;
800 let t = only(&[(0, 0.4, y)]);
801 let s = simulate(&t, Shot { angle: 0, power: at(0.9) }, false);
802 assert!(s.end.is_on(0), "dropped though it only rolled past");
803 assert!(m(s.end.pos[0][0]) > LEN / 2.0 + 0.2);
804 }
805
806 /// Sliding into a full hit: the cue ball stops dead (a stun shot).
807 /// Rolling into one: it stops, then its topspin pulls it on (follow).
808 #[test]
809 fn stun_and_follow() {
810 let t = only(&[(0, 0.6, 0.6), (5, 0.6 + 2.0 * R + 0.005, 0.6)]);
811 let s = simulate(&t, Shot { angle: 0, power: at(0.7) }, true);
812 assert_eq!(s.first, Some(5));
813 assert!(m(s.end.pos[0][0]) < 0.62, "the stunned cue ball stays at the contact");
814 assert!(m(s.end.pos[5][0]) > 1.3, "the object ball runs on");
815 let t = only(&[(0, 0.3, 0.6), (5, 1.2, 0.6)]);
816 let s = simulate(&t, Shot { angle: 0, power: at(1.0) }, true);
817 assert_eq!(s.first, Some(5));
818 assert!(m(s.end.pos[0][0]) > 1.2 + 0.03, "the rolling cue ball follows through");
819 assert!(rolled(&s, 5) > rolled(&s, 0) - 0.95, "and the object ball runs further");
820 }
821
822 #[test]
823 fn ball_on_ball_restitution() {
824 let mut r = Run::new(&only(&[(0, 0.6, 0.6), (5, 0.7, 0.6)]), Shot { angle: 0, power: at(2.0) }, true);
825 while r.out.first.is_none() {
826 r.advance();
827 }
828 let Event::Clack { speed, .. } = r.out.events[1] else { panic!() };
829 let (v0, v5) = (r.b[0].v[0], r.b[5].v[0]);
830 // (Less a step's cloth friction since the contact.)
831 assert!(((v5 - v0) / speed - E_BALL).abs() < 0.005, "separate at e");
832 assert!((v0 + v5 - speed).abs() < 0.01, "momentum kept");
833 }
834
835 #[test]
836 fn the_break_spreads_the_rack() {
837 let t = Table::racked(&ORDER);
838 let s = simulate(&t, Shot { angle: 0, power: FULL }, false);
839 assert_eq!(s.first, Some(ORDER[0]));
840 let moved = (1..BALLS).filter(|&k| s.end.pos[k] != t.pos[k]).count();
841 assert!(moved >= 12, "only {moved} balls moved");
842 assert!(s.rail_after);
843 let _ = (FOOT_X, HEAD_X);
844 }
845
846 #[test]
847 fn aim_finds_the_ball_and_the_cushion() {
848 let t = only(&[(0, 0.6, 0.6), (5, 1.0, 0.6)]);
849 let a = aim(&t, [0.6, 0.6], 0);
850 assert_eq!(a.ball, Some(5));
851 assert!((a.hit[0] - (1.0 - 2.0 * R)).abs() < 1e-6);
852 let b = aim(&t, [0.6, 0.6], deg(90.0));
853 assert_eq!(b.ball, None);
854 assert!((b.hit[1] - (WID - R)).abs() < 1e-9 && b.then[1] < 0.0);
855 // Continuous: a hair more angle moves the ghost ball a hair.
856 let (c1, c2) = (aim_dir(&t, [0.6, 0.6], [0.6, 0.8]), aim_dir(&t, [0.6, 0.6], [0.6000001, 0.7999999]));
857 let moved = (c1.hit[0] - c2.hit[0]).hypot(c1.hit[1] - c2.hit[1]);
858 assert!(moved > 0.0 && moved < 1e-5, "{moved}");
859 }
860
861 /// The smallest step of aim still changes where the object ball goes,
862 /// and a thousand steps (under a ten-thousandth of a degree) where it
863 /// comes to rest.
864 #[test]
865 fn one_angle_step_still_counts() {
866 let t = only(&[(0, 0.5, 0.6), (6, 1.3, 0.62)]);
867 let after = |angle: u32| {
868 let mut r = Run::new(&t, Shot { angle, power: at(2.0) }, false);
869 while r.out.first.is_none() {
870 r.advance();
871 }
872 r.b[6].v
873 };
874 assert_ne!(after(deg(1.0)), after(deg(1.0) + 1));
875 let a = simulate(&t, Shot { angle: deg(1.0), power: at(2.0) }, false);
876 let b = simulate(&t, Shot { angle: deg(1.0) + 1000, power: at(2.0) }, false);
877 assert_ne!(a.end.pos[6], b.end.pos[6]);
878 }
879}