# Trying to understand bresenhams line algorithm

Well, i tried to read the line.h file so i can understand it myself, but to me it looks like unmaintainable code. I have noticed when programming (c++) that everything has some logic, like its not how you would do it in common sense; like you don’t type loop(100) to loop, you do it some other way like `for (int i; i<100; ++i)`. I just wanna understand how the line algorithm works.
When i googled the algorithm, it usually describes it as “draw a line from x to y”, which is what the line does of course.
But in cataclysm the line is used in the vehicle.h file, it somehow makes the line have things in it, like on the line it has a frame, seat, wheel, etc (but I’m not sure if it works that way :S).
How i think how it works is by using a vector and somehow merging the algorithm into it, and the vector will be later defined as how many elements it will have, and the elements will be defined as a frame, wheel, seat, etc.

I’m not sure exactly what your question is. You’re right about line::line_to(), it calculates the coordinates of the cells the line touches, and then returns them in a vector, which the caller can easily iterate over.
As for how bresenham works, it determines the “dominant” direction the line is being drawn in, and calculates the fractional “lateral” per-cell movement. With each iteration it advances along the major coordinate axis by one cell, and updates the fractional lateral coordinate by the precalculated amount, when the fractional component exceeds 1, it increments the actual lateral coordinate and decrements the fractional lateral coordinate correspondingly. The fractional component is handled with integer math for performance reasons.

so many big words, share some brains please.

It picks an angle and then iterates outwards, moving 1 square in the main direction while tracking how far over in the secondary direction it’s moved. When the secondary direction move counter goes over one then it shifts one square in the secondary direction, subtracts 1 from the counter, and keeps going. It then converts each square that it touches into co-ordinates and saves them in the vector form, which can be used elsewhere.

A side-issue about how line_to() returns a vector of coordinates, there are a few places in the code that have another copy of the bresenham algorithm, and they do whatever work they’re tasked with inline instead of building and returning a vector.

Does the game use Bresenham’s for raycasting stuff like vision and shooting?

All kinds of stuff, LOS, firing lines, “pathing”, lighting, I think it’s even used for rotating vehicles.