-
Notifications
You must be signed in to change notification settings - Fork 0
/
raster-01-lines.cpp
82 lines (67 loc) · 1.99 KB
/
raster-01-lines.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Raster 01
=========
Implements a simpler rasterization program for lines. This is the initial, buggy
line drawing algorithm.
```bash
g++ raster-01-lines.cpp -o main.out -std=c++20 -Ofast
./main.out
open output.bmp
```
Implementation for https://gabrielgambetta.com/computer-graphics-from-scratch/demos/raster-01.html
*/
#include "bmp.h"
typedef std::array<float, 3> float3;
typedef std::array<uint8_t, 3> rgb;
const int32_t WIDTH = 600;
const int32_t HEIGHT = 600;
// Canvas
bool PutPixel(
uint8_t data[WIDTH * HEIGHT][3],
int32_t x,
int32_t y,
const rgb color
) {
// Translate [-W/2, W/2] into [0, W]. Ditto for H
x = WIDTH / 2 + x;
y = HEIGHT / 2 - y - 1;
// Checks that the pixel is in bound
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) {
std::cerr << "Error: Attempted to write out-of-bounds pixel (" << x << ", " << y << ")." << std::endl;
return false;
}
// Write into data, which is a flattened array where width * height in 1d
int32_t offset = y * WIDTH + x;
data[offset][0] = color[0];
data[offset][1] = color[1];
data[offset][2] = color[2];
return true;
}
void Clear(uint8_t data[][3]) {
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
for (int i = 0; i < 3; i++) {
data[y * WIDTH + x][i] = 255;
}
}
}
}
// Rasterization code
void DrawLineBroken(uint8_t data[][3], int x0, int y0, int x1, int y1, rgb color) {
float a = ((float) y1 - y0) / (x1 - x0);
float y = y0;
for (int x = x0; x <= x1; x++) {
PutPixel(data, x, (int) std::round(y), color);
y += a;
}
}
int main() {
uint8_t data[WIDTH * HEIGHT][3];
Clear(data);
DrawLineBroken(data, -200, -100, 240, 120, {0, 0, 0});
DrawLineBroken(data, -50, -200, 60, 240, {0, 0, 0});
if (std::getenv("OUT") && write_bmp_file("output.bmp", data, WIDTH, HEIGHT)) {
std::cout << "Image written successfully." << std::endl;
}
return 0;
}