Skip to content
tailugePublic

Repository files navigation

Billiards - Free online pool and billiards game

codecov CodeFactor Code Smells Tests Open in Gitpod GitHub

Free online 3D pool and billiards game running in a browser, WebGL table viewed from behind the cue ball

This is an open-source project bringing unsophisticated billiards physics written in TypeScript to the browser.

Online Demo

Demos run in all major desktop and mobile browsers and use WebGL

Features

  • Backspin, sidespin and cushion bounces well modeled.
  • Presentation using WebGL in any modern browser on mobile, linux, mac or windows.
  • Record and playback breaks.
  • Two player online mode with nchan nginx server.
  • Nine ball, snooker, three cushion and Sagu billiards rules.
  • Deploys to GitHub Pages, Vercel and Render with GitHub Actions.
  • Runs on and was developed mostly on a potato e.g. Raspberry Pi 4.

Install

You dont, you just play in your browser at billiards.tailuge.workers.dev/lobby

If you prefer, you can install a thin client wrapper:

Reference material

Key equations

Based on Han 2005 paper

surface velocity

$$\vec{v}_a = \vec{v} + (\vec{up} \times R\vec{\omega})$$

sliding motion

$$\dot{v} = -\mu g \frac{\vec{v}_a}{|\vec{v}_a|}$$

$$\dot{\omega} = -\frac{5}{2}\frac{\mu g}{R} \frac{\vec{v}_a}{|\vec{v}_a|}$$

$$\dot{\omega}_z = -\frac{5}{2}\frac{M_z}{mR^2} \text{sgn}(\omega_z)$$

rolling motion

$$\dot{v} = -\frac{5}{7}\frac{M_{xy}}{mR} \frac{\vec{up} \times \vec{\omega}}{|\vec{\omega}|}$$

$$\dot{\omega} = -\frac{5}{7}\frac{M_{xy}}{mR^2} \frac{\vec{\omega}}{|\vec{\omega}|}$$

where

$M_{xy} = \frac{7}{5\sqrt{2}} R \mu m g$ , $M_z = \frac{2}{3} \mu m g \rho$

collisions

Based on paper by Alciatore incorporating throw effect due to the small amount of friction between balls. Figures to prove consistency between the code and paper can be found in the Mathavan model validation diagram.

For ball $a$:

$$\vec{v}_a \leftarrow \vec{v}_a + \frac{J_{\text{normal}}}{m}\hat{n} + \frac{J_{\text{tangential}}}{m}\hat{t}$$

$$\vec{\omega}_a \leftarrow \vec{\omega}_a + \frac{1}{I} (\vec{r}_a \times \vec{J}_{\text{tangential}})$$

For ball $b$:

$$\vec{v}_b \leftarrow \vec{v}_b - \frac{J_{\text{normal}}}{m}\hat{n} - \frac{J_{\text{tangential}}}{m}\hat{t}$$

$$\vec{\omega}_b \leftarrow \vec{\omega}_b + \frac{1}{I} (\vec{r}_b \times \vec{J}_{\text{tangential}})$$

Where:

The relative velocity at the point of contact is computed as:

$$\vec{v}_{\text{rel}} = (\vec{v}_a - \vec{v}_b) + \vec{r}_a \times \vec{\omega}_a - \vec{r}_b \times \vec{\omega}_b$$

$$\vec{v}_{\text{slip}} = \vec{v}_{\text{rel}} - (\vec{v}_{\text{rel}} \cdot \hat{n}) \hat{n}$$

$\vec{r}_a = -R \cdot \hat{n}$ and $\vec{r}_b = R \cdot \hat{n}$

$J_{\text{normal}} = \frac{-(1 + e)v_{\text{rel,normal}}}{(2/m)}$

$J_{\text{tangential}} = \min\left( \frac{\mu J_{\text{normal}}}{v_{\text{rel}}}, \frac{1}{7} \right)(-v_{\text{rel,tangential}})$

$\hat{n}$: normal unit vector along the line of centers.

$\hat{t}$: tangential unit vector perpendicular to $\hat{n}$.

cushion bounce

This is based on a paper by Mathavan. Many of the figures from the paper are recreated to confirm correctness.

Slip velocity at cushion contact point I

$$ ẋ_I = \dot{v_x} + \dot{\omega_y} R \sin \theta - \dot{\omega_z} R \cos \theta \qquad ẏ'_I = -\dot{v_y} \sin \theta + \dot{\omega_x} R $$

$$ \phi = \arctan\left(\frac{ẏ'_I}{ẋ_I}\right) \qquad s = \sqrt{(ẋ_I)^2 + (ẏ'_I)^2} $$

Slip velocity at table contact point C

$$ ẋ_C = \dot{v_x} - \dot{\omega_y} R \qquad ẏ_C = \dot{v_y} + \dot{\omega_x} R $$

$$ \phi' = \arctan\left(\frac{ẏ_C}{ẋ_C}\right) \qquad s' = \sqrt{(ẋ_C)^2 + (ẏ_C)^2} $$

