Chapter 03: Filled Triangles, Z-Buffer & Clipping

Turn hollow wireframes into solid, flat-lit 3D geometry with back-face culling, view-space near-plane polygon clipping, and a 1/z depth buffer.

Chapter:03    Duration: 1 hr 15
Files:src/raster.h, src/raster.c, src/main.c, Makefile
Concepts:1/z Z-buffer, Sutherland-Hodgman near clipping, edge functions, barycentric weights, back-face culling, Lambert flat lighting
On this page:Why 1/z? · Near-Plane Clipping · The Rasterizer · Solid Lit Cube · Build & Verify · Exercises · Recap

1. Why Store 1/z Instead of z?

Raw depth z does not vary linearly in screen space across a tilted triangle—only its reciprocal 1/z does. Storing 1/z in our ZBuffer gives us three wins at once:

2. View-Space Near-Plane Clipping

Before projecting a triangle, we transform its three corners into camera view space (MV = view * model) and clip against the plane z = 0.15f using Sutherland-Hodgman edge clipping. A triangle partially behind the camera produces either 3 vertices (one clipped triangle) or 4 vertices (a quad, which we split into a 2-triangle fan).

3. Writing src/raster.h & src/raster.c

The signed 2D edge function edge_fn(s0, s1, s2) returns twice the screen-space triangle area. If area <= 0.0f, the triangle is facing away from the camera (back-face) and gets culled immediately before touching a single pixel. Otherwise, dividing the three sub-edge weights by area yields exact barycentric coordinates (w0, w1, w2) for every pixel inside the bounding box.

src/raster.h (c)
#ifndef     RASTER_H
#define     RASTER_H

#include    "types.h"
#include    "math3d.h"

typedef struct {

    Vec3    pos;
    float   u;
    float   v;

} Vertex;

typedef struct {

    int     width;
    int     height;
    float  *inv_z;

} ZBuffer;

int     zb_init(ZBuffer *zb, int w, int h);
void    zb_free(ZBuffer *zb);
void    zb_clear(ZBuffer *zb);

void    rast_tri_flat(Framebuffer *fb,
                      ZBuffer *zb,
                      Mat4 model,
                      Mat4 view,
                      Mat4 proj,
                      Vec3 v0,
                      Vec3 v1,
                      Vec3 v2,
                      u32 base_color);

#endif
src/raster.c (c)
#include    "raster.h"
#include    <stdlib.h>

typedef struct {

    float   x;
    float   y;
    float   inv_z;

} ScreenVert;

static u32 shade_color(u32 c, float lit) {

    int     r;
    int     g;
    int     b;

    if (lit < 0.15f) { lit = 0.15f; }
    if (lit > 1.0f)  { lit = 1.0f;  }

    r = (int)((float)((c >> 16) & 0xFFu) * lit);
    g = (int)((float)((c >>  8) & 0xFFu) * lit);
    b = (int)((float)( c        & 0xFFu) * lit);

    return PACK_RGB(r, g, b);

}

static float edge_fn(float ax, float ay, float bx, float by, float cx, float cy) {

    return ((cx - ax) * (by - ay)) - ((cy - ay) * (bx - ax));

}

static int clip_near_view(const Vec3 in[3], Vec3 out[4], float znear) {

    int     count;
    int     i;
    Vec3    a;
    Vec3    b;
    int     a_in;
    int     b_in;
    float   t;

    count = 0;

    for (i = 0; i < 3; ++i) {

        a    = in[i];
        b    = in[(i + 1) % 3];
        a_in = (a.z >= znear);
        b_in = (b.z >= znear);

        if (a_in && b_in) {

            out[count++] = b;

        } else if (a_in && !b_in) {

            t            = (znear - a.z) / (b.z - a.z);
            out[count++] = v3_add(a, v3_scale(v3_sub(b, a), t));

        } else if (!a_in && b_in) {

            t            = (znear - a.z) / (b.z - a.z);
            out[count++] = v3_add(a, v3_scale(v3_sub(b, a), t));
            out[count++] = b;

        }

    }

    return count;

}

