Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
444 changes: 444 additions & 0 deletions apps/web/src/components/billiards/BilliardsOverlay.tsx

Large diffs are not rendered by default.

53 changes: 53 additions & 0 deletions apps/web/src/components/billiards/billiardsAim.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vite-plus/test";

import { castTrajectory } from "./billiardsAim.ts";
import { makeBall, shotSpeed, type PhysicsEvent } from "./billiardsPhysics.ts";
import { BilliardsGame } from "./billiardsRules.ts";
import { BALL_RADIUS } from "./billiardsTable.ts";

const R = BALL_RADIUS;

describe("castTrajectory", () => {
it("stops where the cue ball touches the first ball", () => {
const cue = makeBall(0, 0.5, 1.5);
const path = castTrajectory([cue, makeBall(3, 0.5, 1)], cue, -Math.PI / 2);
expect(path.ball?.id).toBe(3);
expect(path.points.at(-1)?.y).toBeCloseTo(1 + 2 * R);
});

it("follows the cue ball off a cushion to a ball behind it", () => {
const cue = makeBall(0, 0.5, 1.8);
// 45 degrees up and right: off the right rail, then on to a ball up on the left.
const bounceY = 1.8 - (1 - R - 0.5);
// The rail keeps 72% of the speed into it and 94% along it, like the physics.
const out = Math.hypot(0.72, 0.94);
const target = makeBall(5, 1 - R - (0.4 * 0.72) / out, bounceY - (0.4 * 0.94) / out);
const path = castTrajectory([cue, target], cue, -Math.PI / 4);
expect(path.points).toHaveLength(3);
expect(path.points[1]?.x).toBeCloseTo(1 - R);
expect(path.ball?.id).toBe(5);
});

it("ends in the pocket when the cue ball heads straight into one", () => {
const cue = makeBall(0, 0.3, 0.3);
const path = castTrajectory([cue], cue, (-3 * Math.PI) / 4);
expect(path.pocket).toBe(0);
expect(path.ball).toBeNull();
});

it("predicts where a real shot comes off two cushions and stops", () => {
const cue = makeBall(0, 0.3, 1.6);
const angle = -1.1;
const speed = shotSpeed(0.45);
const path = castTrajectory([cue], cue, angle, speed, 6);
const game = new BilliardsGame({ skipBreak: true, balls: [makeBall(0, 0.3, 1.6)] });
game.shoot(angle, speed);
const events: PhysicsEvent[] = [];
while (game.phase === "rolling") game.advance(1 / 60, events);
const end = path.points.at(-1)!;
const ball = game.ball(0)!;
expect(path.points.length).toBeGreaterThanOrEqual(3);
expect(path.stops).toBe(true);
expect(Math.hypot(end.x - ball.x, end.y - ball.y)).toBeLessThan(0.03);
});
});
133 changes: 133 additions & 0 deletions apps/web/src/components/billiards/billiardsAim.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import {
CUSHION_GRIP,
CUSHION_RESTITUTION,
DRAG,
ROLL_DECEL,
type Ball,
} from "./billiardsPhysics.ts";
import { BALL_RADIUS, TABLE_LENGTH, TABLE_WIDTH, type Point } from "./billiardsTable.ts";

const R = BALL_RADIUS;
/** How many cushions the guide follows the cue ball off. */
const AIM_BOUNCES = 2;
const MAX_LENGTH = 3;
/** The golden cue's full sight. */
export const GOLDEN_SIGHT = { bounces: 5, length: 7 } as const;

export interface Trajectory {
/** The cue ball's path: its centre at the start, at each cushion, and where it ends. */
readonly points: ReadonlyArray<Point>;
/** The ball it hits first, with the cue ball touching it at the path's last point. */
readonly ball: Ball | null;
/** The path ends in this pocket: a scratch, unless a ball comes first. */
readonly pocket: number | null;
/** The cue ball runs out of speed at the path's end. */
readonly stops: boolean;
/** Direction of the last segment, for the cue ball's deflection off `ball`. */
readonly dx: number;
readonly dy: number;
}

// Where the rails open into a pocket, measured along the rail the path reaches.
const CORNER_OPENING = 0.07;
const SIDE_OPENING = 0.045;

