o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Implement a very simple rasterizer in pure C code.
- User
Implement a very simple rasterizer in pure C code.
- Assistant
Implement a very simple rasterizer in pure C code.
Creating a simple rasterizer in pure C involves several steps:
Below is a complete C program that demonstrates a very basic rasterizer. It renders a single colored triangle and saves the result as a BMP image.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
// Define the image dimensions
#define WIDTH 800
#define HEIGHT 600
// Define a simple RGB color structure
typedef struct {
uint8_t r, g, b;
} Color;
// Define a vertex structure
typedef struct {
float x, y; // Screen coordinates
Color color;
} Vertex;
// Framebuffer to store pixel colors
Color framebuffer[HEIGHT][WIDTH];
// Function to set a pixel in the framebuffer
void set_pixel(int x, int y, Color color) {
// Clamp coordinates to the framebuffer
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
return;
framebuffer[y][x] = color;
}
// Function to write the framebuffer to a BMP file
int write_bitmap(const char *filename) {
FILE *f;
uint8_t 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
};
uint8_t 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 = none)
0,0,0,0, // Image size (can be 0 for no compression)
0x13,0x0B,0,0, // Horizontal resolution (2835 pixels/meter)
0x13,0x0B,0,0, // Vertical resolution (2835 pixels/meter)
0,0,0,0, // Colors in color table
0,0,0,0 // Important color count
};
int filesize = 54 + 3*WIDTH*HEIGHT;
// File size
bmpfileheader[2] = (uint8_t)(filesize );
bmpfileheader[3] = (uint8_t)(filesize >> 8);
bmpfileheader[4] = (uint8_t)(filesize >> 16);
bmpfileheader[5] = (uint8_t)(filesize >> 24);
// Image width
bmpinfoheader[4] = (uint8_t)(WIDTH );
bmpinfoheader[5] = (uint8_t)(WIDTH >> 8 );
bmpinfoheader[6] = (uint8_t)(WIDTH >> 16);
bmpinfoheader[7] = (uint8_t)(WIDTH >> 24);
// Image height
bmpinfoheader[8] = (uint8_t)(HEIGHT );
bmpinfoheader[9] = (uint8_t)(HEIGHT >> 8 );
bmpinfoheader[10] = (uint8_t)(HEIGHT >> 16);
bmpinfoheader[11] = (uint8_t)(HEIGHT >> 24);
f = fopen(filename, "wb");
if (!f) {
perror("Unable to open file for writing");
return -1;
}
// Write headers
fwrite(bmpfileheader, 1, 14, f);
fwrite(bmpinfoheader, 1, 40, f);
// Write pixel data (BMP uses little endian and BGR format)
uint8_t padding[3] = {0, 0, 0};
int padding_size = (4 - (WIDTH * 3) % 4) % 4;
for(int y = HEIGHT-1; y >=0; y--){
for(int x = 0; x < WIDTH; x++){
uint8_t pixel[3];
pixel[0] = framebuffer[y][x].b;
pixel[1] = framebuffer[y][x].g;
pixel[2] = framebuffer[y][x].r;
fwrite(pixel, 1, 3, f);
}
fwrite(padding, 1, padding_size, f);
}
fclose(f);
return 0;
}
// Function to compute barycentric coordinates
void compute_barycentric(float x, float y, Vertex v0, Vertex v1, Vertex v2, float *u, float *v, float *w) {
float denom = (v1.y - v2.y)*(v0.x - v2.x) + (v2.x - v1.x)*(v0.y - v2.y);
*u = ((v1.y - v2.y)*(x - v2.x) + (v2.x - v1.x)*(y - v2.y)) / denom;
*v = ((v2.y - v0.y)*(x - v2.x) + (v0.x - v2.x)*(y - v2.y)) / denom;
*w = 1.0f - (*u) - (*v);
}
// Function to rasterize a single triangle
void rasterize_triangle(Vertex v0, Vertex v1, Vertex v2) {
// Find bounding box
int minX = (int)(v0.x < v1.x ? (v0.x < v2.x ? v0.x : v2.x) : (v1.x < v2.x ? v1.x : v2.x));
int maxX = (int)(v0.x > v1.x ? (v0.x > v2.x ? v0.x : v2.x) : (v1.x > v2.x ? v1.x : v2.x));
int minY = (int)(v0.y < v1.y ? (v0.y < v2.y ? v0.y : v2.y) : (v1.y < v2.y ? v1.y : v2.y));
int maxY = (int)(v0.y > v1.y ? (v0.y > v2.y ? v0.y : v2.y) : (v1.y > v2.y ? v1.y : v2.y));
// Clamp to framebuffer
if(minX < 0) minX = 0;
if(maxX >= WIDTH) maxX = WIDTH-1;
if(minY < 0) minY = 0;
if(maxY >= HEIGHT) maxY = HEIGHT-1;
// Iterate over the bounding box
for(int y = minY; y <= maxY; y++) {
for(int x = minX; x <= maxX; x++) {
float u, v, w;
compute_barycentric((float)x + 0.5f, (float)y + 0.5f, v0, v1, v2, &u, &v, &w);
// If the point is inside the triangle or on the edge
if(u >= 0 && v >= 0 && w >= 0) {
// Simple color interpolation
Color color;
color.r = (uint8_t)(u * v0.color.r + v * v1.color.r + w * v2.color.r);
color.g = (uint8_t)(u * v0.color.g + v * v1.color.g + w * v2.color.g);
color.b = (uint8_t)(u * v0.color.b + v * v1.color.b + w * v2.color.b);
set_pixel(x, y, color);
}
}
}
}
int main() {
// Initialize framebuffer to white
Color white = {255, 255, 255};
for(int y = 0; y < HEIGHT; y++) {
for(int x = 0; x < WIDTH; x++) {
framebuffer[y][x] = white;
}
}
// Define a triangle in screen space with colors
Vertex v0 = {400.0f, 100.0f, (Color){255, 0, 0}}; // Top vertex (Red)
Vertex v1 = {100.0f, 500.0f, (Color){0, 255, 0}}; // Bottom-left vertex (Green)
Vertex v2 = {700.0f, 500.0f, (Color){0, 0, 255}}; // Bottom-right vertex (Blue)
// Rasterize the triangle
rasterize_triangle(v0, v1, v2);
// Write the framebuffer to a BMP file
if(write_bitmap("output.bmp") == 0){
printf("Rasterization complete. Image saved as output.bmp\n");
}
else{
printf("Failed to write image.\n");
}
return 0;
}
Structures:
Color: Holds RGB values for each pixel.Vertex: Represents a point in screen space with an associated color.Framebuffer:
framebuffer of size HEIGHT x WIDTH stores the color of each pixel.Setting a Pixel:
set_pixel function assigns a color to a specific (x, y) coordinate in the framebuffer, ensuring the coordinates are within bounds.Writing BMP File:
write_bitmap function creates a BMP file. BMP format is chosen for its simplicity.Barycentric Coordinates:
compute_barycentric function calculates the barycentric coordinates (u, v, w) for a point (x, y) relative to the triangle defined by vertices v0, v1, and v2.Rasterizing the Triangle:
rasterize_triangle function first computes the bounding box of the triangle to limit the area of pixel checks.Main Function:
rasterize_triangle to fill in the triangle.output.bmp.Save the Code:
simple_rasterizer.c.Compile the Code:
gcc. Open your terminal and run:
gcc simple_rasterizer.c -o rasterizer
Run the Program:
./rasterizer
Rasterization complete. Image saved as output.bmp
View the Image:
output.bmp with any image viewer. You should see a white background with a colorful triangle.This basic rasterizer can be extended in numerous ways:
main function to rasterize multiple triangles.This example serves as a foundational understanding of rasterization in computer graphics. From here, you can explore more sophisticated algorithms and optimizations used in modern graphics pipelines.