static ScreenVert project_view(Mat4 proj, Vec3 p, int w, int h) {

    Vec4        v;
    Vec4        c;
    ScreenVert  s;
    float       inv_w;

    v.x     = p.x;
    v.y     = p.y;
    v.z     = p.z;
    v.w     = 1.0f;

    c       = m4_mul_v4(proj, v);
    inv_w   = 1.0f / c.w;

    s.x     = (c.x * inv_w + 1.0f) * 0.5f * (float)w;
    s.y     = (1.0f - c.y * inv_w) * 0.5f * (float)h;
    s.inv_z = inv_w;

    return s;

}

static void draw_screen_tri(Framebuffer *fb,
                            ZBuffer *zb,
                            ScreenVert s0,
                            ScreenVert s1,
                            ScreenVert s2,
                            u32 color) {

    float   area;
    float   inv_area;
    int     min_x;
    int     max_x;
    int     min_y;
    int     max_y;
    int     x;
    int     y;

    area = edge_fn(s0.x, s0.y, s1.x, s1.y, s2.x, s2.y);

    if (area <= 0.0f) { return; }

    inv_area = 1.0f / area;

    min_x = (int)s0.x;
    if ((int)s1.x < min_x) { min_x = (int)s1.x; }
    if ((int)s2.x < min_x) { min_x = (int)s2.x; }

    max_x = (int)s0.x;
    if ((int)s1.x > max_x) { max_x = (int)s1.x; }
    if ((int)s2.x > max_x) { max_x = (int)s2.x; }

    min_y = (int)s0.y;
    if ((int)s1.y < min_y) { min_y = (int)s1.y; }
    if ((int)s2.y < min_y) { min_y = (int)s2.y; }

    max_y = (int)s0.y;
    if ((int)s1.y > max_y) { max_y = (int)s1.y; }
    if ((int)s2.y > max_y) { max_y = (int)s2.y; }

    if (min_x < 0)               { min_x = 0; }
    if (min_y < 0)               { min_y = 0; }
    if (max_x >= fb -> width)    { max_x = fb -> width  - 1; }
    if (max_y >= fb -> height)   { max_y = fb -> height - 1; }

    for (y = min_y; y <= max_y; ++y) {

        float   py  = (float)y + 0.5f;
        int     row = y * fb -> width;

        for (x = min_x; x <= max_x; ++x) {

            float   px = (float)x + 0.5f;
            float   w0 = edge_fn(s1.x, s1.y, s2.x, s2.y, px, py);
            float   w1 = edge_fn(s2.x, s2.y, s0.x, s0.y, px, py);
            float   w2 = edge_fn(s0.x, s0.y, s1.x, s1.y, px, py);

            if (w0 >= 0.0f && w1 >= 0.0f && w2 >= 0.0f) {

                float   iz;
                int     idx;

                w0  *= inv_area;
                w1  *= inv_area;
                w2  *= inv_area;
                iz   = (w0 * s0.inv_z) + (w1 * s1.inv_z) + (w2 * s2.inv_z);
                idx  = row + x;

                if (iz > zb -> inv_z[idx]) {

                    zb -> inv_z[idx]  = iz;
                    fb -> pixels[idx] = color;

                }

            }

        }

    }

}

int zb_init(ZBuffer *zb, int w, int h) {

    zb -> width  = w;
    zb -> height = h;
    zb -> inv_z  = (float *)malloc((size_t)(w * h) * sizeof(float));

    if (!zb -> inv_z) { return 0; }

    zb_clear(zb);

    return 1;

}

void zb_free(ZBuffer *zb) {

    if (zb && zb -> inv_z) {

        free(zb -> inv_z);
        zb -> inv_z = NULL;

    }

}

