“Signed distance functions”, or SDF sounds scary but it is not too crazy to understand. A SDF is a function that can tell you how far a point is from a surface of a shape, say a sphere (usually in Euclidean space)

「符号付き距離関数」(“Signed distance functions”、略してSDF)とは怖そうな名前ですが、実は割とシンプルです。SDFとは、ある点がある他の形の表面、例えば球面から(通常ユークリッド空間で)どのくらい離れているかを教えてくれる関数です。

For example the distance of a point of from the surface of a sphere can be expressed as below where $p$ is the coordinate of the point, $c$ is the center of the sphere, and $r$ is the radius:


$d = \sqrt{(p_{x}-c_{x})^{2} + (p_{y}-c_{y})^{2} + (p_{z}-c_{z})^{2}} - r$

This is very interesting because SDF is the technique used as basis for many mind-blowing 3D graphics demos with really small amount of code you often find on ShaderToy.


2D Demos

The three demonstrations below use SDF to define different shapes and fill in the inside and outside of the shape with dots.


The size of the dot represents the distance from the shape's boundary (the smaller the closer). White dots represent the inside of the shape. Black dots are outside the shape.


function sdf(p, center, radius) {
    return Math.sqrt(Math.pow(p.x - center.x, 2) + Math.pow(p.y - center.y, 2)) - radius; // or use p5.Vector.dist()