The bulk of rasterization is done with line drawing algorithms.
Remember, this is filling an width by height array.
Integer indexes please
We have two endpoints
And an operation WritePixel(ix,iy,value)
WebGL assumes that pixels are centered 1/2 way between the coordinates.
A pixel at (0,0) is actually drawn at (1/2,1/2)
There are implications for edges, and especially for antialiasing.
But for now, just go with square pixels, integer indexes.
Bresenham's line algorithm
This is the algorithm graphics cards use
Invented in 1962 by Jack Bressenham
Published in 63
Big Ideas
Do all integer calculations
"predict" an integer error for the axis of minor change
Change y when this error becomes too large.
WLOG assume $0 \le m \le 1 $
You can flip the role of x and y if this is not the case.
Given (x1,y1) and (x2, y2)
$$
\begin{array}{rcl}
y & =& mx + b \\
& = & \frac{\Delta y}{\Delta x} \cdot x + b \\
\Delta x \cdot y & = & \Delta y \cdot x + \Delta x \cdot b \\
0 & = & \Delta y \cdot x - \Delta x \cdot y + \Delta x\cdot b \\
\end{array}
$$
And also, if a point is not on the line if it is above or below the line.
(2,4) is above the line 2-3×4+6 = -4 < 0
(2,1) is below the line 2-3×1+6 = 5 > 0
Assume we are drawing a line from $(x_1,y_1)$ to $(x_2,y_2)$.
We know that$ F(x_1,y_1)$ is on the line.
The next point will be $F(x_1+1, y_1)$ or $F(x_1+1, y_1+1)$, we just need to decide which.
Remember, the slope is less than one, so the next x will just be to add one.
Determine this by evaluating $F(x_1+1, y_1+1/2)$
If $F(x_1+1, y_1+1/2)$ is positive, the line is above it, select $(x_1+1, y_1+1)$
If $F(x_1+1, y_1+1/2)$ is negative, the line is below it, select $(x_1+1, y_1)$
Notice, this involves one point computation, and one difference computation, not two.
Define $D = F(x_1+1, y_1+1/2) - F(x_1,y_1)$
This tells us how much the error changes from the current point to the predictor for the next point.
$$
\begin{array}{rcl}
D &=& F(x_1+1, y_1+1/2) -F(x_1,y_1) \\
&=& A(x_1+1) + B(y_1+1/2) + C - (Ax_1 +By_1+C) \\
&=& Ax_1 - Ax_1 + A + By_1 - By_1 + 1/2B +C-C \\
&=& A + 1/2 B \\
\end{array} $$
D will give us the same indication as before.
Since $(x_1,y_1)$ is on the line, $F(x_1, y_1) = 0 $
So we initialize D to be 0
The starting point has no error
The first point will be off by $A + 1/2 B$ or $ (\Delta y-1/2\Delta x) $
For our example line (y = 1/3 x + 2) starting at (0,2)
A = 1, B = -3, C = 6
(0,2) is on the line.
F(1,2.5) = 1 - 3×2.5 + 6 = 1 - 7.5 + 6 = -0.5
This is negative, so it is above the line, so the point is (1,2)