Chapter 04: Perspective Textures, Fog & Bitmaps

Add Quake-style perspective-correct texture mapping, procedural brick and stone generators, a zero-dependency 24-bit .bmp loader, and atmospheric distance fog.

Chapter:04    Duration: 1 hr 30
Files:src/tex.h, src/tex.c, src/raster.h, src/raster.c, Makefile
Concepts:Perspective-correct u/z and v/z, power-of-two bitmask wrapping, BMP binary parsing, linear distance fog
On this page:Affine vs. Perspective · Textures & BMP Loader · Textured Rasterizer · Pentium Span Note · Exercises · Recap

1. Why Affine Mapping Warps (and How Quake Solves It)

If you interpolate texture coordinates u and v directly across screen pixels (affine mapping, as on the original PlayStation), floors and long hallways visibly swim and bend along triangle diagonals. Instead, we divide each vertex’s UVs by depth once per vertex: u_oz = u / z and v_oz = v / z. Those quantities do vary linearly across the screen. For every visible pixel that passes the Z-buffer test, we recover true depth z = 1.0f / iz and multiply back: u = u_oz * z, v = v_oz * z.

2. Procedural Textures & 24-Bit BMP Loader

Create src/tex.h and src/tex.c. Keeping textures at power-of-two sizes (64x64 or 128x128) lets the inner pixel loop tile seamlessly using a single bitwise AND (& (width - 1)) instead of slow modulo divisions. You can start immediately with tex_make_brick and tex_make_checker, or drop any uncompressed 24-bit .bmp from GIMP straight into your project folder.

src/tex.h (c)
#ifndef     TEX_H
#define     TEX_H

#include    "types.h"

typedef struct {

    int     width;
    int     height;
    u32    *pixels;

} Texture;

int     tex_make_brick(Texture *tex, int size);
int     tex_make_checker(Texture *tex, int size, u32 c0, u32 c1);
int     tex_load_bmp24(Texture *tex, const char *path);
void    tex_free(Texture *tex);

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

static u32 read_u32_le(const u8 *p) {

    return  ((u32)p[0])       |
            ((u32)p[1] <<  8) |
            ((u32)p[2] << 16) |
            ((u32)p[3] << 24);

}

static u16 read_u16_le(const u8 *p) {

    return (u16)(((u16)p[0]) | ((u16)p[1] << 8));

}

int tex_make_brick(Texture *tex, int size) {

    int     y;
    int     x;

    tex -> width  = size;
    tex -> height = size;
    tex -> pixels = (u32 *)malloc((size_t)(size * size) * sizeof(u32));

    if (!tex -> pixels) { return 0; }

    for (y = 0; y < size; ++y) {

        int     row_id  = y / 16;
        int     y_mod   = y % 16;
        int     offset  = (row_id & 1) ? 16 : 0;

        for (x = 0; x < size; ++x) {

            int     x_mod = (x + offset) % 32;
            int     noise = ((x * 37) ^ (y * 17)) & 15;
            u32     col;

            if (y_mod == 0 || x_mod == 0) {

                col = PACK_RGB(62 + noise, 58 + noise, 52 + noise);

            } else {

                col = PACK_RGB(128 + noise, 68 + (noise / 2), 48 + (noise / 2));

            }

            tex -> pixels[(y * size) + x] = col;

        }

    }

    return 1;

}

int tex_make_checker(Texture *tex, int size, u32 c0, u32 c1) {

    int     y;
    int     x;

    tex -> width  = size;
    tex -> height = size;
    tex -> pixels = (u32 *)malloc((size_t)(size * size) * sizeof(u32));

    if (!tex -> pixels) { return 0; }

    for (y = 0; y < size; ++y) {

        for (x = 0; x < size; ++x) {

            int     tile = ((x >> 4) ^ (y >> 4)) & 1;

            tex -> pixels[(y * size) + x] = tile ? c1 : c0;

        }

    }

    return 1;

}

int tex_load_bmp24(Texture *tex, const char *path) {

    FILE   *fp;
    u8      hdr[54];
    u32     offset;
    int     w;
    int     h;
    u16     bpp;
    int     row_bytes;
    u8     *row;
    int     y;
    int     x;

    fp = fopen(path, "rb");

    if (!fp) { return 0; }

    if (fread(hdr, 1, 54, fp) != 54) {

        fclose(fp);

        return 0;

    }

    if (hdr[0] != 'B' || hdr[1] != 'M') {

        fclose(fp);

        return 0;

    }

    offset = read_u32_le(hdr + 10);
    w      = (int)read_u32_le(hdr + 18);
    h      = (int)read_u32_le(hdr + 22);
    bpp    = read_u16_le(hdr + 28);

    if (w <= 0 || h <= 0 || bpp != 24) {

        fclose(fp);

        return 0;

    }

    tex -> width  = w;
    tex -> height = h;
    tex -> pixels = (u32 *)malloc((size_t)(w * h) * sizeof(u32));

    if (!tex -> pixels) {

        fclose(fp);

        return 0;

    }

    row_bytes = ((w * 3) + 3) & ~3;
    row       = (u8 *)malloc((size_t)row_bytes);

    if (!row) {

        free(tex -> pixels);
        tex -> pixels = NULL;
        fclose(fp);

        return 0;

    }

    fseek(fp, (long)offset, SEEK_SET);

    for (y = h - 1; y >= 0; --y) {

        if (fread(row, 1, (size_t)row_bytes, fp) != (size_t)row_bytes) { break; }

        for (x = 0; x < w; ++x) {

            u8  b = row[(x * 3) + 0];
            u8  g = row[(x * 3) + 1];
            u8  r = row[(x * 3) + 2];

            tex -> pixels[(y * w) + x] = PACK_RGB(r, g, b);

        }

    }

    free(row);
    fclose(fp);

    return 1;

}

