1
$\begingroup$

I'm getting started with graphics and I'm having trouble implementing the Bresenham's algorithm. Now, I know that my implementation is incomplente, but I can't see why it doesn't make horizontal lines(same height(y) values, different width(x values). I get a floating point exception. Here's the algo:

int draw_line(void *mlx_ptr, void*win_ptr, t_2dpoint *initial_p, t_2dpoint *final_p)
{
 53     int delta_x;

 53     int delta_x;
 54     int y;
 55     int delta_y;
 56
 57     delta_x = final_p->x - initial_p->x;
 58     delta_y = final_p->y - initial_p->y;
 59
 60     x = initial_p->x;
 61     y = initial_p->y;
 62     e = (float)(delta_x / delta_y) - 1.0;
 63
 64     while(x < final_p->x - 1)
 65     {
 66         mlx_pixel_put(mlx_ptr, win_ptr, x, y, 0XFF00FF);
 67         if ( e >= 0)
 68         {
 69             y += 1;
 70             e -= 1.0;
 71         }
 72         x += 1;
 73         e += (float)delta_x / delta_y;
 74     }
 75     mlx_pixel_put(mlx_ptr, win_ptr, x, y, 0XFF00FF);
 76 }
$\endgroup$

1 Answer 1

2
$\begingroup$
e = (float)(delta_x / delta_y) - 1.0;

e += (float)delta_x / delta_y;

Either of these lines will cause a divide-by-zero error when delta_y is zero, which is when the line is horizontal (or zero-length). You need to check for this condition and have some special-case code.

As an aside, I don't know why people still teach Bresenham's algorithm to new CG students. It's a good example of an algorithm but it's not very useful knowledge in itself: you're unlikely to need to know it unless it's for a job interview.

$\endgroup$
4
  • $\begingroup$ The underlying principle of Bresenham (the error value getting accumulated and moved back to 0 as events happen) is nice but no-one seems to teach it $\endgroup$ Aug 7, 2018 at 14:58
  • $\begingroup$ Yep, that fixes the floating point exception, now I just need to find the math logic. What algorithm you'd recommend? $\endgroup$
    – koperandus
    Aug 8, 2018 at 16:38
  • 2
    $\begingroup$ Well, if you want to draw lines one pixel at a time, Bresenham's algorithm is the right one. But why do you want to draw lines one pixel at a time? Any OpenGL implementation will draw them all at once for you. $\endgroup$
    – Dan Hulme
    Aug 8, 2018 at 17:04
  • $\begingroup$ @DanHulme Sometimes it's useful to know a little history.... even if it's only to give you a greater appreciation of the present ;-) $\endgroup$
    – Simon F
    Sep 7, 2018 at 8:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.