メインコンテンツまでスキップ

rectSDF: Two-Dimensional Rectangular Distance Field

Flexible Rectangle Generation with Size and Rounding Control

The rectSDF function family provides comprehensive 2D rectangular primitives with support for custom dimensions, uniform sizing, and corner rounding. This versatile primitive forms the foundation for UI elements and geometric compositions.

Mathematical Foundation

The rectangular SDF uses coordinate normalization and maximum distance selection:

drect(st,s)=max(stx0.5sx,sty0.5sy)d_{\text{rect}}(st, s) = \max\left(\frac{|st_x - 0.5|}{s_x}, \frac{|st_y - 0.5|}{s_y}\right)

For rounded rectangles, the distance incorporates corner radius:

drounded(p,b,r)=max(0,p0.54.2b+r)+min(0,max(dx,dy))rd_{\text{rounded}}(p, b, r) = \|\max(\mathbf{0}, |p - 0.5| \cdot 4.2 - b + r)\| + \min(0, \max(d_x, d_y)) - r

Function Signatures

rectSDF (Custom Dimensions)

ParameterTypeDescription
stvec2Sample point coordinates
svec2Rectangle half-dimensions

rectSDFUniform (Square)

ParameterTypeDescription
stvec2Sample point coordinates
sfloatUniform half-size

rectSDFRounded (Rounded Corners)

ParameterTypeDescription
pvec2Sample point coordinates
bvec2Rectangle dimensions
rfloatCorner radius

Implementation Demonstrations

ライブエディター
const fragment = () => {
      const size = vec2(0.6, 0.3).mul(iTime.sin().mul(0.3).add(1))
      const dist = rectSDF(uv, size)
      const inside = dist.step(1)
      const edge = float(1.02).smoothstep(0.98, dist)
      const color = inside.mul(0.7).add(edge.mul(0.4))
      return vec4(color.mul(vec3(1, 0.5, 0.3)), 1)
}