Skip to main content

polySDF: Regular Polygon Distance Field

Parametric Regular Polygons with Variable Vertex Count​

The polySDF function generates signed distance fields for regular polygons with arbitrary vertex count. This function utilizes angular subdivision and polar coordinate mathematics to create precise geometric shapes.

Mathematical Foundation​

The polygon distance function operates through angular discretization:

dpoly=cos⁡(⌊av+0.5⌋⋅v−a)⋅rd_{\text{poly}} = \cos\left(\lfloor\frac{a}{v} + 0.5\rfloor \cdot v - a\right) \cdot r

where:

  • a=arctan⁡(px,py)+πa = \arctan(p_x, p_y) + \pi is the angle from point to origin
  • r=∣p∣r = |p| is the radial distance
  • v=2πVv = \frac{2\pi}{V} is the angular step for VV vertices

The floor operation discretizes the angle into VV equal segments, creating the polygon structure.

Function Parameters​

ParameterTypeDescription
stvec2Sample point in normalized coordinates
VintNumber of polygon vertices

Implementation Demonstrations​

Live Editor

const fragment = () => {
      const center = vec2(0.5)
      const minDist = float(1).toVar()
      Loop(4, ({ i }) => {
              const sides = i.add(3)
              const offset = vec2(
                      i.mod(2).mul(0.5).add(0.25),
                      i.div(2).floor().mul(0.5).add(0.25)
              )
              const p = uv.sub(offset)
              const d = polySDFFloat(p.add(0.5), sides.toFloat()).sub(0.2).abs().sub(0.02)
              minDist.assign(minDist.min(d))
      })
      const brightness = minDist.step(0).mul(0.9).add(float(0.02).smoothstep(0, minDist.abs()).mul(0.3))
      const hue = uv.x.add(uv.y).mul(0.5)
      return vec4(brightness.mul(vec3(hue.mul(0.8).add(0.2), 0.6, 1)), 1)
}
Result
Loading...