Procedural Shapes and Meshes
"Procedural" means generated by code instead of drawn by hand. With nothing more than , 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 sides has its vertices equally spaced on a circle (the circumscribed circle). Vertex sits at angle (polygons, the unit circle):
rotates the whole shape: puts a vertex straight up, which is how most icons and game pieces want a triangle or pentagon. Some useful facts:
| Quantity | Formula | Hexagon, |
|---|---|---|
| Central angle | 60° | |
| Interior angle | 120° | |
| Side length | 1 | |
| Area |
Stars
A star with points is a polygon with vertices whose radius alternates between an outer radius and an inner radius , at angle steps of . The ratio 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 .
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, vertices on the rim, and triangle joins the centre with rim vertices and (wrapping round to 0 at the end).
A ring (a donut shape, like a health-bar circle or a selection marker) needs an inner and an outer rim of vertices each and two triangles per segment: vertices and triangles.
How many segments ? The straight edge of each segment cuts inside the true circle. The largest gap, the sagitta, is in the middle of each edge:
So a circle of radius 100 pixels needs only enough segments to keep the error under half a pixel; a fixed is too coarse for big circles and wasteful for tiny ones.
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 , then rim ), so every signed area is positive. Engines rely on this winding order to tell front faces from back faces.
Tip: The area converges to quickly: 96 segments are 0.07% short. Choosing 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 .
Answer
, , , , ,
Solution
The angles are 0°, 60°, 120°, 180°, 240°, 300°, and , :
and so on. Every side has length .
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. .
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 and for .
Answer
(); with 49 segments the error is , too large.
Solution
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 , find the area of a regular octagon with , exactly and as a decimal. How close is it to ?
Answer
, about 90% of .
Solution
Test yourself
How many triangles does a triangle-fan circle with rim vertices have?
What is the angle step between consecutive vertices of a 5-pointed star outline?
- 72°
- 36°
- 144°
- 18°
Why choose the segment count from the circle's on-screen radius?
- Because GPUs cannot draw small circles
- So the edge error stays below a pixel without wasting triangles on small circles
- Because cos is slow for large angles
- Because big circles need fewer triangles