/** The pocket whose mouth the path reaches at a rail, if any. */
function pocketAt(x: number, y: number, onSideRail: boolean): number | null {
const right = x > TABLE_WIDTH / 2;
const top = y < TABLE_LENGTH / 2;
if (onSideRail && Math.abs(y - TABLE_LENGTH / 2) < SIDE_OPENING) return right ? 3 : 2;
const along = onSideRail ? Math.min(y, TABLE_LENGTH - y) : Math.min(x, TABLE_WIDTH - x);
if (along < CORNER_OPENING) return top ? (right ? 1 : 0) : right ? 5 : 4;
return null;
}

/** How far a ball rolling at `speed` travels before friction stops it (same law as the physics). */
function stoppingDistance(speed: number): number {
return speed / DRAG - (ROLL_DECEL / (DRAG * DRAG)) * Math.log(1 + (DRAG * speed) / ROLL_DECEL);
}

/** The speed left after rolling `distance` from `speed`. */
function speedAfter(speed: number, distance: number): number {
const target = stoppingDistance(speed) - distance;
if (target <= 0) return 0;
let low = 0;
let high = speed;
for (let i = 0; i < 30; i++) {
const mid = (low + high) / 2;
if (stoppingDistance(mid) < target) low = mid;
else high = mid;
}
return (low + high) / 2;
}

/**
* Where the cue ball goes along `angle` if nothing slows it: off up to `bounces` cushions,
* until it touches a ball, runs into a pocket, or (given a `speed`) stops. Cushions bounce it the
* way the physics does: they keep less of the speed into the rail than along it.
*/
export function castTrajectory(
balls: ReadonlyArray<Ball>,
cue: Ball,
angle: number,
speed: number | null = null,
bounces: number = AIM_BOUNCES,
maxLength: number = MAX_LENGTH,
): Trajectory {
let v = speed ?? Infinity;
let x = cue.x;
let y = cue.y;
let dx = Math.cos(angle);
let dy = Math.sin(angle);
let travelled = 0;
const points: Point[] = [{ x, y }];
for (let bounce = 0; ; bounce++) {
let best = Infinity;
let hit: Ball | null = null;
for (const ball of balls) {
if (!ball.onTable || ball === cue) continue;
const fx = x - ball.x;
const fy = y - ball.y;
const b = fx * dx + fy * dy;
const c = fx * fx + fy * fy - 4 * R * R;
const disc = b * b - c;
if (disc < 0) continue;
const t = -b - Math.sqrt(disc);
if (t > 1e-6 && t < best) {
best = t;
hit = ball;
}
}
const wallX = dx > 0 ? (TABLE_WIDTH - R - x) / dx : dx < 0 ? (R - x) / dx : Infinity;
const wallY = dy > 0 ? (TABLE_LENGTH - R - y) / dy : dy < 0 ? (R - y) / dy : Infinity;
const wall = Math.max(0, Math.min(wallX, wallY));
const rolls = v === Infinity ? Infinity : stoppingDistance(v);
const remaining = Math.min(maxLength - travelled, rolls);
if (hit && best <= wall && best <= remaining) {
points.push({ x: x + dx * best, y: y + dy * best });
return { points, ball: hit, pocket: null, stops: false, dx, dy };
}
const step = Math.min(wall, remaining);
x += dx * step;
y += dy * step;
travelled += step;
points.push({ x, y });
if (step === remaining) {
return { points, ball: null, pocket: null, stops: rolls <= wall, dx, dy };
}
const pocket = pocketAt(x, y, wall === wallX);
if (pocket !== null || bounce >= bounces) {
return { points, ball: null, pocket, stops: false, dx, dy };
}
// Same bounce as the physics: the speed into the rail drops more than the speed along it.
const normalX = wall === wallX;
const along = normalX ? dy : dx;
const into = normalX ? dx : dy;
const outAlong = along * CUSHION_GRIP;
const outInto = -into * CUSHION_RESTITUTION;
const factor = Math.hypot(outAlong, outInto);
dx = normalX ? outInto / factor : outAlong / factor;
dy = normalX ? outAlong / factor : outInto / factor;
if (v !== Infinity) v = speedAfter(v, step) * factor;
}
}
133 changes: 133 additions & 0 deletions apps/web/src/components/billiards/billiardsAudio.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Every sound is synthesised, so the game ships no audio files.

