I created a function which takes in a 2D std::vector
, 2 points in the vector, and "draws" a line within the vector. But, it doesn't cover all the cases (octants). By a line I mean the points connected to each other in a straight line. This vector will be written to a .ppm
file, so it appears as a line in the image.
I implemented this function using this link: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
Looking here: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm#All_cases
I tried to figure out how to change my function so it "draws" a line for any 2 coordinates in the 2D vector, but I'm a little confused. I don't understand why there is a function to apply on the input and output. And which one to apply on which coordinate. Also, I don't know how to figure out which octant the line from the 2 coordinates is in.
The 2D vector will be written to the .ppm
file like this:
255 255 255 255 255 255 255 255 255
255 255 255 0 0 0 255 255 255
255 255 255 255 255 255 255 255 255
This image would be a black dot in the center.
#include <vector>
#include <tuple>
#include <utility>
using pixel = std::tuple<unsigned, unsigned, unsigned>; // rgb pixel
using row_t = std::vector<pixel>; // row in a 2D vector
using grid_t = std::vector<row_t>; // the grid made up of rows
// x, y coordinate - access is like grid[y][x] since grid is made of rows
using coord = std::pair<long long, long long>;
// Bresenham's line algorithm
// 2 points to draw a line between
void draw(grid_t& grid, const coord& c1, const coord& c2)
{
long long dx{c2.first - c1.first},
dy{c2.second - c1.second},
D {2 * dy - dx},
y {c1.second};
// is the if/else needed?
if (c1.first <= c2.first)
for (long long x{c1.first}; x <= c2.first; ++x)
{
grid[y][x] = pixel{0, 0, 0};
if (D > 0)
{
++y;
D -= 2 * dx;
}
D += 2 * dy;
}
else
for (long long x{c1.first}; x >= c2.first; --x)
{
grid[y][x] = pixel{0, 0, 0};
if (D > 0)
{
++y;
D -= 2 * dx;
}
D += 2 * dy;
}
}
Any help in making this function work for all the cases (and how to make it better) and helping me understand how would be appreciated.