1// This file is part of SmallBASIC
2//
3// Bresenham's algorithm for drawing line
4//
5// This program is distributed under the terms of the GPL v2.0 or later
6// Download the GNU Public License (GPL) from www.gnu.org
7//
8// Copyright(C) 2000 Nicholas Christopoulos
9
10#include "common/sys.h"
11
12void g_line(int x1, int y1, int x2, int y2, void(*dotproc)(int, int)) {
13 int dX, dY, row, col, final, G, inc1, inc2;
14 char pos_slope;
15
16 dX = x2 - x1;
17 dY = y2 - y1;
18 pos_slope = (dX > 0);
19 if (dY < 0)
20 pos_slope = !pos_slope;
21
22 if (ABS(dX) > ABS(dY)) {
23 if (dX > 0) {
24 col = x1;
25 row = y1;
26 final = x2;
27 } else {
28 col = x2;
29 row = y2;
30 final = x1;
31 }
32
33 inc1 = 2 * ABS(dY);
34 G = inc1 - ABS(dX);
35 inc2 = 2 * (ABS(dY) - ABS(dX));
36 if (pos_slope) {
37 while (col <= final) {
38 dotproc(col, row);
39 col++;
40 if (G >= 0) {
41 row++;
42 G += inc2;
43 } else
44 G += inc1;
45 }
46 } else {
47 while (col <= final) {
48 dotproc(col, row);
49 col++;
50 if (G > 0) {
51 row--;
52 G += inc2;
53 } else
54 G += inc1;
55 }
56 }
57 } /* if |dX| > |dY| */
58 else {
59 if (dY > 0) {
60 col = x1;
61 row = y1;
62 final = y2;
63 } else {
64 col = x2;
65 row = y2;
66 final = y1;
67 }
68
69 inc1 = 2 * ABS(dX);
70 G = inc1 - ABS(dY);
71 inc2 = 2 * (ABS(dX) - ABS(dY));
72
73 if (pos_slope) {
74 while (row <= final) {
75 dotproc(col, row);
76 row++;
77 if (G >= 0) {
78 col++;
79 G += inc2;
80 } else
81 G += inc1;
82 }
83 } else {
84 while (row <= final) {
85 dotproc(col, row);
86 row++;
87 if (G > 0) {
88 col--;
89 G += inc2;
90 } else
91 G += inc1;
92 }
93 }
94 }
95}
96