Creating a simple 3D rasterizer in pure C involves several key steps: defining a basic 3D model, applying transformations, projecting 3D coordinates to 2D space, rasterizing the projected shapes, and finally exporting the result to an image format like BMP.
Below is a straightforward implementation that renders a rotating colored cube and saves the output as a BMP image. This example focuses on clarity and simplicity, making it suitable for educational purposes.
Overview
- Vector and Matrix Operations: Basic structures and functions for 3D vectors and 4x4 matrices.
- Transformation Matrices: Functions to create rotation and projection matrices.
- Projection: Converting 3D coordinates to 2D screen space.
- Rasterization: Drawing triangles onto a pixel buffer.
- BMP Export: Saving the pixel buffer as a BMP image.
Implementation
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
// Define screen dimensions
#define WIDTH 800
#define HEIGHT 600
typedef struct {
float x, y, z, w;
} Vec4;
typedef struct {
float m[4][4];
} Mat4;
// Define a simple Vertex structure
typedef struct {
Vec4 position;
unsigned char r, g, b;
} Vertex;
// Define a Triangle
typedef struct {
Vertex v0, v1, v2;
} Triangle;
// Function to create an identity matrix
Mat4 mat4_identity() {
Mat4 mat = {0};
for(int i=0;i<4;i++) mat.m[i][i] = 1.0f;
return mat;
}
// Function to multiply two matrices
Mat4 mat4_multiply(Mat4 a, Mat4 b) {
Mat4 result = {0};
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
for(int k=0;k<4;k++) {
result.m[i][j] += a.m[i][k] * b.m[k][j];
}
}
}
return result;
}
// Function to create a rotation matrix around Y-axis
Mat4 mat4_rotate_y(float angle) {
Mat4 mat = mat4_identity();
mat.m[0][0] = cosf(angle);
mat.m[0][2] = sinf(angle);
mat.m[2][0] = -sinf(angle);
mat.m[2][2] = cosf(angle);
return mat;
}
// Function to create a perspective projection matrix
Mat4 mat4_perspective(float fov, float aspect, float znear, float zfar) {
Mat4 mat = {0};
float tanHalfFOV = tanf(fov / 2.0f);
mat.m[0][0] = 1.0f / (aspect * tanHalfFOV);
mat.m[1][1] = 1.0f / tanHalfFOV;
mat.m[2][2] = -(zfar + znear) / (zfar - znear);
mat.m[2][3] = -(2.0f * zfar * znear) / (zfar - znear);
mat.m[3][2] = -1.0f;
return mat;
}
// Function to multiply matrix with a vector
Vec4 mat4_multiply_vec4(Mat4 mat, Vec4 v) {
Vec4 result;
result.x = mat.m[0][0]*v.x + mat.m[0][1]*v.y + mat.m[0][2]*v.z + mat.m[0][3]*v.w;
result.y = mat.m[1][0]*v.x + mat.m[1][1]*v.y + mat.m[1][2]*v.z + mat.m[1][3]*v.w;
result.z = mat.m[2][0]*v.x + mat.m[2][1]*v.y + mat.m[2][2]*v.z + mat.m[2][3]*v.w;
result.w = mat.m[3][0]*v.x + mat.m[3][1]*v.y + mat.m[3][2]*v.z + mat.m[3][3]*v.w;
return result;
}
// Function to normalize a vector
void normalize(Vec4* v) {
float length = sqrtf(v->x * v->x + v->y * v->y + v->z * v->z);
if(length != 0.0f){
v->x /= length;
v->y /= length;
v->z /= length;
}
}
// Function to compute cross product
Vec4 cross(Vec4 a, Vec4 b) {
Vec4 result;
result.x = a.y * b.z - a.z * b.y;
result.y = a.z * b.x - a.x * b.z;
result.z = a.x * b.y - a.y * b.x;
result.w = 0.0f;
return result;
}
// Function to compute dot product
float dot(Vec4 a, Vec4 b) {
return a.x*b.x + a.y*b.y + a.z*b.z;
}
// Simple framebuffer
unsigned char framebuffer[WIDTH * HEIGHT * 3];
// Function to set a pixel in the framebuffer
void set_pixel(int x, int y, unsigned char r, unsigned char g, unsigned char b){
if(x <0 || x >= WIDTH || y <0 || y >= HEIGHT) return;
int index = (x + y * WIDTH) * 3;
framebuffer[index] = b;
framebuffer[index +1] = g;
framebuffer[index +2] = r;
}
// Function to draw a filled triangle (simple barycentric)
void draw_triangle(Triangle tri){
// Find bounding box
float minX = fminf(fminf(tri.v0.position.x, tri.v1.position.x), tri.v2.position.x);
float minY = fminf(fminf(tri.v0.position.y, tri.v1.position.y), tri.v2.position.y);
float maxX = fmaxf(fmaxf(tri.v0.position.x, tri.v1.position.x), tri.v2.position.x);
float maxY = fmaxf(fmaxf(tri.v0.position.y, tri.v1.position.y), tri.v2.position.y);
// Clamp to screen
int x0 = (int)fmaxf(0, floorf(minX));
int y0 = (int)fmaxf(0, floorf(minY));
int x1 = (int)fminf(WIDTH-1, ceilf(maxX));
int y1 = (int)fminf(HEIGHT-1, ceilf(maxY));
// Triangle setup
float x0f = tri.v0.position.x;
float y0f = tri.v0.position.y;
float x1f = tri.v1.position.x;
float y1f = tri.v1.position.y;
float x2f = tri.v2.position.x;
float y2f = tri.v2.position.y;
// Compute area of the triangle
float area = (x1f - x0f)*(y2f - y0f) - (x2f - x0f)*(y1f - y0f);
if(area ==0.0f) return;
// Iterate over bounding box
for(int y = y0; y <= y1; y++){
for(int x = x0; x <= x1; x++){
// Barycentric coordinates
float w1 = ((x1f - x0f)*(y - y0f) - (x - x0f)*(y1f - y0f)) / area;
float w2 = ((x2f - x1f)*(y - y1f) - (x - x1f)*(y2f - y1f)) / area;
float w3 = ((x0f - x2f)*(y - y2f) - (x - x2f)*(y0f - y2f)) / area;
if(w1 >=0 && w2 >=0 && w3 >=0){
// Interpolate color
unsigned char r = (unsigned char)(w1 * tri.v0.r + w2 * tri.v1.r + w3 * tri.v2.r);
unsigned char g = (unsigned char)(w1 * tri.v0.g + w2 * tri.v1.g + w3 * tri.v2.g);
unsigned char b = (unsigned char)(w1 * tri.v0.b + w2 * tri.v1.b + w3 * tri.v2.b);
set_pixel(x, y, r, g, b);
}
}
}
}
// Function to save framebuffer to BMP
void saveBMP(const char* filename){
FILE *f;
unsigned char bmpfileheader[14] = {
'B','M', // Signature
0,0,0,0, // Image file size in bytes
0,0, // Reserved
0,0, // Reserved
54,0,0,0 // Start of pixel array
};
unsigned char bmpinfoheader[40] = {
40,0,0,0, // Header size
0,0,0,0, // Image width
0,0,0,0, // Image height
1,0, // Planes
24,0, // Bits per pixel
0,0,0,0, // Compression
0,0,0,0, // Image size (can be 0 for uncompressed)
0,0,0,0, // X pixels per meter
0,0,0,0, // Y pixels per meter
0,0,0,0, // Total colors
0,0,0,0 // Important colors
};
int filesize = 54 + 3*WIDTH*HEIGHT;
bmpfileheader[ 2] = (unsigned char)(filesize );
bmpfileheader[ 3] = (unsigned char)(filesize>> 8);
bmpfileheader[ 4] = (unsigned char)(filesize>>16);
bmpfileheader[ 5] = (unsigned char)(filesize>>24);
bmpinfoheader[4] = (unsigned char)(WIDTH );
bmpinfoheader[5] = (unsigned char)(WIDTH>>8 );
bmpinfoheader[6] = (unsigned char)(WIDTH>>16);
bmpinfoheader[7] = (unsigned char)(WIDTH>>24);
bmpinfoheader[8] = (unsigned char)(HEIGHT );
bmpinfoheader[9] = (unsigned char)(HEIGHT>>8 );
bmpinfoheader[10] = (unsigned char)(HEIGHT>>16);
bmpinfoheader[11] = (unsigned char)(HEIGHT>>24);
f = fopen(filename,"wb");
fwrite(bmpfileheader,1,14,f);
fwrite(bmpinfoheader,1,40,f);
// BMP files are bottom to top
for(int y = HEIGHT-1; y >=0; y--){
fwrite(&framebuffer[y*WIDTH*3],3,WIDTH,f);
}
fclose(f);
}
int main(){
// Initialize framebuffer to black
memset(framebuffer, 0, sizeof(framebuffer));
// Define a cube
Vertex vertices[8] = {
// Front face
{{-1, -1, -1, 1}, 255, 0, 0}, // 0
{{ 1, -1, -1, 1}, 0, 255, 0}, // 1
{{ 1, 1, -1, 1}, 0, 0, 255}, // 2
{{-1, 1, -1, 1}, 255, 255, 0}, // 3
// Back face
{{-1, -1, 1, 1}, 255, 0, 255}, // 4
{{ 1, -1, 1, 1}, 0, 255, 255}, // 5
{{ 1, 1, 1, 1}, 255, 255, 255}, // 6
{{-1, 1, 1, 1}, 0, 0, 0} // 7
};
// Define triangles (12 triangles for 6 faces)
int indices[36] = {
// Front face
0,1,2, 0,2,3,
// Right face
1,5,6, 1,6,2,
// Back face
5,4,7, 5,7,6,
// Left face
4,0,3, 4,3,7,
// Top face
3,2,6, 3,6,7,
// Bottom face
4,5,1, 4,1,0
};
int numTriangles = 12;
Triangle triangles[numTriangles];
for(int i=0;i<numTriangles;i++){
triangles[i].v0 = vertices[indices[i*3]];
triangles[i].v1 = vertices[indices[i*3 +1]];
triangles[i].v2 = vertices[indices[i*3 +2]];
}
// Create transformation matrices
float angle = M_PI / 4; // 45 degrees
Mat4 rot = mat4_rotate_y(angle);
Mat4 proj = mat4_perspective(M_PI / 3, (float)WIDTH / HEIGHT, 0.1f, 100.0f);
Mat4 transform = mat4_multiply(rot, proj);
// Camera translation
Mat4 translate = mat4_identity();
translate.m[3][2] = -5.0f; // Move camera back
transform = mat4_multiply(transform, translate);
// Rasterize each triangle
for(int i=0;i<numTriangles;i++){
Triangle tri = triangles[i];
Vertex transformed[3];
for(int j=0;j<3;j++){
Vec4 pos = (j==0) ? tri.v0.position : (j==1) ? tri.v1.position : tri.v2.position;
Vec4 tp = mat4_multiply_vec4(transform, pos);
if(tp.w !=0){
tp.x /= tp.w;
tp.y /= tp.w;
tp.z /= tp.w;
}
// Scale to screen
transformed[j].position.x = (tp.x +1.0f) * 0.5f * WIDTH;
transformed[j].position.y = (1.0f - (tp.y +1.0f) * 0.5f) * HEIGHT;
transformed[j].position.z = tp.z;
transformed[j].r = (j==0) ? tri.v0.r : (j==1) ? tri.v1.r : tri.v2.r;
transformed[j].g = (j==0) ? tri.v0.g : (j==1) ? tri.v1.g : tri.v2.g;
transformed[j].b = (j==0) ? tri.v0.b : (j==1) ? tri.v1.b : tri.v2.b;
}
// Back-face culling
Vec4 a = transformed[1].position;
Vec4 b = transformed[2].position;
Vec4 edge1 = {a.x - transformed[0].position.x, a.y - transformed[0].position.y, a.z - transformed[0].position.z, 0};
Vec4 edge2 = {b.x - transformed[0].position.x, b.y - transformed[0].position.y, b.z - transformed[0].position.z, 0};
Vec4 normal = cross(edge1, edge2);
if(normal.z <0) continue; // Cull
// Create transformed triangle
Triangle transformedTri = {
transformed[0],
transformed[1],
transformed[2]
};
draw_triangle(transformedTri);
}
// Save to BMP
saveBMP("output.bmp");
printf("Rendered image saved to output.bmp\n");
return 0;
}
Explanation
-
Vector and Matrix Structures:
Vec4 represents a 4-dimensional vector used for homogeneous coordinates.
Mat4 represents a 4x4 matrix for transformations.
-
Matrix Operations:
mat4_identity: Creates an identity matrix.
mat4_multiply: Multiplies two 4x4 matrices.
mat4_rotate_y: Generates a rotation matrix around the Y-axis.
mat4_perspective: Creates a perspective projection matrix.
mat4_multiply_vec4: Multiplies a matrix with a vector.
-
Transformations:
- A rotation matrix is applied to rotate the cube.
- A perspective projection matrix projects 3D coordinates to 2D screen space.
- A translation matrix moves the cube away from the camera to be within the view frustum.
-
Rasterization:
- The
draw_triangle function uses a simple barycentric coordinate technique to determine if a pixel is inside a triangle and interpolates colors accordingly.
- Back-face culling is performed to avoid drawing triangles facing away from the camera.
-
BMP Export:
- The
saveBMP function writes the framebuffer to a BMP file. BMP is chosen for its simplicity in writing pixel data without compression.
-
Main Function:
- Defines the cube's vertices and faces.
- Applies transformations to the cube.
- Rasterizes each visible triangle.
- Saves the final image as
output.bmp.
Compilation and Execution
-
Save the Code: Save the above code in a file named rasterizer.c.
-
Compile:
Use GCC to compile the code. Open your terminal and navigate to the directory containing rasterizer.c, then run:
gcc rasterizer.c -o rasterizer -lm
The -lm flag links the math library required for mathematical functions like sinf, cosf, and tanf.
-
Run:
Execute the compiled program:
./rasterizer
After running, you should see a message:
Rendered image saved to output.bmp
-
View the Image:
Open output.bmp with any image viewer to see the rendered rotating cube.
Notes and Improvements
-
Depth Buffering: This implementation does not include a depth buffer, which means it might not handle overlapping triangles correctly. Implementing a Z-buffer would resolve rendering order issues.
-
Optimization: The rasterization process here is simplistic and not optimized for performance. Techniques like edge functions or scanline rasterization can be employed for efficiency.
-
Lighting and Shading: Currently, colors are interpolated per vertex. Implementing lighting calculations (like Lambertian shading) would enhance the visual appearance.
-
Multiple Views or Animations: To create animations, you can update the rotation angle in a loop and render multiple frames, saving each as separate images or combining them into a video.
-
File Formats: BMP is easy to write but not space-efficient. For more advanced applications, consider using formats like PNG or JPEG with appropriate libraries.
This example serves as a foundational step into the world of 3D graphics rendering. Exploring and extending it can provide deeper insights into how rasterizers function under the hood.