The goal for today is to create wireframe renders. To achieve this, we first need to learn how to draw line segments on the screen. I provide my students with the following code:

Starting point

The code below generates a 64x64 image named 010.ppm .

scaled-up version

scaled-up version

*magick result.ppm -scale 400% result.png*

We create a simple ppm module → https://github.com/qiekn/tinyrenderer-jai/blob/206fae7da681037b4a95c87962bcedb4620cfd37/modules/ppm.jai

//
// make_image :: (width: int, height: int) -> PPM_Image
// make_image :: (width: int, height: int, background_color: Vector4) -> PPM_Image
//
// clear      :: (image: *PPM_Image, color: Vector4)
//
// set_pixel  :: (image: *PPM_Image, x: int, y: int, color: Vector4)
//
// write_p3   :: (filename: string, image: *PPM_Image)
// write_p6   :: (filename: string, image: *PPM_Image)
//

image.png

First attempt

下面尝试使用参数方程绘制线段,我们这里把参数 t 分 50 步,从 0 走到 1,点沿直线移动,总共 51 个像素点。

<aside>

$$ 参数式: \begin{cases} x(t) = a_x + t \cdot (b_x - a_x) \\ y(t) = a_y + t \cdot (b_y - a_y) \end{cases}, t \in [0, 1] $$

</aside>

$t = 0 \Rightarrow A(a_x, a_y), \quad t = 1 \Rightarrow B(b_x, b_y)$

image.png

bresenham1.png

注意到的问题

  1. 我们先绘制了黄色 CA,然后绘制了红色 AC,可以看到黄色,说明同一条线段顺序不同,像素不一致,这不是我们期望的
  2. 中间有短缺,因为我们最多 51 个像素

Second attempt