Here's a basic implementation of a 3D rasterizer with depth buffering in Python using just basic math operations (no OpenGL or other graphics libraries).
Core Components
1. Data Structures
python
class Vec3:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Triangle:
def __init__(self, v0, v1, v2):
self.vertices = [v0, v1, v2]
2. Projection and Transformation
python
def project_point(point, width, height, fov, distance):
# Perspective projection
factor = fov / (distance + point.z)
x = point.x * factor + width / 2
y = -point.y * factor + height / 2 # Flip y-axis for screen coordinates
return x, y, point.z # Return z for depth testing
3. Rasterization with Depth Buffer
python
def rasterize_triangle(triangle, width, height, fov, distance, pixels, depth_buffer):
# Project vertices to screen space
projected = [project_point(v, width, height, fov, distance) for v in triangle.vertices]
# Get bounding box
min_x = min(p[0] for p in projected)
max_x = max(p[0] for p in projected)
min_y = min(p[1] for p in projected)
max_y = max(p[1] for p in projected)
# Clamp to screen bounds
min_x = max(0, int(min_x))
max_x = min(width - 1, int(max_x))
min_y = max(0, int(min_y))
max_y = min(height - 1, int(max_y))
# Get triangle edges
p0, p1, p2 = projected
# Rasterize
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
# Barycentric coordinate check
denom = (p1[1] - p2[1]) * (p0[0] - p2[0]) + (p2[0] - p1[0]) * (p0[1] - p2[1])
if denom == 0:
continue
# Calculate weights
w0 = ((p1[1] - p2[1]) * (x - p2[0]) + (p2[0] - p1[0]) * (y - p2[1])) / denom
w1 = ((p2[1] - p0[1]) * (x - p2[0]) + (p0[0] - p2[0]) * (y - p2[1])) / denom
w2 = 1 - w0 - w1
# Check if point is inside triangle
if w0 >= 0 and w1 >= 0 and w2 >= 0:
# Interpolate z for depth
z = w0 * p0[2] + w1 * p1[2] + w2 * p2[2]
# Depth test
if z < depth_buffer[y][x]:
depth_buffer[y][x] = z
pixels[y][x] = (255, 255, 255) # White color
4. Main Rendering Loop
python
def render(width, height, triangles):
# Initialize pixel buffer and depth buffer
pixels = [[(0, 0, 0) for _ in range(width)] for _ in range(height)]
depth_buffer = [[float('inf')] * width for _ in range(height)]
# Camera parameters
fov = 500
distance = 5
# Rasterize each triangle
for tri in triangles:
rasterize_triangle(tri, width, height, fov, distance, pixels, depth_buffer)
return pixels
Example Usage
python
# Create a simple cube (12 triangles)
def create_cube():
# Define 8 vertices
vertices = [
Vec3(-1, -1, -1), Vec3(1, -1, -1), Vec3(1, 1, -1), Vec3(-1, 1, -1),
Vec3(-1, -1, 1), Vec3(1, -1, 1), Vec3(1, 1, 1), Vec3(-1, 1, 1)
]
# Define 12 triangles (2 per face)
triangles = [
# Front face
Triangle(vertices[0], vertices[1], vertices[2]),
Triangle(vertices[0], vertices[2], vertices[3]),
# Back face
Triangle(vertices[4], vertices[6], vertices[5]),
Triangle(vertices[4], vertices[7], vertices[6]),
# Left face
Triangle(vertices[0], vertices[3], vertices[7]),
Triangle(vertices[0], vertices[7], vertices[4]),
# Right face
Triangle(vertices[1], vertices[5], vertices[6]),
Triangle(vertices[1], vertices[6], vertices[2]),
# Top face
Triangle(vertices[3], vertices[2], vertices[6]),
Triangle(vertices[3], vertices[6], vertices[7]),
# Bottom face
Triangle(vertices[0], vertices[4], vertices[5]),
Triangle(vertices[0], vertices[5], vertices[1])
]
return triangles
# Render and display (using PIL for image display)
def display_pixels(pixels):
from PIL import Image
img = Image.new('RGB', (len(pixels[0]), len(pixels)))
img.putdata([pixel for row in pixels for pixel in row])
img.show()
# Main execution
if __name__ == "__main__":
width, height = 800, 600
cube = create_cube()
pixels = render(width, height, cube)
display_pixels(pixels)
Key Concepts Explained
Depth Buffer: A 2D array that stores the depth (z-value) of the closest object at each pixel. New fragments are only drawn if they're closer than what's already in the buffer.
Perspective Projection: Converts 3D points to 2D screen coordinates while maintaining perspective.
Barycentric Coordinates: Used to determine if a pixel is inside a triangle and to interpolate values (like depth) across the triangle.
Rasterization Process:
Project vertices to screen space
Find bounding box
Test each pixel in the bounding box
Use depth buffer to handle occlusion
This is a very basic implementation. A production-quality rasterizer would include: