On Sunday, 6 November 2022 at 17:15:03 UTC, rikki cattermole wrote:
On 07/11/2022 5:48 AM, Joel wrote:
The algorithm is too hard for me to work out and dg2d doesn't help either. I want my code fixed up so that works from any two points.

Its not as complex as that page initially looks.

```
plotLine(x0, y0, x1, y1)
    dx = abs(x1 - x0)
    sx = x0 < x1 ? 1 : -1
    dy = -abs(y1 - y0)
    sy = y0 < y1 ? 1 : -1
    error = dx + dy

    while true
        plot(x0, y0)
        if x0 == x1 && y0 == y1 break
        e2 = 2 * error
        if e2 >= dy
            if x0 == x1 break
            error = error + dy
            x0 = x0 + sx
        end if
        if e2 <= dx
            if y0 == y1 break
            error = error + dx
            y0 = y0 + sy
        end if
    end while
```

That is the pseudo code you want.

Its just a matter of typing the variables to something like int.

I can recommend:

https://www.amazon.com/Computer-Graphics-Principles-Practice-3rd/dp/0321399528

and

https://www.amazon.com/Computer-Graphics-C-Version-2nd/dp/0135309247

(The updated version should be fine too)

If you wish to understand it.

Ok, this is working:

```d
        void drawLine(Dot s, Dot e) {
                Dot d=s;
                int x0=s.pos.Xi, y0=s.pos.Yi;
                int x1=e.pos.Xi, y1=e.pos.Yi;

                int dx = abs(x1 - x0);
                int sx = x0 < x1 ? 1 : -1;
                int dy = -abs(y1 - y0);
                int sy = y0 < y1 ? 1 : -1;
                int error = dx + dy;

                while(true) {
                        d.setPos(Point(x0,y0));
                        drawDot(d);
                        if (x0 == x1 && y0 == y1)
                                break;
                        int e2 = 2 * error;
                        if (e2 >= dy) {
                                if (x0 == x1) break;
                                error = error + dy;
                                x0 = x0 + sx;
                        }
                        if (e2 <= dx) {
                                if (y0 == y1) break;
                                error = error + dx;
                                y0 = y0 + sy;
                        }
                }
        }
//[...]
void mouseDraw(ref Dot d) {
        int lmx=g_mx, lmy=g_my, mx,my;
        int mstate = SDL_GetMouseState(&mx,&my);
        if (mstate & SDL_BUTTON_LEFT) {
                if (mx>0 && my>0) {
                        g_mx=mx/3;
                        g_my=my/3;
                        auto s=d, e=d;
                        s.setPos(Point(lmx, lmy));
                        e.setPos(Point(g_mx, g_my));
                        //mixin(tce("lmx lmy g_mx g_my".split));
                        g_df.drawLine(s,e);
                }
        } else {
                if (mx>0 && my>0) {
                        g_mx=mx/3;
                        g_my=my/3;
                }
        }
}
```

Reply via email to