void zb_clear(ZBuffer *zb) {

    int     i;
    int     count;

    if (!zb || !zb -> inv_z) { return; }

    count = zb -> width * zb -> height;

    for (i = 0; i < count; ++i) { zb -> inv_z[i] = 0.0f; }

}

void rast_tri_flat(Framebuffer *fb,
                   ZBuffer *zb,
                   Mat4 model,
                   Mat4 view,
                   Mat4 proj,
                   Vec3 v0,
                   Vec3 v1,
                   Vec3 v2,
                   u32 base_color) {

    Mat4        mv;
    Vec3        vp[3];
    Vec3        clipped[4];
    Vec3        n;
    Vec3        light;
    float       lit;
    u32         col;
    int         nverts;
    int         i;
    Vec4        t;

    mv = m4_mul(view, model);

    t.x = v0.x; t.y = v0.y; t.z = v0.z; t.w = 1.0f; t = m4_mul_v4(mv, t);
    vp[0] = v3_make(t.x, t.y, t.z);

    t.x = v1.x; t.y = v1.y; t.z = v1.z; t.w = 1.0f; t = m4_mul_v4(mv, t);
    vp[1] = v3_make(t.x, t.y, t.z);

    t.x = v2.x; t.y = v2.y; t.z = v2.z; t.w = 1.0f; t = m4_mul_v4(mv, t);
    vp[2] = v3_make(t.x, t.y, t.z);

    n     = v3_norm(v3_cross(v3_sub(vp[1], vp[0]), v3_sub(vp[2], vp[0])));
    light = v3_norm(v3_make(0.35f, 0.7f, -0.6f));
    lit   = v3_dot(n, light);

    if (lit < 0.0f) { lit = -lit * 0.4f; }

    col    = shade_color(base_color, 0.25f + (lit * 0.75f));
    nverts = clip_near_view(vp, clipped, 0.15f);

    if (nverts < 3) { return; }

    for (i = 1; i + 1 < nverts; ++i) {

        ScreenVert  s0;
        ScreenVert  s1;
        ScreenVert  s2;

        s0 = project_view(proj, clipped[0],     fb -> width, fb -> height);
        s1 = project_view(proj, clipped[i],     fb -> width, fb -> height);
        s2 = project_view(proj, clipped[i + 1], fb -> width, fb -> height);

        draw_screen_tri(fb, zb, s0, s1, s2, col);

    }

}
Winding Order & Back-Face Culling
Because area <= 0.0f culls back-facing triangles, vertex winding order matters. If a face looks invisible from outside and visible from inside, swap its second and third vertex indices.

4. Wiring Up a Solid Lit Cube

Add src/raster.c to SRCS in Makefile. In src/main.c, include "raster.h", allocate a ZBuffer zb with zb_init(&zb, fb.width, fb.height) (and free it with zb_free(&zb) at shutdown), clear it every frame with zb_clear(&zb), and replace the 12 wireframe edges with 12 outward-facing triangles:

src/main.c (cube triangle table) (c)
static const int g_cube_tris[12][3] = {

    { 0, 2, 1 }, { 0, 3, 2 },
    { 5, 7, 4 }, { 5, 6, 7 },
    { 4, 3, 0 }, { 4, 7, 3 },
    { 1, 6, 5 }, { 1, 2, 6 },
    { 3, 6, 2 }, { 3, 7, 6 },
    { 4, 1, 5 }, { 4, 0, 1 }

};

Inside your frame loop, call rast_tri_flat for each of the 12 triangles using g_cube_verts[g_cube_tris[i][0..2]] and your favorite Quake-brown or steel-blue base color.

5. Build & Verify

Terminal (bash)
make run

You should see a solid, crisply shaded 3D cube spinning smoothly. Walk straight up to it with W until the camera slices through a face—it should clip smoothly against the near plane without inverting or glitching.

Exercises

Recap