c++consolelinerasterizingapproximate

Fixing the approximations of a line rasterization algorithm


I'm currently making an header for making simple graphics in the c++ console. 2 days ago i added a function to draw lines using the rasterization algorithm used here.

But i have a problem: since the console's cartesian plane works only with integers, my function doesn't draw anithing when the numbers given if approximated are equal to 0, so i was wandering if you could do something like this:

if ( y == 0 ) 
{ 
    //fix using some kind of 'forecast' of what y could be
}

so here is my code:

void Engine::line(int ax, int ay, int bx, int by, int color)
{

    int i = 0;

    if(ax < bx)
        i = 1;
    if(ax > bx)
        i = -1;


    int dx = bx - ax;
    int dy = by - ay;

    for (int x = ax; x != bx; x+=i)
    {
        int y = ay + (by - ay) * (x - ax)/(bx - ax);

        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        SetConsoleTextAttribute(hConsole, color);

        Engine::gotoxy(x,y); printf("%c", 219);
    }
}

And here is my output, where if the line is inclined a lot it doesn't properly show: image

I really hope you can help me, but if not, can you link me a better algorithm that is still simple but that works fine with integers? (not the Bresenham's one)


Solution

  • The traditional approach is to write your algorithm 2, 4, or 8 times depending on the octant of the diagonal you want to draw. basically, when |dx| > |dy| you step by 1 in x. When |dx| < |dy| you step by 1 in y.

    As to what you have done in the loop, that looks the same as about the 6th equation on the wiki for Bresenham's, and it should be OK because you do all your multiplies before all your divide, but is doing all those multiplies and divides, which the latacode snippets avoid. You might need to factor in a half-pixel nudge.

    You might also want to look at the Wu antialias trick, which uses the float remainder to shade the 2 overlapping pixels, though how you then apply that to text mode is your problem, sorry.