From b1f6c2b60fd54e19c21f5cc81e3b47ca18d8f703 Mon Sep 17 00:00:00 2001 From: rodri Date: Thu, 9 Nov 2023 11:22:35 +0000 Subject: =?UTF-8?q?Lesson=200:=20Bresenham's=20Line=20Drawing=20Algorithm?= =?UTF-8?q?=E2=80=94Third=20attempt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.c | 48 +++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 9 deletions(-) (limited to 'main.c') diff --git a/main.c b/main.c index 0cd9e9a..d6a11cd 100644 --- a/main.c +++ b/main.c @@ -6,7 +6,7 @@ #include #include #include -#include "libgeometry/geometry.h" +#include Memimage *fb; @@ -90,20 +90,48 @@ pixel(Memimage *dst, Point p, Memimage *src) memimagedraw(dst, r, src, ZP, nil, ZP, SoverD); } +void +swap(int *a, int *b) +{ + int t; + + t = *a; + *a = *b; + *b = t; +} + void bresenham(Memimage *dst, Point p0, Point p1, Memimage *src) { - double t, dt; - Point p; + int steep = 0; + double t; + Point p, dp; + + if(abs(p0.x-p1.x) < abs(p0.y-p1.y)){ + steep = 1; + swap(&p0.x, &p0.y); + swap(&p1.x, &p1.y); + } - dt = 0.01; + /* make them left-to-right */ + if(p0.x > p1.x){ + swap(&p0.x, &p1.x); + swap(&p0.y, &p1.y); + } + + dp = subpt(p1, p0); + + for(p = p0; p.x <= p1.x; p.x++){ + t = (double)(p.x-p0.x)/(p1.x-p0.x); + p.y = flerp(p0.y, p1.y, t); + + if(steep) + swap(&p.x, &p.y); - for(t = 0; t < 1; t += dt){ - p = Pt( - flerp(p0.x, p1.x, t), - flerp(p0.y, p1.y, t) - ); pixel(dst, p, src); + + if(steep) + swap(&p.x, &p.y); } } @@ -181,6 +209,8 @@ threadmain(int argc, char *argv[]) fb = eallocmemimage(screen->r, screen->chan); red = rgb(DRed); bresenham(fb, Pt(40,40), Pt(300,300), red); + bresenham(fb, Pt(80,80), Pt(100,200), red); + bresenham(fb, Pt(80,80), Pt(200,100), red); display->locking = 1; unlockdisplay(display); -- cgit v1.2.3