A lightweight Ruby implementation of 2D fluid dynamics based on the Navier-Stokes equations using Jos Stam's stable fluid method.
gem install fluidrixOr add to your Gemfile:
gem 'fluidrix'The simulator solves the incompressible Navier-Stokes equations:
Where:
-
$\mathbf{u} = (u, v)$ - velocity field -
$p$ - pressure -
$\rho$ - density -
$\nu$ - kinematic viscosity -
$\mathbf{f}$ - external forces
- Add Forces - Apply external forces to velocity field
- Diffuse - Viscosity spreads velocity (Gauss-Seidel iteration)
- Project - Enforce mass conservation (pressure solve)
- Advect - Move velocity along itself
- Project - Final pressure correction
require 'fluidrix'
# Create simulator (width, height, viscosity, dt)
sim = Fluidrix::Simulator.new(100, 100, 0.0001, 0.1)
# Add velocity (x, y, amount)
sim.add_velocity(50, 50, 10.0, 5.0)
# Add density/dye (x, y, amount)
sim.add_density(50, 50, 1.0)
# Step simulation forward
sim.step
# Get field data
velocity_field = sim.velocity
density_field = sim.densityThe simulator provides raw arrays for:
- Velocity:
velocity[x][y] = {u: float, v: float} - Density:
density[x][y] = float
require 'fluidrix'
sim = Fluidrix::Simulator.new(128, 128)
# Add circular impulse
64.times do |i|
angle = i * Math::PI * 2 / 64
sim.add_velocity(64 + Math.cos(angle) * 10,
64 + Math.sin(angle) * 10,
Math.cos(angle) * 5,
Math.sin(angle) * 5)
end
100.times { sim.step }Open visualize.html in a browser for an interactive fluid simulation:
- Click and drag to add fluid and velocity
- Adjust viscosity, diffusion, and resolution
- Real-time velocity field visualization
| Parameter | Description | Typical Range |
|---|---|---|
| width, height | Grid resolution | 32-512 |
| viscosity | Fluid thickness | 0.00001 - 0.1 |
| dt | Time step | 0.01 - 0.5 |
MIT License - feel free to use in your projects!