Recursive AI

Draw pouring liquid with a smooth surface in C#

onegame is a free, open-source game engine for .NET from Recursive AI. MIT or Apache-2.0, no editor required.

Draw the particles with FluidSurface2D instead of drawing dots.

Terminal
dotnet add package RecursiveAI.OneGame.Host
dotnet add package RecursiveAI.OneGame.Physics

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using System.Numerics;
using OneGame.Host;
using OneGame.Physics;
 
using var surface = new FluidSurface2D("water");
surface.Style.ParticleRadius = 3.2f;
surface.Style.Blur = 1.76f;
var points = new Vector2[2048];
// Call from a view with its Draw2D and fluid space.
void DrawWater(Draw2D draw, PhysicsSpace2D space)
{
    int count = space.GetFluidPositions(points);
    surface.Draw(draw, points.AsSpan(0, count), 20);
}

A smooth blue column of water spreading across a gray platform

This fragment belongs in a view. See WaterView in the full program for where draw and space come from. The view draws a continuous surface at 20 drawing units per physics unit. This style assumes 0.08 particle spacing. Keep the surface and buffer between frames.

Unzip the example, then dotnet run.

On Linux, the example needs Vulkan because it renders on the GPU.

The full program

The example uses no asset files. It releases a rectangle of water from (-1, 1) to (1, 5) above a solid floor, steps the simulation, then saves one frame. RecursiveAI.OneGame.Host includes the source generator: it registers the [Entity] and its [View] under OneGame.Generated.Example, based on the Example.csproj project name. The project enables implicit System usings for AsSpan.

C#
using System.Numerics;
using OneGame.Atlas;
using OneGame.Core;
using OneGame.Host;
using OneGame.Physics;
using OneGame.Render2D;
using OneGame.Text;
using OneGame.UI;
using RecursiveAI.OneGpu;
 
const int width = 320, height = 180;
int ticks = args.Length != 0 && args[0] == "--pooled" ? 100 : 65;
var registry = new EntityRegistry();
OneGame.Generated.Example.EntityTypes.Register(registry);
var world = new World(1, registry);
var space = PhysicsSpace2D.AddTo(world);
space.AddBox(new FVec2(10, 1), new FVec2(0, -3),
    new BodyOptions { Kind = BodyKind.Static });
space.SetFluidSettings(new FluidWorldSettings { MaxParticles = 2048 });
var water = space.AddFluid(new FluidOptions
{
    Preset = FluidPreset.Liquid,
    Spacing = Fixed.FromRatio(8, 100)
});
space.FillFluidBox(water, new FVec2(-1, 1), new FVec2(1, 5));
using var surface = new FluidSurface2D("water", new FluidSurfaceStyle
{
    ParticleRadius = 3.2f,
    Blur = 1.76f,
    Threshold = 0.38f,
    RimWidth = 0.15f
});
world.Add(new WaterView { Surface = surface });
for (int tick = 0; tick < ticks; tick++) world.Step();
 
var fonts = new FontLibrary();
using var device = GpuBackends.CreateDevice();
using var stage = new Render2DStage(new HostResources(
    fonts, new FontTextMeasurer(fonts), new ArtAtlas(), GeneratedShaders.Instance));
using var target = device.CreateTexture(new TextureDesc(width, height,
    GpuFormat.Rgba8UnormSrgb, TextureUsage.RenderTarget | TextureUsage.CopySource));
stage.Render(device, target,
    new FrameInfo(width, height, 1, world.Tick, new DisplayList(), world, Fixed.Zero));
var pixels = new byte[width * height * 4];
device.ReadTexture(target, 0, 0, pixels);
Png.Save(new CapturedFrame(width, height, pixels, device.Adapter.ToString()), "pour.png");
Console.WriteLine($"Wrote pour.png ({width} x {height}, tick {world.Tick})");
 
[Entity]
partial class WaterView : Entity, IView2D
{
    public FluidSurface2D Surface { get; init; } = null!;
    private readonly Vector2[] points = new Vector2[2048];
 
    [View]
    public void Draw(Draw2D draw)
    {
        var space = PhysicsSpace2D.Of(World!)!;
        draw.FillRect(new Rect(-160, -90, 320, 180), Color.Rgb(0x162333));
        draw.FillRect(new Rect(-100, 50, 200, 20), Color.Rgb(0x45566b));
        int count = space.GetFluidPositions(points);
        Surface.Draw(draw, points.AsSpan(0, count), 20);
    }
}
Text
Wrote pour.png (320 x 180, tick 65)

Open pour.png to see the rim and the water spreading along the floor. If the water breaks up into beads, check that ParticleRadius and Blur are sized after multiplying the particle spacing by the same scale passed to Draw.

Variations

Watch the same pour farther along. This writes a new pour.png at tick 100:

Terminal
dotnet run -- --pooled

The short answer

Use FluidPreset.Liquid for the movement and FluidSurface2D for the image. After the simulation steps, copy the positions into a reusable Vector2 array with GetFluidPositions. Pass only the filled portion to Draw. The renderer puts a soft blob at each point, blurs their edges together, then draws a filled surface and a rim where the result crosses a cutoff.

How do you draw a smooth water surface from particles?

Match the drawing style to the spacing of the simulation. Here the spacing is 0.08 physics units, or 1.6 drawing units at a scale of 20. The full program sets ParticleRadius to 3.2 and Blur to 1.76, roughly twice the spacing and just over the spacing, respectively. That gives the blobs room to touch before the cutoff is applied.

Tune Threshold while the water is both falling and pooled. Lower values join more gaps and thicken the outline. Higher values can separate a narrow stream into drops. Change RimWidth if the edge is too pronounced; it changes the look, not the fluid movement. The physics uses Y up, while the drawing uses Y down. Draw flips Y by default.

How do you keep a stream of liquid together in a 2D game?

First decide whether the gap is in the simulation or only in the drawing. A sparse fluid has too few points to outline a thin stream; use a smaller particle spacing and a budget large enough for the volume you want. When the points are close but the image still has holes, adjust the drawing style before changing the physics. The OneGame fluid guide distinguishes surface tension, which acts on the particles, from the rendering threshold, which acts only on their image.

GetFluidPositions also accepts a fluid handle if your scene contains multiple fluids. Use that filter when water and oil need separate looks, and give each FluidSurface2D its own layer name. If you already manage your own render layer, the same cutoff pass is available through PostChain.AddFluidSurface; UpdateFluidSurface changes its settings later. The helper in this example handles the layer, blur, and cutoff together.

All onegame recipes