TExcelTAD
Home › Pre-Calculus, Geometry & Trigonometry › Procedural Shapes and Meshes

Procedural Shapes and Meshes

"Procedural" means generated by code instead of drawn by hand. With nothing more than cos⁡\cos, sin⁡\sin and a loop you can produce any regular polygon, a star, or a circle made of triangles ready for the GPU. This lesson builds all three and answers a practical question: how many triangles does a circle need before nobody can see the corners?

Regular polygons

A regular polygon with nn sides has its vertices equally spaced on a circle (the circumscribed circle). Vertex kk sits at angle θ0+k⋅2π/n\theta_0 + k \cdot 2\pi/n (polygons, the unit circle):

xk=cx+rcos⁡(θ0+2πk/n)yk=cy+rsin⁡(θ0+2πk/n)k=0,1,…,n−1\begin{aligned} x_k &= c_x + r\cos(\theta_0 + 2\pi k/n) \\ y_k &= c_y + r\sin(\theta_0 + 2\pi k/n) && k = 0, 1, \ldots, n - 1 \end{aligned}

θ0\theta_0 rotates the whole shape: θ0=π/2\theta_0 = \pi/2 puts a vertex straight up, which is how most icons and game pieces want a triangle or pentagon. Some useful facts:

Quantity Formula Hexagon, r=1r = 1
Central angle 2π/n2\pi/n 60°
Interior angle (n−2)⋅180∘/n(n - 2) \cdot 180^\circ/n 120°
Side length 2rsin⁡(π/n)2r\sin(\pi/n) 1
Area 12nr2sin⁡(2π/n)\frac{1}{2} n r^2 \sin(2\pi/n) 33/2≈2.5983\sqrt{3}/2 \approx 2.598

Stars

A star with nn points is a polygon with 2n2n vertices whose radius alternates between an outer radius RR and an inner radius rr, at angle steps of π/n\pi/n. The ratio r/Rr/R sets the look: small values give spiky stars, values near 1 almost a polygon. The classic five-pointed star, whose edges line up into straight lines (a pentagram), has r/R=cos⁡72∘/cos⁡36∘≈0.382r/R = \cos 72^\circ / \cos 36^\circ \approx 0.382.

python · try it yourself
import math
import matplotlib.pyplot as plt

def polygon(n, r=1.0, c=(0.0, 0.0), theta0=math.pi / 2):
    return [(c[0] + r * math.cos(theta0 + 2 * math.pi * k / n),
             c[1] + r * math.sin(theta0 + 2 * math.pi * k / n)) for k in range(n)]

def star(n, R=1.0, r=0.4, c=(0.0, 0.0), theta0=math.pi / 2):
    pts = []
    for k in range(2 * n):
        rad = R if k % 2 == 0 else r
        a = theta0 + math.pi * k / n
        pts.append((c[0] + rad * math.cos(a), c[1] + rad * math.sin(a)))
    return pts

hexagon = polygon(6, theta0=0)
print("hexagon:", [(round(x, 3), round(y, 3)) for x, y in hexagon])
side = math.dist(hexagon[0], hexagon[1])
print(f"side {side:.4f}, formula {2 * math.sin(math.pi / 6):.4f}")
print(f"pentagram inner ratio {math.cos(math.radians(72)) / math.cos(math.radians(36)):.6f}")

fig, ax = plt.subplots(figsize=(7, 3))
shapes = [polygon(3, c=(0, 0)), polygon(5, c=(2.5, 0)), polygon(6, c=(5, 0), theta0=0),
          star(5, r=0.382, c=(7.5, 0)), star(8, r=0.6, c=(10, 0))]
for pts in shapes:
    xs, ys = zip(*(pts + pts[:1]))           # repeat the first point to close the outline
    ax.fill(xs, ys, alpha=0.3); ax.plot(xs, ys)
ax.set_aspect("equal"); ax.axis("off")
hexagon: [(1.0, 0.0), (0.5, 0.866), (-0.5, 0.866), (-1.0, 0.0), (-0.5, -0.866), (0.5, -0.866)]
side 1.0000, formula 1.0000
pentagram inner ratio 0.381966

A circle as a triangle mesh