const clamp01 = (value: number) => Math.max(0, Math.min(1, value));

export class BilliardsAudio {
private context: AudioContext | null = null;
private master: GainNode | null = null;
private noise: AudioBuffer | null = null;

/** Starts audio; call from a user gesture. */
unlock(): void {
if (!this.context) {
const context = new AudioContext();
const master = context.createGain();
master.gain.value = 0.55;
master.connect(context.destination);
const noise = context.createBuffer(
1,
Math.floor(context.sampleRate * 0.4),
context.sampleRate,
);
const data = noise.getChannelData(0);
for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
this.context = context;
this.master = master;
this.noise = noise;
}
if (this.context.state === "suspended") void this.context.resume();
}

dispose(): void {
void this.context?.close();
this.context = null;
}

/** Ball on ball: a bright click whose pitch and level follow the impact. */
click(speed: number): void {
const v = clamp01(speed / 5);
if (v < 0.01) return;
this.tone("sine", 2300 + Math.random() * 900 + v * 600, 1900, v * 0.45, 0.05);
this.hiss("bandpass", 3600, 1.4, v * 0.55, 0.02);
}

/** Ball on cushion: a low, soft thud. */
cushion(speed: number): void {
const v = clamp01(speed / 4);
if (v < 0.02) return;
this.tone("sine", 150, 70, v * 0.6, 0.12);
this.hiss("lowpass", 700, 0.7, v * 0.35, 0.07);
}

/** Ball into a pocket: a hollow drop, then a rattle in the pocket. */
pocket(): void {
this.tone("triangle", 240, 85, 0.35, 0.28);
this.hiss("bandpass", 950, 2, 0.22, 0.05, 0.09);
this.hiss("bandpass", 780, 2, 0.14, 0.05, 0.17);
}

/** Cue tip on the cue ball. */
cue(power: number): void {
const p = clamp01(power);
this.hiss("bandpass", 1500 + p * 900, 0.9, 0.25 + p * 0.5, 0.03);
this.tone("sine", 700 + p * 300, 500, 0.15 + p * 0.2, 0.04);
}

/** A power-up: a quick rising chime. */
powerUp(): void {
for (const [i, note] of [784, 1047, 1319, 1568].entries()) {
this.tone("sine", note, note * 1.01, 0.22, 0.28, i * 0.055);
this.tone("triangle", note * 2, note * 2, 0.05, 0.18, i * 0.055);
}
}

/** A soft two-note bell: a thread wants attention. */
chime(): void {
this.tone("sine", 1318, 1318, 0.2, 0.6);
this.tone("sine", 1760, 1760, 0.16, 0.8, 0.12);
}

/** A ball taken by a power-up: a soft magic swish. */
guide(): void {
this.tone("sine", 520, 1400, 0.16, 0.35);
this.hiss("highpass", 5000, 0.7, 0.08, 0.3);
}

private tone(
type: OscillatorType,
from: number,
to: number,
gain: number,
decay: number,
delay = 0,
): void {
const { context, master } = this;
if (!context || !master) return;
const at = context.currentTime + delay;
const oscillator = context.createOscillator();
const envelope = context.createGain();
oscillator.type = type;
oscillator.frequency.setValueAtTime(from, at);
oscillator.frequency.exponentialRampToValueAtTime(to, at + decay);
envelope.gain.setValueAtTime(gain, at);
envelope.gain.exponentialRampToValueAtTime(0.0001, at + decay);
oscillator.connect(envelope).connect(master);
oscillator.start(at);
oscillator.stop(at + decay + 0.02);
}

private hiss(
type: BiquadFilterType,
frequency: number,
q: number,
gain: number,
decay: number,
delay = 0,
): void {
const { context, master, noise } = this;
if (!context || !master || !noise) return;
const at = context.currentTime + delay;
const source = context.createBufferSource();
const filter = context.createBiquadFilter();
const envelope = context.createGain();
source.buffer = noise;
filter.type = type;
filter.frequency.value = frequency;
filter.Q.value = q;
envelope.gain.setValueAtTime(gain, at);
envelope.gain.exponentialRampToValueAtTime(0.0001, at + decay);
source.connect(filter).connect(envelope).connect(master);
source.start(at, Math.random() * 0.3);
source.stop(at + decay + 0.02);
}
}
Loading
Loading