A renderer supporting rasterization, transformation, Phong shading, texture.
Rasterization
Use barycentric coordinates to determine wheter a pixel is in a triangle. (x0,y0),(x1,y1),(x2,y2) are three vertexex of a triangle. w
xmin=floor(xi) xmax=ceiling(xi) ymin=floor(yi) ymax=ceiling(yi)
for y=ymin to ymax do
for x=xmin to xmax do α=f12(x,y)/f12(x0,y0) β=f20(x,y)/f20(x1,y1) γ=f01(x,y)/f01(x2,y2)
if (α>0 and β>0 and γ>0) then c=αc0+βc1+γc2
drawpixal(x, y) with color c
Here fij: f01(x,y)=(y0−y1)x+(x1−x0)y+x0y1−x1y0 f12(x,y)=(y1−y2)x+(x2−x1)y+x1y2−x2y1 f20(x,y)=(y2−y0)x+(x0−x2)y+x2y0−x0y2
Transformation
Model Space -> World Space
rotate−z(θ)=cosθsinθ00−sinθcosθ0000100001
rotate−x(θ)=10000cosθsinθ00−sinθcosθ00001
rotate−y(θ)=cosθ0−sinθ00100sinθ0cosθ00001
World Space -> Camera Space
Assume u,v,w is three base vectors in Camera Space, and the position of camera is eMcam=xuxvxw0yuyvyw0zuzvzw00001100001000010−xe−ye−ze1
w=∥g∥gu=∥t×w∥t×wv=w×v
Camera Space -> Perspective Space
Mperspective=10000100001/d1/d0001
Use fourth dimension to make perspective effect.
Perspective Space -> Screen Space
xs means the number of pixels in screen width. ys means the number of pixels in screen height
Mscreen=xs/20000−ys/20000MAXINT0xs/2ys/201