GPUs draw triangles, so a filled circle must become triangles. The simplest mesh is a triangle fan: one vertex at the centre, nn vertices on the rim, and triangle kk joins the centre with rim vertices kk and k+1k + 1 (wrapping round to 0 at the end).

vertices: n+1(centre + rim)triangles: nindices (0, k+1, (k+1) mod n+1)\begin{aligned} &\text{vertices: } n + 1 && \text{(centre + rim)} \\ &\text{triangles: } n && \text{indices } (0,\ k + 1,\ (k + 1) \bmod n + 1) \end{aligned}

A ring (a donut shape, like a health-bar circle or a selection marker) needs an inner and an outer rim of nn vertices each and two triangles per segment: 2n2n vertices and 2n2n triangles.

How many segments nn? The straight edge of each segment cuts inside the true circle. The largest gap, the sagitta, is in the middle of each edge:

error=r(1−cos⁡(π/n))n≥π/arccos⁡(1−ε/r)for an error of at most ε\begin{aligned} &\text{error} = r(1 - \cos(\pi/n)) \\ &n \ge \pi / \arccos(1 - \varepsilon/r) && \text{for an error of at most } \varepsilon \end{aligned}

So a circle of radius 100 pixels needs only enough segments to keep the error under half a pixel; a fixed n=32n = 32 is too coarse for big circles and wasteful for tiny ones.

python · try it yourself
import math

def fan_mesh(n, r=1.0):
    verts = [(0.0, 0.0)] + [(r * math.cos(2 * math.pi * k / n), r * math.sin(2 * math.pi * k / n))
                            for k in range(n)]
    tris = [(0, k + 1, (k + 1) % n + 1) for k in range(n)]
    return verts, tris

def mesh_area(verts, tris):
    total = 0.0
    for i, j, k in tris:
        (x1, y1), (x2, y2), (x3, y3) = verts[i], verts[j], verts[k]
        total += ((x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1)) / 2
    return total

verts, tris = fan_mesh(6)
print(len(verts), "vertices,", len(tris), "triangles, first:", tris[:3], "last:", tris[-1])
for n in [6, 12, 24, 48, 96]:
    v, t = fan_mesh(n)
    area = mesh_area(v, t)
    print(f"n = {n:3}: area {area:.5f}  (pi = {math.pi:.5f}, {100 * (1 - area / math.pi):.3f}% short)")

for r in [10, 100, 1000]:
    n = math.ceil(math.pi / math.acos(1 - 0.5 / r))
    print(f"radius {r:4} px -> {n} segments for at most 0.5 px error")
7 vertices, 6 triangles, first: [(0, 1, 2), (0, 2, 3), (0, 3, 4)] last: (0, 6, 1)
n =   6: area 2.59808  (pi = 3.14159, 17.301% short)
n =  12: area 3.00000  (pi = 3.14159, 4.507% short)
n =  24: area 3.10583  (pi = 3.14159, 1.138% short)
n =  48: area 3.13263  (pi = 3.14159, 0.285% short)
n =  96: area 3.13935  (pi = 3.14159, 0.071% short)
radius   10 px -> 10 segments for at most 0.5 px error
radius  100 px -> 32 segments for at most 0.5 px error
radius 1000 px -> 100 segments for at most 0.5 px error

Each fan triangle is listed counter-clockwise (centre, then rim kk, then rim k+1k + 1), so every signed area is positive. Engines rely on this winding order to tell front faces from back faces.

Tip: The area converges to πr2\pi r^2 quickly: 96 segments are 0.07% short. Choosing nn from the screen-space radius, as in the last loop, is a simple form of level of detail (LOD).

In software

  • 2D games and UI: shields, range indicators, pie charts and radial menus are generated meshes.
  • 3D modelling: cylinders, cones and spheres are built the same way, ring by ring (volume and surface area).
  • Procedural content: varying the radius per vertex with noise turns a polygon into an asteroid or an island outline (noise).

Exercises

Exercise 1: Hexagon by hand

Give the exact vertices of a regular hexagon centred at the origin with radius 2 and θ0=0\theta_0 = 0.

Answer

(2,0)(2, 0), (1,3)(1, \sqrt{3}), (−1,3)(-1, \sqrt{3}), (−2,0)(-2, 0), (−1,−3)(-1, -\sqrt{3}), (1,−3)(1, -\sqrt{3})

Solution

The angles are 0°, 60°, 120°, 180°, 240°, 300°, and cos⁡60∘=1/2\cos 60^\circ = 1/2, sin⁡60∘=3/2\sin 60^\circ = \sqrt{3}/2:

k=1:2⋅(cos⁡60∘,sin⁡60∘)=(1,3)k=2:2⋅(cos⁡120∘,sin⁡120∘)=(−1,3)k=4:2⋅(cos⁡240∘,sin⁡240∘)=(−1,−3)\begin{aligned} k = 1{:}\quad & 2 \cdot (\cos 60^\circ, \sin 60^\circ) = (1, \sqrt{3}) \\ k = 2{:}\quad & 2 \cdot (\cos 120^\circ, \sin 120^\circ) = (-1, \sqrt{3}) \\ k = 4{:}\quad & 2 \cdot (\cos 240^\circ, \sin 240^\circ) = (-1, -\sqrt{3}) \end{aligned}

and so on. Every side has length 2⋅2⋅sin⁡30∘=22 \cdot 2 \cdot \sin 30^\circ = 2.

Exercise 2: Count the triangles

A ring mesh with 40 segments and a fan mesh with 40 segments: how many vertices and triangles does each have? How many index numbers does each send to the GPU (3 per triangle)?

Answer

Fan: 41 vertices, 40 triangles, 120 indices. Ring: 80 vertices, 80 triangles, 240 indices.

Solution

Fan: centre + 40 rim vertices, one triangle per segment. Ring: 40 inner + 40 outer vertices, and each segment is a quadrilateral split into two triangles. Indices=3×triangles\text{Indices} = 3 \times \text{triangles}.

Exercise 3: Enough segments (code)

How many segments does a circle of radius 50 need for the edge error to be at most 0.1? Compute it, then print the actual error for that nn and for n−1n - 1.

Answer

n=50n = 50 (error≈0.0987\text{error} \approx 0.0987); with 49 segments the error is ≈0.1027\approx 0.1027, too large.

Solution
n≥π/arccos⁡(1−0.1/50)=π/arccos⁡(0.998)≈π/0.06326≈49.67  ⟹  n=50n \ge \pi / \arccos(1 - 0.1/50) = \pi / \arccos(0.998) \approx \pi / 0.06326 \approx 49.67 \;\Longrightarrow\; n = 50
python · try it yourself
import math
r, eps = 50, 0.1
n = math.ceil(math.pi / math.acos(1 - eps / r))
for m in (n - 1, n):
    print(m, round(r * (1 - math.cos(math.pi / m)), 4))
49 0.1027
50 0.0987

Exercise 4: Polygon area vs circle

Using area=12nr2sin⁡(2π/n)\text{area} = \frac{1}{2} n r^2 \sin(2\pi/n), find the area of a regular octagon with r=1r = 1, exactly and as a decimal. How close is it to π\pi?

Answer

22≈2.82842\sqrt{2} \approx 2.8284, about 90% of π≈3.1416\pi \approx 3.1416.

Solution
12⋅8⋅12⋅sin⁡(2π/8)=4⋅sin⁡(π/4)=4⋅2/2=22≈2.82842.8284/3.1416≈0.900\begin{aligned} &\tfrac{1}{2} \cdot 8 \cdot 1^2 \cdot \sin(2\pi/8) = 4 \cdot \sin(\pi/4) = 4 \cdot \sqrt{2}/2 = 2\sqrt{2} \approx 2.8284 \\ &2.8284 / 3.1416 \approx 0.900 \end{aligned}

Test yourself

How many triangles does a triangle-fan circle with nn rim vertices have?

  1. n−2n - 2
  2. 2n2n
  3. nn
  4. n+1n + 1

What is the angle step between consecutive vertices of a 5-pointed star outline?

  1. 72°
  2. 36°
  3. 144°
  4. 18°

Why choose the segment count from the circle's on-screen radius?

  1. Because GPUs cannot draw small circles
  2. So the edge error stays below a pixel without wasting triangles on small circles
  3. Because cos is slow for large angles
  4. Because big circles need fewer triangles