2D Signed Distance Functions🔗
Tricks for Deriving SDFs🔗
Assume the centre of the shape lies at the origin. Translation can be applied later. (see SDF transformations). This lets us calculate distances from the centre of the shape to point $p$ as just $|p|$
If the shape is symmetrical around its centre, you can limit the space you're working in to simply positive values, and use the absolute value in your calculations.
For example, if a shape is symmetrical in the $x$ axis, using $|x|$ in place of $x$ will yield the same result.
Circles🔗
A circle is defined by its radius $r$ (we are assuming it lies at the origin).
The distance between the centre of the circle and point $p$ is $|p|$.
The signed distance, $d$, between the circle and $p$ is: $$ \large d=|p|-r $$ Drag point $p$ or the circle to view changes:
Rectangles🔗
A rectangle is defined by its width and height. For this, we will define a 2-component radius $$ \large R = ({width \over 2}, \, {height \over 2}) $$
Rectangles are always symmetrical in both axes, so we only need to consider positive $x$ and $y$ values.
We call our positive position $abs(p)$
$$
\large
p = (x, \, y)
$$
$$
\large
\therefore abs(p) = (abs(x), \, abs(y))
$$
Since we are working in $+x$, $+y$ we are only considering the top right corner.
This corner will be at position $R$
We can now calculate the vector from this corner to $p$ with: $$ \large q = p - R $$
If $p$ is inside the rectangle ($q_x<0$ and $q_y<0$):
$d<0$. The distance is the shortest of $q_x$ and $q_y$. Since these are negative we take the maximum component:
$$ \large
d = maxcomp(q)
$$
If $p$ is outside the rectangle ($q_x>=0$ or $q_y>=0$):
$d>0$
If $q_y<0$, $d=q_x$
If $q_x<0$, $d=q_y$
Otherwise, $d=length(q)$
This can be simplified into: $$ \large q' = (max(q_x,0), \, max(q_y,0) $$ $$ \large d = length(q') $$
Show symmetry