void tex_free(Texture *tex) {

    if (tex && tex -> pixels) {

        free(tex -> pixels);
        tex -> pixels = NULL;

    }

}
Pitfall: BMP Rows Are Stored Bottom-Up & Padded
Standard Windows .bmp files store pixel rows upside down (bottom scanline first) in BGR byte order, with each row padded to a 4-byte boundary (((w * 3) + 3) & ~3). tex_load_bmp24 handles all three quirks in pure C89 without relying on struct packing pragmas.

3. Perspective-Correct Textured Triangle Rasterizer

Include "tex.h" in src/raster.h and add the prototype for rast_tri_tex:

src/raster.h (add declaration) (c)
void    rast_tri_tex(Framebuffer *fb,
                     ZBuffer *zb,
                     const Texture *tex,
                     Mat4 model,
                     Mat4 view,
                     Mat4 proj,
                     Vertex v0,
                     Vertex v1,
                     Vertex v2,
                     u32 fog_col);

Append the following textured pipeline to src/raster.c, and add src/tex.c to SRCS in Makefile. Notice that clip_near_tex interpolates u and v right alongside pos whenever a polygon crosses the near plane, and apply_light_fog blends distant walls smoothly into a dark Quake atmosphere color.

src/raster.c (append textured rasterizer) (c)
typedef struct {

    float   x;
    float   y;
    float   inv_z;
    float   u_oz;
    float   v_oz;

} TexScreenVert;

static u32 apply_light_fog(u32 px, float lit, float depth, u32 fog_col) {

    float   fog;
    float   inv_fog;
    int     r;
    int     g;
    int     b;
    int     fr;
    int     fg;
    int     fb;

    fog = (depth - 4.0f) / 18.0f;

    if (fog < 0.0f) { fog = 0.0f; }
    if (fog > 1.0f) { fog = 1.0f; }

    inv_fog = 1.0f - fog;

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

    fr = (int)((fog_col >> 16) & 0xFFu);
    fg = (int)((fog_col >>  8) & 0xFFu);
    fb = (int)( fog_col        & 0xFFu);

    r  = (int)(((float)r * inv_fog) + ((float)fr * fog));
    g  = (int)(((float)g * inv_fog) + ((float)fg * fog));
    b  = (int)(((float)b * inv_fog) + ((float)fb * fog));

    return PACK_RGB(r, g, b);

}

static int clip_near_tex(const Vertex in[3], Vertex out[4], float znear) {

    int     count;
    int     i;
    Vertex  a;
    Vertex  b;
    int     a_in;
    int     b_in;
    float   t;
    Vertex  nv;

    count = 0;

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

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

        if (a_in && b_in) {

            out[count++] = b;

        } else if (a_in && !b_in) {

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

        } else if (!a_in && b_in) {

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

        }

    }

    return count;

}

static TexScreenVert project_tex_view(Mat4 proj, Vertex vtx, int w, int h) {

    Vec4            v;
    Vec4            c;
    TexScreenVert   s;
    float           inv_w;

    v.x     = vtx.pos.x;
    v.y     = vtx.pos.y;
    v.z     = vtx.pos.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;
    s.u_oz  = vtx.u * inv_w;
    s.v_oz  = vtx.v * inv_w;

    return s;

}

void rast_tri_tex(Framebuffer *fb,
                  ZBuffer *zb,
                  const Texture *tex,
                  Mat4 model,
                  Mat4 view,
                  Mat4 proj,
                  Vertex v0,
                  Vertex v1,
                  Vertex v2,
                  u32 fog_col) {

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

    if (!tex || !tex -> pixels) { return; }

    mv = m4_mul(view, model);

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

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

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

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

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

    nverts = clip_near_tex(vp, clipped, 0.15f);

    if (nverts < 3) { return; }

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

        TexScreenVert   s0;
        TexScreenVert   s1;
        TexScreenVert   s2;
        float           area;
        float           inv_area;
        int             min_x;
        int             max_x;
        int             min_y;
        int             max_y;
        int             x;
        int             y;

        s0   = project_tex_view(proj, clipped[0],     fb -> width, fb -> height);
        s1   = project_tex_view(proj, clipped[i],     fb -> width, fb -> height);
        s2   = project_tex_view(proj, clipped[i + 1], fb -> width, fb -> height);
        area = edge_fn(s0.x, s0.y, s1.x, s1.y, s2.x, s2.y);

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

        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]) {

                        float   z  = 1.0f / iz;
                        float   u  = ((w0 * s0.u_oz) + (w1 * s1.u_oz) + (w2 * s2.u_oz)) * z;
                        float   v  = ((w0 * s0.v_oz) + (w1 * s1.v_oz) + (w2 * s2.v_oz)) * z;
                        int     tx = ((int)(u * (float)tex -> width))  & (tex -> width  - 1);
                        int     ty = ((int)(v * (float)tex -> height)) & (tex -> height - 1);
                        u32     raw;

                        raw               = tex -> pixels[(ty * tex -> width) + tx];
                        zb -> inv_z[idx]  = iz;
                        fb -> pixels[idx] = apply_light_fog(raw, lit, z, fog_col);

                    }

                }

            }

        }

    }

}

4. Performance Note for Retro Hardware

On any CPU made after ~2005, doing one 1.0f / iz divide per visible pixel at 320x240 runs effortlessly at hundreds of FPS. If you test on a genuine 1998 Pentium II or 486, remember John Carmack’s classic Quake trick: switch the inner loop to horizontal scanline spans and compute 1.0f / iz only once every 16 pixels, interpolating linearly in between. Visual distortion stays invisible while division cost drops by 16x.

Exercises

Recap