SDF

SDF stands for “Signed Distance Field” or “Signed Distance Function”. The difference between the two is unclear, but it seems that a distance function produces a distance field. The terms are used interchangeably though.

float DistanceToCircle(Vector2 p, float r)
{
    return p.Length() - r;
}

This is the most straightforward SDF. It returns the signed distance from point p to the surface (edge) of a circle at the origin with radius r. If p is a point on the surface, it returns zero. If it’s inside the circle, it returns a negative distance. Otherwise, the returned value is the positive distance. This is a 2D function but they can be expanded to however many dimensions.

You can perform boolean-like operations with these by subtracting, adding, min, or maxing the resulting values of many different functions. This way, many different shapes can be created and queried. It’s not a perfect boolean operation, though, as the returned value won’t necessarily be the distance to the surface of the compound shape anymore, but instead a melted mess that is only guaranteed to be zero on the surface, positive outside it, and negative inside it. It’s possible to derive an exact SDF from multiple shapes but this is difficult and generally not needed.

Distance functions are very versatile tools. They can be (and are) used extensively in game development in fields like graphics, AI, UI, procgen, physics, and so on.

The signed variant of distance functions is seemingly more common than the unsigned one, which is why this page is named as such, but unsigned distance functions won’t be excluded here.