r11859: Canonicalize whitespace
[ctsim.git] / libctgraphics / bresenham.cpp
1 /*****************************************************************************
2 **  This is part of the CTSim program
3 **  Copyright (c) 1983-2001 Kevin Rosenberg
4 **
5 **  $Id$
6 **
7 **  This program is free software; you can redistribute it and/or modify
8 **  it under the terms of the GNU General Public License (version 2) as
9 **  published by the Free Software Foundation.
10 **
11 **  This program is distributed in the hope that it will be useful,
12 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 **  GNU General Public License for more details.
15 **
16 **  You should have received a copy of the GNU General Public License
17 **  along with this program; if not, write to the Free Software
18 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 ******************************************************************************/
20
21 // REFERENCES FOR BRESENHAM'S ALGORITHM
22 // Newman & Sproll, "Principals of Interactive Computer Graphics",  page 25.
23 // Foley & van Dam, "Fundementals of Interactive Computer Graphics", page 433
24
25
26
27 void
28 bresenham (int x1, int y1, int x2, int y2)
29 {
30   int delta_x = x2 - x1;
31   int dx_abs = (delta_x >= 0 ? delta_x : -delta_x);
32
33   int delta_y = y2 - y1;
34   int dy_abs = (delta_y >= 0 ? delta_y : -delta_y);
35
36   // draws a line when abs(dx) >= abs(dy)
37   if (dx_abs > dy_abs) {
38     int count = dx_abs + 1;
39     int major_inc = (x1 <= x2 ? 1 : -1);
40     int min_inc = (delta_y >= 0 ? 1 : -1);     // determine direction of minor axis
41
42     int d = dy_abs * 2 - dx_abs;      // Put decision variable in d
43     int dinc1 = (dy_abs - dx_abs) * 2;
44     int dinc2 = 2 * dy_abs;
45
46     bresx (x1, y1, major_inc, d, d1, d2);
47   } else {    //For plotting lines with abs(dy) > abs(sx)
48     int count = dy_abs + 1;
49
50     int major_inc = (y1 <= y2 ? 1 : -1);
51     int min_inc = (delta_x >= 0 ? 1 : -1);      // check direction of minor axis
52
53     int d = dx_abs * 2 - dy_abs;
54     dinc1 = (dx_abs - dy_abs) * 2;
55     dinc2 = 2 * dx_abs;
56
57     bresy (x1, y1, major_inc, min_inc, count, d, d1, d2);
58   }
59 }
60
61
62 static void
63 bresx (int x, int y, int majorinc, int minorinc, int count, int d, int d1, int d2)
64 {
65   do {
66     setpixel();
67     x += majorinc;
68
69     if (d < 0)
70       d += dinc2;
71     else {
72       d += dinc1;
73       y += min_inc;
74     }
75   } while (--count > 0);
76 }
77
78
79 static void
80 bresy (int x, int y, int majorinc, int minorinc, int count, int d, int d1, int d2)
81 {
82   do {
83     setpixel();
84     y += majorinc;
85
86     if (d < 0)
87       d += dinc2;
88     else {
89       d += dinc1;
90       x += min_inc;
91     }
92   } while (--count > 0);
93 }
94
95