Numerical solutions for the centroid velocity of the ball during compression and restitution phases.

$$ (\dot{v_x})_{n+1} - (\dot{v_x})_n = - \frac{1}{M} \left[\mu_w \cos(\phi) + \mu_s \cos(\phi') \cdot (\sin \theta + \mu_w \sin(\phi) \cos \theta)\right] \Delta P_I $$

$$ (\dot{v_y})_{n+1} - (\dot{v_y})_n = - \frac{1}{M} \left[ \cos \theta - \mu_w \sin \theta \sin \phi + \mu_s \sin \phi' \cdot \left( \sin \theta + \mu_w \sin \phi \cos \theta \right) \right] \Delta P_I $$

Numerical solutions for angular velocity of ball

$$ (\dot{\omega_x})_{n+1}−(\dot{\omega_x})_n = -\frac{5}{2MR}[\mu_w \sin(\phi) + \mu_s \sin(\phi') \times (\sin(\theta) + \mu_w \sin(\phi)\cos(\theta))]\Delta P_I $$

$$ (\dot{\omega_y})_{n+1}−(\dot{\omega_y})_n = -\frac{5}{2MR}[\mu_w \cos(\phi)\sin(\theta) - \mu_s \cos(\phi') \times (\sin(\theta) + \mu_w \sin(\phi)\cos(\theta))]\Delta P_I $$

$$ (\dot{\omega_z})_{n+1}−(\dot{\omega_z})_n = \frac{5}{2MR}(\mu_w \cos(\phi)\cos(\theta))\Delta P_I $$

$\theta$ is a constant of the angle of cushion contact above ball centre with $\sin(\theta) = 2/5$. $\mu_s$ is the coefficient of sliding friction between the ball and table surface. $\mu_w$ is the coefficient of sliding friction between the ball and the cushion.

Work done by the normal force at contact point $I$ along the $Z'$-axis which is aligned from the ball centre to I

$$ W_{Z'}^I(P_I^{(n+1)}) = W_{Z'}^I(P_I^{(n)}) + \frac{\Delta P_I}{2} \left( z'_I(P_I^{(n+1)}) + z'_I(P_I^{(n)}) \right) $$

The ball is assumed to be bouncing in the +y cushion. Compression phase iterates until

$$\dot{v}_y \le 0$$

For the restitution phase the iteration continues until the work done is

$$W_{Z'}^I \ge e_e^2 W_{\text{compression}}$$

Some of the Mathavan equations not supplied by the paper were inferred to bridge gaps for a complete numerical solution.

Stronge compliant cushion model

Based on the book Impact Mechanics by Stronge. This analytical model accounts for the compliant nature of cushion deformation and resolves the collision across three slip regimes.

Contact velocity at the cushion contact point:

$$\vec{V}_c = \vec{v} - (\vec{\omega} \times R \hat{n})$$

Regime classification is determined by the ratio $v_{\text{ratio}} = v_{t0} / v_{n0}$ and thresholds involving the friction coefficient $\mu$, restitution $e_n$, and mass-matrix coefficients $\beta$:

Regime Condition
Gross slip $v_{\text{ratio}} > \mu \left( (1 + e_n) \beta_{\text{ratio}} - \frac{\eta^2}{e_n} \right)$
Initial stick $v_{\text{ratio}} < \mu \eta^2$
Slip-stick-slip neither of the above

where $\eta^2$ is derived from the frequency ratio $\omega_t/\omega_n$.

Velocity reconstruction from scalar solver results $v_{nf}$ and $v_{tf}$:

$$\Delta v_n = \frac{v_{nf} - v_{n0}}{\beta_n} , \quad \Delta v_t = \frac{v_{tf} - v_{t0}}{\beta_t}$$

Final updates:

$$\vec{v} \leftarrow \vec{v} + \Delta v_n \hat{n} + \Delta v_t \hat{t}$$ $$\vec{\omega} \leftarrow \vec{\omega} + \frac{mR}{I} (-\hat{n} \times \Delta v_t \hat{t})$$

Useful commands

Local setup and build

nvm use v24.11.0
corepack enable
yarn set version 4.9.1
yarn install
yarn build
yarn gltfpack

This generates artefacts in /dist for prod deployment (e.g. on github static pages)

Run

yarn serve

Then open http://localhost:8080/ in your browser to play

Test

yarn test
yarn coverage

Maintain

yarn deps
yarn upgrade -L
yarn prettify

Two player

yarn serve

then open http://localhost:8080/multi.html to see options, message server is public nchan.

Controls

Use mouse, trackpad, touch screen or keyboard:

⇦ ⇨ Aim

Control ⇦ ⇨ Fine aim

⇧ ⇩ Topspin and backspin

Shift ⇦ ⇨ Side spin

Space Hit - hold for more power

A Toggle aim helper

M Masse angle

O Camera view

F Full screen

C Chat

H Help

+ - Camera height

Mouse

scroll Shot power

dbl click Hit

Trajectory Fitting, Machine Learning & Simulation

The physics engine is lightweight and deterministic, making batch rollouts, parameter fitting, and simulation experiments practical:

  • Throughput & batch execution: Performs ~500 rollouts/sec on 4 CPU cores in pure TypeScript, scaling across worker threads. Runs in-browser via Web Workers or headlessly via Node.js for parallel batch runs.
  • System identification & real-to-sim calibration: Designed for trajectory fitting and physics calibration against recorded real-world shot trajectories. Used to estimate physical parameters such as rolling friction, sliding friction, spin decay, restitution, and cushion deflection.
  • Reinforcement learning & planning: Suitable as a fast test environment for RL agents, continuous control, Monte Carlo Tree Search (MCTS), trajectory forecasting, or synthetic dataset generation.
  • Parameter optimization: The multi-shot physics optimiser provides a starting point for fitting parameters and exploring the loss landscape against recorded shots.
  • Worker interface & headless runs: The Web Worker / simulation research page documents the worker protocol, parallel rollouts, headless Node.js scripts, batch processing, and runtime parameter overrides.

Contributions and experiments are welcome.

Progress snapshots

July 2018

WebGL pool table rendered in the browser, July 2018

July 2019

Ball shading and spin effects added to the WebGL table, July 2019

March 2021

Snooker style table and refined cue rendering, March 2021

August 2023 (mobile)

top aim
Top-down camera view for planning shots on a mobile screen Aim view along the cue on a mobile touchscreen

Billiards gameplay video from 2026

Star History

RepoStars

Licence

This project is open source and licensed under the GNU General Public License - see the LICENSE file for details. Contributions welcome.

Translations

🌐 Read this in 한국어 or 中文

한국어

설치도 가입도 필요 없는 무료 온라인 당구게임입니다. PC와 모바일의 웹 브라우저에서 주소만 입력하면 바로 당구대에 섭니다. 3쿠션 게임과 사구(4구) 게임은 물론 9볼, 스누커, 8볼 풀, 그리고 온라인 대전까지 한곳에서 이어집니다.

정말 당구장의 물리엔진을 그대로 옮겨 놓았습니다. 밀어치기와 끌어치기, 사이드스핀, 뒤스핀까지 공의 회전이 쿠션 반발에 미치는 영향까지 계산하고, 연습용 작은 테이블에서 12피트 정식 타일까지 감각을 그대로 옮겼습니다. 온라인 대전은 로비에서 지금 접속 중인 상대를 골라 바로 대국할 수 있고, 사람이 적은 새벽에는 ClawBreak과 TheFarJaw 같은 연습 봇과 실전처럼 붙어 볼 수도 있습니다.

스냅샷 녹화와 리플레이, 다이아몬드 시스템 구도 훈련, 물리 다이어그램에서 상수를 직접 바꿔보며 확인하는 기능, 그리고 Web Worker로 돌리는 배치 시뮬레이션까지 담고 있습니다. 2018년부터 GitHub에서 공개적으로 발전해 온 오픈소스 당구 프로젝트입니다.

네이버 블로그 티스토리 블로그

中文

免費線上斯諾克遊戲,免安裝、免註冊,打開瀏覽器就能直接開打。PC 與手機的網頁 版都支援,3 庫撞球(卡羅姆)、9球、8 球台球、線上斯諾克,以及線上真人對戰, 都能在線上遊戲大廳裡完成。

物理效果是照著論文模型做出來的:桿法旋轉、走位角度到顆星反彈都算得出來, 12呎正規賽桌和 6呎趣味模式各自保留不同手感。線上對戰可以挑對手直接下場, 人少的時段也有 ClawBreak、TheFarJaw 兩支機器人陪你練。另有斷球重播、破壞 練球、調整物理參數的圖表工具與 Web Worker 批次模擬,2018 年起在 GitHub 上公開發展的開源撞球專案。

Keywords

billiards, billiards simulator, online billiards, free billiards game, pool game, snooker game, 8-ball, 9-ball, three-cushion billiards, three cushion carom, carom billiards, 4-ball billiards, open source billiards, ビリヤード, ビリヤードゲーム, 無料ビリヤード, 3クッション, スリークッション, 9ボール, 당구, 무료 당구, 온라인 당구, 당구 게임, 3쿠션, 사구, 스누커, Bida 3 băng, bi-a 3 băng, Biliar 3 bandas, billar a tres bandas, billar de carambolas, jugar billar carambolas, billar online gratis, Üç bant bilardo, üç bant, driebanden, biljart, gratis biljart, biljart spel, Carom3D, ShootersPool

Mentions

Molbergen, Bored, AZBilliards, itch.io, SnookerForum, GameJolt, Billard-aktuell, Naver, Tistory, Ameblo, r/billiards, FMHY, AppImageHub, WebGames, IOGame, RepoRank, IndexPage, Slowden, Foundplay