Project 2: A comptime-Powered Vector Library

A generic vector math library (Vec<N, T>) where N (dimensions) and T (element type) are compile-time parameters.

Quick Reference

Attribute Value
Primary Language Zig
Alternative Languages C++, Rust
Difficulty Level 2: Intermediate
Time Estimate 1-2 weeks
Knowledge Area Metaprogramming / Linear Algebra
Tooling A 2D/3D math library
Prerequisites Basic familiarity with structs and functions.

What You Will Build

A generic vector math library (Vec<N, T>) where N (dimensions) and T (element type) are compile-time parameters.

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • Creating a generic Vec type → maps to writing a function that returns a struct type at comptime
  • Implementing generic functions (dot, cross etc.) → maps to using comptime loops and conditional logic
  • Accessing components via .x, .y, .z → maps to using @fieldParentPtr and comptime to generate fields
  • Operator overloading → maps to implementing add, mul functions in the struct

Key Concepts

  • Generic Data Structures: Zig Documentation on comptime
  • Type Functions: zig.news - “What is a Type?”
  • Vector Math: “3D Math Primer for Graphics and Game Development” by Fletcher Dunn

Real-World Outcome

// Your code
const Vec2f = Vec(2, f32);
const Vec3i = Vec(3, i32);

var v1 = Vec2f{.x = 1.0, .y = 2.0};
var v2 = Vec2f{.x = 3.0, .y = 4.0};
var v3 = v1.add(v2); // {.x = 4.0, .y = 6.0}

var cross_prod = Vec3i{1,0,0}.cross(Vec3i{0,1,0}); // {0,0,1}

// This would be a compile error:
// var error = v1.add(cross_prod);

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References