Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
23 views
71 pages
Foley 2E
Book on Computer Graphics
Uploaded by
MUHAMMAD EHSANUL KADER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Foley 2E For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
23 views
71 pages
Foley 2E
Book on Computer Graphics
Uploaded by
MUHAMMAD EHSANUL KADER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Foley 2E For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save Foley 2E For Later
You are on page 1
/ 71
Search
Fullscreen
72 Basic Raster Graphics Algorithms for Drawing 2D Primitives Raster displays invoke clipping and scan-conversion algorithms each time an image is created or modified. Hence, these algorithms not only must create visually satisfactory images, but also must execute as rapidly as possible. As discussed in detail in later sections, scan-conversion algorithms use incremental methods to minimize the number of calcula- tions (especially multiplies and divides) performed during each iteration; further, these calculations employ integer rather than floating-point arithmetic. As shown in Chapter 18, speed can be increased even further by using multiple parallel processors to scan convert simultaneously entire output primitives or pieces of them. 2 SCAN CONVERTING LINES ‘A scan-conversion algorithm for lines computes the coordinates of the pixels that lie on or near an ideal, infinitely thin straight line imposed on a 2D raster grid. In principle, we would like the sequence of pixels to lie as close to the ideal line as possible and to be as straight as possible. Consider a I-pixel-thick approximation to an ideal line; what properties should it have? For lines with slopes between ~1 and 1 inclusive, exactly 1 pixel should be illuminated in each column; for lines with slopes outside this range, exactly 1 pixel should be illuminated in each row. All lines should be drawn with constant brightness, independent of length and orientation, and as rapidly as possible. There should also be provisions for drawing lines that are more than 1 pixel wide, centered on the ideal line, that are affected by line-style and pen-style attributes, and that create other effects needed for high-quality illustrations, For example, the shape of the endpoint regions should be under programmer control to allow beveled, rounded, and mitered corners. We would even like to be able to minimize the jaggies due to the discrete approximation of the ideal line by using antialiasing techniques exploiting the ability 10 set the intensity of individual pixels on n-bits-per-pixel displays. For now, we consider only ‘‘optimal,"* 1-pixel-thick lines that have exactly 1 bilevel pixel in each column (or row for steep lines). Later in the chapter, we consider thick primitives and deal with styles. ‘To visualize the geometry, we recall that SRGP represents a pixel as a circular dot centered at that pixel’s (x, y) location on the integer grid. This representation is a convenient approximation to the more or less circular cross-section of the CRT’s electron beam, but the exact spacing between the beam spots on an actual display can vary greatly among systems. In some systems, adjacent spots overlap; in others, there may be space between adjacent vertical pixels; in most systems, the spacing is tighter in the horizontal than in the vertical direction. Another variation in coordinate-system representation arises in systems, such as the Macintosh, that treat pixels as being centered in the rectangular box between adjacent grid lines instead of on the grid lines themselves. In this scheme, rectangles are defined to be all pixels interior to the mathematical rectangle defined by two corner points. This definition allows zero-width (null) canvases: The rectangle from (x, y) to (x, y) contains no pixels, unlike the SRGP canvas, which has a single pixel at that point. For now, we continue to represent pixels as disjoint circles centered on a uniform grid, although we shall make some minor changes when we discuss antialiasing. Figure 3.4 shows a highly magnified view of a 1-pixel-thick line and of the ideal line that it approximates. The intensified pixels are shown as filled circles and the nonintensified3.2 Scan Converting Lines 73 Fig. 3.4 A scan-converted line showing intensified pixels as black circles. pixels are shown as unfilled circles. On an actual screen, the diameter of the roughly Circular pixel is larger than the interpixel spacing, so our symbolic representation exaggerates the discreteness of the pixels. ‘Since SRGP primitives are defined on an integer grid, the endpoints of a line have integer coordinates. In fact, if we first clip the line to the clip rectangle, a line intersecting a clip edge may actually have an endpoint with a noninteger coordinate value. The same is true when we use a floating-point raster graphics package. (We discuss these noninteger intersections in Section 3.2.3.) Assume that our line has slope |m| = 1; lines at other slopes can be handled by suitable changes in the development that follows. Also, the most common lines—those that are horizontal, are vertical, or have a slope of +1—can be handled as trivial special cases because these lines pass through only pixel centers (see Exercise 3.1). The simplest strategy for scan conversion of lines is to compute the slope m as Ay/Ax, to increment x by | starting with the leftmost point, to calculate y; = mx, + B for each x;, and to intensify the pixel at (x, Round(y,)), where Round(y,) = Floor(0.5 + y). This computation selects the closest pixe!—that is, the pixel whose distance to the true line is, smallest. This brute-force strategy is inefficient, however, because each iteration requires a floating-point (or binary fraction) multiply, addition, and invocation of Floor. We can eliminate the multiplication by noting that ier = mye) + B= mx, + Ax) + B= y, + mAx, and, if Ax = 1, then y,,, = y,; + m. Thus, a unit change in x changes y by m, which is the slope of the line. For all points (xi, y)) on the line, we know that, ifx,., =x; + 1, then y,,, = y; + m; thatis, the values of x and y are defined in terms of their previous values (see Fig. 3.5). This is what defines an ‘in Chapter 19, we discuss various measures of closeness for lines and general curves (also called error measures).74 Basic Raster Graphics Algorithms for Drawing 2D Primitives (%;, Round ()) Fig. 3.5 Incremental calculation of |x, y)). incremental algorithm: At each step, we make incremental calculations based on the preceding step. We initialize the incremental calculation with (x, yy), the integer coordinates of an endpoint. Note that this incremental technique avoids the need to deal with the y intercept, B, explicitly. If |m| > 1, a step in x creates a step in y that is greater than 1. Thus, we must reverse the roles of x and y by assigning a unit step to y and incrementing x by Ax = Ay/m = I/m. Line, the procedure in Fig. 3.6, implements this technique. The start point must be the left endpoint. Also, it is limited to the case -1 < m = 1, but other slopes may be accommodated by symmetry. The checking for the special cases of horizontal, vertical, or diagonal lines is omitted, WritePixel, used by Line, is a low-level procedure provided by the device-level software; it places a value into a canvas for a pixel whose coordinates are given as the first, two arguments.? We assume here that we scan convert only in replace mode; for SRGP’s other write modes, we must use a low-level ReadPixel procedure to read the pixel at the destination location, logically combine that pixel with the source pixel, and then write the result into the destination pixel with WritePixel. This algorithm is often referred to as a digital differential analyzer (DDA) algorithm. ‘The DDA is a mechanical device that solves differential equations by numerical methods: It traces out successive (x, y) values by simultancously incrementing x and y by small steps proportional to the first derivative of x and y. In our case, the x increment is 1, and the y increment is dy/dx = m. Since real variables have limited precision, summing an inexact m repetitively introduces cumulative error buildup and eventually a drift away from a true Round(y;); for most (short) lines, this will not present a problem. 3.2.2 Midpoint Line Algorithm ‘The drawbacks of procedure Line are that rounding y to an integer takes time, and that the variables y and m must be real or fractional binary because the slope is a fraction. Bresenham developed a classic algorithm [BRES6S] that is attractive because it uses only AIF such a low-level procedure is not available, the SRGP_pointCoord procedure may be used, as described in the SRGP reference manual.3.2 Scan Converting Lines 75 void Line ( Je Assumes —1
0, we choose pixel NE; ifd <0, ‘we choose E; and if d = 0, we can choose either, so we pick E. Next, we ask what happens to the location of M and therefore to the value of d for the next grid line; both depend, of course, on whether we chose E or NE. If £ is chosen, M is ® This functional form extends nicely to the implicit formulation of both circles and ellipses. ‘I is important for the proper functioning of the midpoint algorithm to choose a to be positive; we meet this criterion if dy is positive, since yy > yp.3.2 Scan Converting Lines 77 incremented by one step in the x direction. Then, yoy = F(Xp + 2, yp + 2) = alxp + 2) + HOp +H +6, but yy = asp + 1) + bp +4) +. Subtracting dy, from d,,, to get the incremental difference, we write dye = dyy + a. ‘We call the increment to add after E is chosen A,; A, = dy. In other words, we can. derive the value of the decision variable at the next step incrementally from the value at the current step without having to compute F(M) directly, by merely adding Ap. If NE is chosen, M is incremented by one step each in both the x and y directions. Then, yey = Flap + 2, yp +9) = alxp + 2) + BOP +) te. Subtracting dy, from dy 10 get the incremental difference, we write ayy = dy + a + bz We call the increment to add to d after NE is chosen Ayg; Ayg = a + b = dy — de. Let’s summarize the incremental midpoint technique. At each step, the algorithm chooses between 2 pixels based on the sign of the decision variable calculated in the previous iteration; then, it updates the decision variable by adding either Ag or Aye to the old value, depending on the choice of pixel. Since the first pixel is simply the first endpoint (x), y), we can directly calculate the initial value of d for choosing between E and NE. The first midpoint is at (4) + 1, y) +2), and Flay + 1, y+) = aly + 1) + by +H +e = ary + by t+ct+at br = F(X, yy) + a + BI2. But (1p, y9) is a point on the line and F(x, y9) is therefore 0; hence, dan is just a + b/2 = dy — du/2. Using dy, we choose the second pixel, and so on. To eliminate the fraction in Gearty WE redefine our original F by multiplying it by 2; F(x, y) = 2(ax + by + c). This multiplies each constant and the decision variable by 2, but does not affect the sign of the decision variable, which is all that matters for the midpoint test. The arithmetic needed to evaluate dyey for any step is simple addition. No time- ‘consuming multiplication is involved. Further, the inner loop is quite simple, as seen in the midpoint algorithm of Fig. 3.8. The first statement in the loop, the test of d, determines the choice of pixel, but we actually increment x and y to that pixel location after updating the decision variable (for compatibility with the circle and ellipse algorithms), Note that this yersion of the algorithm works for only those lines with slope between 0 and 1; generalizing the algorithm is left as Exercise 3.2. In [SPRO82}, Sproull gives an elegant derivation of Bresenham's formulation of this algorithm as a series of program transformations from the original brute-force algorithm. No equivalent of that derivation for circles or ellipses has yet appeared, but the midpoint technique does generalize, as we shall see.78 — Basic Raster Graphics Algorithms for Drawing 2D Primitives void MidpointL ine (int x0, int y0, int x/, int y/, int value) Initial value of d +/ Increment used for move to E +/ Increment used for move to NE *! WritePixel (x, y, value); J+ The start pixel +/ while (x < x/) { if (d<=0){ Ix Choose E +! J» Choose NE +/ WritePixel (x, y, value); Je The selected pixel closest tothe line +/ } /* while +/ } /* MidpointLine +/ Fig. 3.8 The midpoint line scan-conversion algorithm. For alline from point (5, 8) to point (9, 11), the successive values of d are 2, 0, 6, and 4, resulting in the selection of NE, E, NE, and then NE, respectively. as shown in Fig. 3.9. The line appears abnormally jagged because of the enlarged scale of the drawing and the artificially large interpixel spacing used ‘© make the geometry of the algorithm clear. For the same reason, the drawings in the following sections also make the primitives appear blockier than they look on an actual screen. 3.2.3 Additional Issues Endpoint order. Among the complications to consider is that we must ensure that a line from P, to P, contains the same set of pixels as the line from P, to P,, so that the appearance of the line is independent of the order of specification of the endpoints. The only place where the choice of pixel is dependent on the direction of the line is where the line passes exactly through the midpoint and the decision variable is zero; going left to right, we chose to pick £ for this case. By symmetry, while going from right to left, we would also expect to choose W for d= 0, but that would choose a pixel one unit up in y relative to the one chosen for the left-to-right scan. We therefore need to choose SW when d = 0 for right-to-left scanning. Similar adjustments need to be made for lines at other slopes.3.3 Scan Converting Circles 81 ” Line 8 Line A Fig. 3.11 Varying intensity of raster lines as a function of slope. appropriate intensities for the multiple pixels in each column that lie in or near the rectangle. ‘Treating the line as a rectangle is also a way to create thick lines. In Section 3.9, we show how to modify the basic scan-conversion algorithms to deal with thick primitives and with primitives whose appearance is affected by line-style and pen-style attributes. Chapter 19 treats several other enhancements of the fundamental algorithms, such as handling endpoint shapes and creating joins between lines with multiple-pixel width. Outline primitives composed of lines. Knowing how to scan convert lines, how do we scan convert primitives made from lines? Polylines can be scan-converted one line segment at a time. Scan converting rectangles and polygons as area-defining primitives could be done a line segment at a time but that would result in some pixels being drawn that lie outside a primitive’s area—see Sections 3.5 and 3.6 for special algorithms to handle this problem. Care must be taken to draw shared vertices of polylines only once, since drawing a vertex twice causes it to change color or to be set to background when writing in xor mode toa screen, or to be written at double intensity on a film recorder. In fact, other pixels may be shared by two line segments that lie close together or cross as well. See Section 19.7 and Exercise 3.8 for a discussion of this, and of the difference between a polyline and a sequence of connected line segments. 3.3. SCAN CONVERTING CIRCLES Although SRGP does not offer a circle primitive, the implementation will benefit from treating the circular ellipse arc as a special case because of its eight-fold symmetry, both for clipping and for scan conversion. The equation of a circle centered atthe origin isx* + y? Circles not centered at the origin may be translated to the origin by integer amounts and then scan converted, with pixels written with the appropriate offset. There are several easy but inefficient ways to scan convert a circle. Solving for y in the implicit circle equation, we get the explicit y = f(x) as y= VR ‘To draw a quarter circle (the other quarters are drawn by symmetry), we can increment x from 0 to R in unit steps, solving for +y at each step. This approach works, but it is82 Basic Raster Graphics Algorithms for Drawing 2D Primitives inefficient because of the multiply and square-root operations. Furthermore, the circle will have large gaps for values of x close to R, because the slope of the circle becomes infinite there (see Fig. 3.12). A similarly inefficient method, which does, however, avoid the large gaps, is to plot (R cos8, R sind) by stepping 8 from 0° to 90°. 3.3.1. Eight-Way Symmetry ‘We can improve the drawing process of the previous section by taking greater advantage of the symmetry in a circle. Consider first a circle centered at the origin. If the point (x, y) is on the circle, then we can trivially compute seven other points on the circle, as shown in Fig. 3.13. Therefore, we need to compute only one 45° segment to determine the circle completely. Fora circle centered at the origin, the eight symmetrical points can be displayed with procedure CirclePoints (the procedure is easily generalized to the case of circles with arbitrary origins): void CirclePoints (int x, int y, int value) { WritePixel (x, y, value); ‘WritePixel (y, x, value); WritePixel (—x, —y, vali WritePixel (~y, —, value); WritePixel (—y, x, value); WritePixel (—x, y, value); } (+ CirclePoints »/ ‘We do not want to call CirclePoints when x = y, because each of four pixels would be set twice; the code is easily modified to handle that boundary condition. (0.17) § \ \ (17,0) Fig. 3.12 A quarter circle generated with unit steps in x, and with y calculated and then rounded. Unique values of y for each x produce gaps.3.3 Scan Converting Circles 83 Fig. 3.13 Eight symmetrical points on a circle. 3.3.2 Midpoint Circle Algorithm Bresenham [BRES77] developed an incremental circle generator that is more efficient than the methods we have discussed. Conceived for use with pen plotters, the algorithm generates all points on a circle centered at the origin by incrementing all the way around the circle, We derive a similar algorithm, again using the midpoint criterion, which, for the case of integer center point and radius, generates the same, optimal set of pixels. Furthermore, the resulting code is essentially the same as that specified in patent 4,371,933 (BRES83]. ‘We consider only 45° of a circle, the second octant from x = Oto x = y = R/V2, and use the CirclePoints procedure to display points on the entire circle. As with the midpoint line algorithm, the strategy is to select which of 2 pixels is closer to the circle by evaluating a function at the midpoint between the 2 pixels. In the second octant, if pixel P at (xp, yp) has been previously chosen as closest to the circle, the choice of the next pixel is between pixel E and SE (see Fig. 3.14). P= bp, Yp) Previous Choices for Choices for pixel current pixel next pixel Fig. 3.14 The pixel grid for the midpoint circle algorithm showing M and the pixels E and SE to choose between.84 Basic Raster Graphics Algorithms for Drawing 2D Primitives Let F(x, y) = x + y* — R& this function is 0 on the circle, positive outside the circle, and negative inside the circle. It can be shown that if the midpoint between the pixels E and SE is outside the circle, then pixel SE is closer to the circle. On the other hand, if the midpoint is inside the circle, pixel E is closer to the circle. As for lines, we choose on the basis of the decision variable d, which is the value of the function at the midpoint, dug = Ftp +1, Ye — = Op + DP + Op — BF - If d,, < 0, E is chosen, and the next midpoint will be one increment over in x. Then, yge = Flip + 25 Yo — 9 = (Kp + 2 + Op — HF - RE ANd doo = uy + (2xp + 3); therefore, the increment Ay = 2xp + 3. Ifd,,= 0. SE is chosen.* and the next midpoint will be one increment over in xand one increment down in y. Then oey = Fp + 2, yp — 9 = (xp + 2)? + (yp — FF — R. Since dyey = dy + (2xp — 2yp + 5), the increment Ay = 2xp — 2yp + 5. Recall that, in the linear case, A, and Ayg were constants; in the quadratic case, however, Ay and Ac, vary at each step and are functions of the particular values of xp and yp at the pixel chosen in the previous iteration. Because these functions are expressed in terms of (4p, yp), we call P the point of evaluation. The A functions can be evaluated directly at ‘each step by plugging in the values of x and y for the pixel chosen in the previous iteration. ‘This direct evaluation is not expensive computationally, since the functions are only linear. In summary, we do the same two steps at each iteration of the algorithm as we did for the line: (1) choose the pixel based on the sign of the variable d computed during the previous iteration, and (2) update the decision variable d with the A that corresponds to the choice of pixel. The only difference from the line algorithm is that, in updating d, we evaluate a linear function of the point of evaluation. All that remains now is to compute the initial condition. By limiting the algorithm to integer radii in the second octant, we know that the starting pixel lies on the circle at (0, R). The next midpoint lies at (1, R — }), therefore, and FU, R 9) = 1+ (R-R+D 4—R. Now wecan implement the algorithm directly, as in Fig. 3.15. Notice how similar in structure this algorithm is to the line algorithm. The problem with this version is that we are forced to do real arithmetic because of the fractional initialization of d. Although the procedure can be easily modified to handle circles that are not located on integer centers or do not have integer radii, we would like a more efficient, purely integer version. We thus do a simple program transformation to eliminate fractions. First, we define a new decision variable, h, by h = d —4, and we substitute h +4 for d in the code. Now, the intialization ish = | — R, and the comparison d <0 becomesh < — 4. ‘Choosing SE when d = 0 differs from our choice in the line algorithm and is arbitrary. The reader ‘may wish to simulate the algorithm by hand to see that, for R = 17, 1 pixel is changed by this choice.3.3 Scan Converting Circles 85 void MidpointCircle (int radius, int value) J Assumes center of circle is at origin +/ { intx =0; int y = radius; double 5.0 / 4.0 — radius; CirclePoims (x, y, value); while (y > x) { if (@<0) J Select E +! d+=2104x+3.0; else { Iu Select SE »/ 0 « (x —y) +50; att: CirclePoinis (x, y, value); } I while + } /* MidpoimtCircle +/ Fig. 3.15 The midpoint circle scan-conversion algorithm. However, since h starts out with an integer value and is incremented by integer values (A, and Az), we can change the comparison to just h <0. We now have an integer algorithm in terms of h; for consistency with the line algorithm, we will substitute d for h throughout. The final, fully integer algorithm is shown in Fig. 3.16. Figure 3.17 shows the second octant of a circle of radius 17 generated with the algorithm, and the first octant generated by symmetry (compare the results to Fig. 3.12). Second-order differences. We can improve the performance of the midpoint circle algorithm by using the incremental computation technique even more extensively. We noted that the A functions are linear equations, and we computed them directly. Any polynomial can be computed incrementally, however, as we did with the decision variables for both the line and the circle. In effect, we are calculating first- and second-order partial differences, a useful technique that we encounter again in Chapters 11 and 19. The strategy is to evaluate the function directly at two adjacent points, to calculate the difference (which, for polynomials, is always a polynomial of lower degree), and to apply that difference in each iteration. If we choose F in the current iteration, the point of evaluation moves from (xp, Vp) to (ip + 1, yp). As we saw, the first-order difference is Ag. at (Xp, yp) = 2tp + 3. Therefore, Agaee t (Xp + 1, Yp) = Aap + 1) + 3, and the second-order difference is Ay, ~ Asay = 2- at86 Basic Raster Graphics Algorithms for Drawing 2D Primitives void MidpointCircle (int radius, int value) Ix Assumes center of circle is at origin. Integer arithmetic only */ { intx=0; int y = radius; int d =1 — radius; CirclePoints (x, y, value); while (y > x) { if (<0) J+ Select E #/ d+=2ex4+3; else { Ie Select SE */ d *(r-y) +5 e } att CirclePoints (x,y, value): } Ie while «/ } /* MidpointCircle +/ Fig. 3.16 The integer midpoint circle scan-conversion algorithm. Similarly, Aggy, at (xp, yp) = 2xp — 2yp + 5. Therefore, Mséree at (Xp + 1, Yp) = Wap + 1) = 2yp + 5, and the second-order difference is Age. — Asa, = 2 If we choose SE in the current iteration, the point of evaluation moves from (tp, yp) 10 (ap + 1, yp — 1). Therefore, Mowe At (Xp + 1, Ye — 1) = 2p + D+ 3, and the second-order difference is Ay... — Ap, = 2. Also, Asean at (Xp + 1, Yo — 1) = 2p + 1) — 2p - 1) + 5, and the second-order difference is Asis, ~ Aspas = 4: The revised algorithm then consists of the following steps: (1) choose the pixel based on the sign of the variable d computed during the previous iteration; (2) update the decision variable d with either Ay or Ace, using the value of the corresponding A computed during the previous iteration; (3) update the As to take into account the move to the new pixel, using the constant differences computed previously; and (4) do the move. Ay and Asy are initialized using the start pixel (0, R). The revised procedure using this technique is shown in Fig. 3.18.3.3 Scan Converting Circles 87 Second octant generated by algorithm Fig. 3.17 Second octant of circle generated with midpoint algorithm, and first octant generated by symmetry. void MidpointCircle (int radius, int value) J+ This procedure uses second-order partial differences to compute increments. «/ ‘/+ in the decision variable. Assumes center of circle is at origin */ int delta = 3; int deltaSE = ~2 + radius + 5; CirclePoints (x, y, value); while (y > x) { if (d<0){ In Select E +/ J Select SE +! att CirclePoints (x,y, value); } I= while +/ } /* MidpoimCircle +/ Fig. 3.18 Midpoint circle scan-conversion algorithm using second-order differences.88 Basic Raster Graphics Algorithms for Drawing 2D Primitives 3.4 SCAN CONVERTING ELLIPSES Consider the standard ellipse of Fig. 3.19, centered at (0, 0). It is described by the equation FQ, y) = Be + ay? - a’ = 0, where 2a is the length of the major axis along the x axis, and 2b is the length of the minor axis along the y axis. The midpoint technique discussed for lines and circles can also be applied to the more general conics. In this chapter, we consider the standard ellipse that is supported by SRGP; in Chapter 19, we deal with ellipses at any angle. Again, to simplify the algorithm, we draw only the are of the ellipse that lies in the first quadrant, since the other three quadrants can be drawn by symmetry. Note also that standard ellipses centered at integer points other than the origin can be drawn using a simple translation. The algorithm presented here is based on Da Silva’s algorithm, which combines the techniques used by Pitteway [PITT67], Van Aken [VANA84] and Kappel [KAPP85] with the use of partial differences [DASI89]. We first divide the quadrant into two regions; the boundary between the two regions is the point at which the curve has a slope of —1 (see Fig. 3.20). Determining this point is more complex than it was for circles, however. The vector that is perpendicular to the tangent to the curve at point P is called the gradient, defined as grad F(x, y) = dF/ax i + aF/ay j = 2b’x i + laty j. ‘The boundary between the two regions is the point at which the slope of the curve is -1, and that point occurs when the gradient vector has a slope of |—that is, when the i and j ‘components of the gradient are of equal magnitude. The j component of the gradient is larger than the i component in region 1, and vice versa in region 2. Thus, if at the next midpoint, a’(yp — 4) = B(xp + 1), we switch from region 1 to region 2. ‘As with any midpoint algorithm, we evaluate the function at the midpoint between two pixels and use the sign to determine whether the midpoint lies inside or outside the ellipse and, hence, which pixel lies closer to the ellipse. Therefore, in region 1, if the current pixel is located at (xp, yp), then the decision variable for region 1, d,, is F(4, y) evaluated at (xp + 1, Ye —}), the midpoint between E and SE. We now repeat the process we used for deriving the Fig. 3.19 Standard ellipse centered at the origin.3.4 Scan Converting Ellipses 89 Gradient vector component ‘component Fig. 3.20 Two regions of the ell defined by the 45° tangent. two As for the circle. For a move to E, the next midpoint is one increment over in x. Then, dyy = Flxp + 1, yp —) = Pap + IF + ap — 2 — ab, yyy = FXp + 2, yp —Y = Bap + 27 + ap — PH - ae. Since dpey = day + b*(2xp + 3), the increment Ay = L*(2xp + 3). For a move to SE, the next midpoint is one increment over in x and one increment down. in y. Then, ggg = Fp + 25 Ye — ¥) = Pap + DF + ayy — HF - ab? Since dye = dyy + BX2tp + 3) + a%{—2yp + 2), the increment Agy = bA2xp + 3) + a(—2yp + 2). In region 2, if the current pixel is at (xp, yp), the decision variable dz is Flxp + 3, yp — 1), the midpoint between § and SE, Computations similar to those given for region 1 may be done for region 2. We must also compute the initial condition. Assuming integer values a and b, the ellipse starts at (0, 6), and the first midpoint to be calculated is at (1, b — 3). Then, Fl, b-D=P + ab — 3? — ah =F + a(-b +). At every iteration in region 1, we must not only test the decision variable d, and update the A functions, but also see whether we should switch regions by evaluating the gradient at the midpoint between E and SE. When the midpoint crosses over into region 2, we change our choice of the 2 pixels to compare from E and SE to SE and S. At the same time, we have to initialize the decision variable d, for region 2 to the midpoint between SE and S. That is, if the last pixel chosen in region 1 is located at (xp, yp), then the decision variable d, is itialized at (xp + }, yp — 1). We stop drawing pixels in region 2 when the y value of the pixel is equal to 0. As with the circle algorithm, we can either calculate the A functions directly in each iteration of the loop or compute them with differences. Da Silva shows that computation of second-order partials done for the As can, in fact, be used for the gradient as well (DASI89]. He also treats general ellipses that have been rotated and the many wicky90 Basic Raster Graphics Algorithms for Drawing 2D Primitives boundary conditions for very thin ellipses. The pseudocode algorithm of Fig. 3.21 uses the simpler direct evaluation rather than the more efficient formulation using second-order differences; it also skips various tests (see Exercise 3.9). In the case of integer a and b, we can eliminate the fractions via program transformations and use only integer arithmetic. void MidpointEllpse (int a, int b, int value) /* Assumes center of ellipse is at the origin. Note that overflow may occur */ i for 16-bit integers because of the squares. +/ { double 42: double di = 6? — (a*b) + (0.25 a2); EllipsePoints (x, y, value); J+ The 4-way symmetrical WritePixel +/ J Test gradient if still in region 1 +/ while (a"(y-0.5)>B(x+1)){ — /* Region 1 +/ if (dl <0) In Select E +! dl += 6'(2x +3); else { In Select SE */ d] += B(2x +3) +a°(—2y +2); y } +4 EllipsePoints (x, y, value); } Region | +/ d2=P(x +05) +a%(y — 1)? — ab; while (9 > 0) { I+ Region 2 +/ (a
pair. Although the slope-intercept3.12 Clipping Lines 113 formula for lines learned in analytic geometry could be used, it describes infinite lines, whereas in graphics and clipping we deal with finite lines (called line segments in mathematics). In addition, the slope-intercept formula does not deal with vertical lines—a serious problem, given our upright clip rectangle. A parametric formulation for line segments solves both problems: X= y+ 1 — 9), ¥ = Yo + 10; = Yo- These equations describe (x, y) on the directed line segment from (9, ¥) to (x,, ¥,) for the parameter 1 in the range [0, 1], as simple substitution for ¢ confirms. Two sets of simultaneous equations of this parametric form can be solved for parameters fig. for the edge and fee for the line segment. The values Of fig and fae can then be checked to see whether both lie in (0, 1]; if they do, the intersection point lies within both segments and is 4 true clip-rectangle intersection. Furthermore, the special case of a line parallel to a dlip-rectangle edge must also be tested hefore the simultaneous equations can be solved. Altogether, the brute-force approach involves considerable calculation and testing; itis inefficient. The more efficient Cohen—Sutherland algorithm performs ial tests on a line to determine whether intersection calculations can be avoided. First, endpoint pairs are checked for trivial acceptance. If the line cannot be trivially accepted, region checks are done. For instance, two simple comparisons on x show that both endpoints of line EF in Fig. 3.38 have an x coordinate less than x,,, and thus lie in the region to the left of the clip rectangle the outside halfplane defined by the left edge); therefore, line segment EF can be trivially rejected and needs to be neither clipped nor displayed. Similarly, we can trivial- ly reject lines with both endpoints in regions to the right Of Xqac+ BelOW Ygig, and above $a If the line segment can be neither trivially accepted nor rejected, it is divided into two segments at a clip edge, so that one segment can be trivially rejected. Thus, a segment is iteratively clipped by testing for trivial acceptance or rejection, and is then subdivided if ther test is successful, until what remains is completely inside the clip rectangle or can be trivially rejected. The algorithm is particularly efficient for two common cases. In the first case of a large clip rectangle enclosing all or most of the display area, most primitives can be trivially accepted. In the second case of a small clip rectangle, almost all primitives can be trivially rejected. This latter case arises in a standard method of doing pick correlation in which a small rectangle surrounding the cursor, called the pick window, is used to clip primitives to determine which primitives lie within a small (rectangular) neighborhood of the cursor's pick point (see Section 7.12.2). ‘To perform trivial accept and reject tests, we extend the edges of the clip rectangle to divide the plane of the clip rectangle into nine regions (see Fig. 3.39). Each region is assigned a 4-bit code, determined by where the region lies with respect to the outside halfplanes of the clip-rectangle edges. Each bit in the outcode is set to either | (true) or 0 (false); the 4 bits in the code correspond to the following conditions:114 Basic Raster Graphics Algorithms for Drawing 2D Primitives g g 0001 | 0000 | 0010 oro 1 lip rectangle Fig. 3.39 Region outcodes. First bit outside halfplane of top edge, above top edge y> Yeas Second bit outside halfplane of bottom edge, below bottom edge ¥< Yen Third bit ‘outside halfplane of right edge, to the right of right edge x > mux Fourth bit outside halfplane of left edge, to the left of left edge £
ymax) code |= TOP: elseif (y < ymin) code |= ROTTOM; if (x > xmar) code |= RIGHT; else if (x < xmin) code |= LEFT; return code; } /* CompOutCode +/ Fig. 3.41 Cohen-Sutherland line-clipping algorithm. Nicholl [NICH87] algorithm, by contrast, avoids calculating external intersections by subdividing the plane into many more regions; itis discussed in Chapter 19. An advantage of the much simpler Cohen—Sutherland algorithm is that its extension to a 3D orthographic view volume is straightforward, as seen in Section 6.5.3 3.12.4 A Parametric Lin the most commonly used line-clipping algorithm because it has been around longest and has been published widely. In 1978, Cyrus and Beck published an algorithm that takes a fundamentally different and generally more efficient approach to line clipping [CYRU78]. The Cyrus—Beck technique can be used to clip a 2D line against a rectangle or an arbitrary convex polygon in the plane, or a 3D line ‘against an arbitrary convex polyhedron in 3D space. Liang and Barsky later independently developed a more efficient parametric line-clipping algorithm that is especially fast in the special cases of upright 2D and 3D clip regions [LIAN84]. In addition to taking advantage of these simple clip boundaries, they introduced more efficient trivial rejection tests that work for general clip regions. Here we follow the original Cyrus-Beck development to introduce parametric clipping. Since we are concerned only with upright clip rectangles, however, we reduce the Cyrus-Beck formulation to the more efficient Liang—Barsky case at the end of the development. Recall that the Cohen-Sutherland algorithm, for lines that cannot be trivially accepted or rejected, calculates the (x, y) intersection of a line segment with a clip edge by substituting the known value of x or y for the vertical or horizontal clip edge, respectively. The parametric line algorithm, however, finds the value of the parameter tin the parametric118 Basic Raster Graphics Algorithms for Drawing 2D Primitives representation of the line segment for the point at which that segment intersects the infinite line on which the clip edge lies. Because all clip edges are in general intersected by the line, four values of 1 are calculated. A series of simple comparisons is used to determine which (if any) of the four values of ¢ correspond to actual intersections. Only then are the (x, y) values for one or two actual intersections calculated. In general, this approach saves time over the Cohen-Sutherland intersection-calculation algorithm because it avoids the repeti- tive looping needed to clip to multiple clip-rectangle edges. Also, calculations in 1D parameter space are simpler than those in 3D coordinate space. Liang and Barsky improve on Cyrus-Beck by examining each t-value as it is generated, to reject some line segments before alll four -values have been computed. The Cyrus-Beck algorithm is based on the following formulation of the intersection between two lines. Figure 3.42 shows a single edge E, of the clip rectangle and that edge’s outward normal N, (ie., outward to the clip rectangle"), as well as the line segment from P, to P, that must be clipped to the edge. Either the edge or the line segment may have to be extended to find the intersection point. As before, this line is represented parametrically as P(t) = Py + (P, — Podt, where 1 = 0 at Py and = 1 at P;. Now, pick an arbitrary point Pg, on edge E, and consider the three vectors P(0) — Pg, from Pg, to three designated points on the line from P, to P,: the intersection point to be determined, an endpoint of the line on the inside halfplane of the edge, and an endpoint on the line in the outside halfplane of the edge. We can distinguish in which region a point lies by looking at the value of the dot product N, - [P(t) — Pg]. This value is negative for a point in the inside halfplane, zero for a point on the line containing the edge, and positive for a point that lies in the outside halfplane. The definitions of inside and outside halfplanes of an edge correspond to a counterclockwise enumeration of the ‘edges of the clip region, a convention we shall use throughout this book. Now we can solve for the value of £ at the intersection of P,P, with the edge: N, > [P() — Py] = 0. First, substitute for P(2): Ny+ (Py + (Py — Pot — Next, group terms and distribute the dot product: N,* (Py — Ped +N, + [P, — Polt = 0. Let D = (P, ~ P;) be the vector from Py to P,, and solve for t: (3.1) Note that this gives a valid value of ¢ only if the denominator of the expression is nonzero. "Cyrus and Beck use inward normals, but we prefer to use outward normals for consistency with plane normals in 3D, which are outward. Our formulation therefore differs only in the testing of a sign3.12 Clipping Lines 119 Outside of clip region | Inside of clip rectangle Edge E Pi(t)— Pe, N= (P()-Pe}<0 N, (Plt) -Pe,]=0 N+ (Pt) ~Pel>0) —W Fig. 3.42 Dot products for three points outside, inside, and on the boundary of the clip region. For this to be true, the algorithm checks that N, # 0 (that is, the normal should not be 0; this could occur only as a mistake), D £0 (that is, P, # Po), N, + D # 0 (that is, the edge E, and the line from P, to P, are not parallel. If they were parallel, there can be no single intersection for this edge, so the algorithm moves on to the next case.). Equation (3.1) can be used to find the intersections between P,P, and each edge of the clip rectangle. We do this calculation by determining the normal and an arbitrary P;,—say, aan endpoint of the edge—for each clip edge, then using these values for all line segments. Given the four values of for a line segment, the next step is to determine which (if any) of the values correspond to internal intersections of the line segment with edges of the clip rectangle. As a first step, any value of 1 outside the interval (0, |] can be discarded, since it lies outside P,P,. Next, we need to determine whether the intersection lies on the clip boundary, We could try simply sorting the remaining values of 1, choosing the intermediate values of f for intersection points, as suggested in Fig. 3.43 for the case of line 1. But how do we distinguish this case from that of line 2, in which no portion of the line segment lies in the clip rectangle and the intermediate values of 1 correspond to points not on the clip boundary? Also, which of the four intersections of line 3 are the ones on the clip boundary? The intersections in Fig. 3.43 are characterized as “potentially entering”” (PE) or “potentially leaving’ (PL) the clip rectangle, as follows: If moving from Py to P, causes us to cross a particular edge to enter the edge’s inside halfplane, the intersection is PE; if it causes us to leave the edge's inside halfplane, it is PL. Notice that, with this distinction, two interior intersection points of a line intersecting the clip rectangle have opposing labels Formally, intersections can be classified as PE or PL on the basis of the angle between PoP, and Nj: Ifthe angle is less than 90°, the intersection is PL; if itis greater than 90°, itis PE, This information is contained in the sign of the dot product of N; and P,P,:120 Raster Graphics Algorithms for Drawing 2D Primitives Clip (fo | rectangle | Fig. 3.43 Lines lying diagonal to the clip rectangle. N;- D <0> PE (angle greater than 90), N,* D > 0> PL (angle less than 90), Notice that Nj D is merely the denominator of Eq. (3.1), which means that, in the process of calculating f, the intersection can be trivially categorized. With this categorization, line 3 in Fig. 3.43 suggests the final step in the process. We must choose a (PE, PL) pair that defines the clipped line. The portion of the infinite line through P,P, that is within the clipping region is bounded by the PE intersection with the largest ¢ value, which we call fy, and the PL intersection with the smallest r value, t,. The intersecting line segment is then defined by the range (t,, 1,). But because we are interested in intersecting P,P,, not the infinite line, the definition of the range must be further modified so that ¢ = 0 is a lower bound for fy and t= 1 is an upper bound for 1, What if ty > (,2 This is exactly the case for line 2. It means that no portion of PyP; is within the clip rectangle, and the entire line is rejected. Values of fy and f, that correspond to actual intersections are used to calculate the corresponding x and y coordinates. The completed algorithm for upright clip rectangles is pseudocoded in Fig. 3.44. Table 3.1 shows for each edge the values of N,, a canonical point on the edge, P,,, the vector P) ~ Pz, and the parameter r, Interestingly enough, because one coordinate of each normal is 0, we do not need to pin down the corresponding coordinate of Ps, (denoted by an indeterminate x or y). Indeed, because the clip edges are horizontal and vertical, many simplifications apply that have natural interpretations. Thus we see from the table that the numerator, the dot product N - (P, ~ P,,) determining whether the endpoint Po lies inside or outside a specified edge, reduces to the directed horizontal or vertical distance from the point to the edge. This is exactly the same quantity computed for the corresponding ‘component of the Cohen-Sutherland outcode. The denominator dot product N; * D, which determines whether the intersection is potentially entering or leaving, reduces to + dx or dy: if dxis positive, the line moves from left to right and is PE for the left edge, PL for the right edge, and so on. Finally, the parameter f, the ratio of numerator and denominator, reduces to the distance to an edge divided by dx or dy, exactly the constant of proportionality we could calculate directly from the parametric line formulation. Note that it is important to preserve the signs of the numerator and denominator instead of cancelling minus signs, because the numerator and denominator as signed distances carry information that is used in the algorithm.3.12 Clipping Lines 121 precalculate N, and select a Pp, for each edge; for (each line segment to be clipped) { it (P, == Po) line is degenerate so clip as a point; else { te = 0sty = 1s for (each candidate intersection with a clip edge) { if (Nie D!=0){ —_ /* Ignore edges parallel to line fornow */ calculate t; use sign of N; @ D to categorize as PE or PL; if (PE) te = max (te, 1); if (PL) tz = min (tr,1); } } it (te >) return NULL; ebe return P(t_) and P(t;,) as true clip intersections; t } Fig. 3.44 Pseudocode for Cyrus—Beck parametric line clipping algorithm. The complete version of the code, adapted from [LIAN84] is shown in Fig. 3.45. The procedure calls an internal function, CLIPt(), that uses the sign of the denominator to determine whether the line segment-edge intersection is potentially entering (PE) or leaving (PL), computes the parameter value of the intersection and checks to see if trivial rejection can be done because the new value of ty or f, would cross the old value of 1, oF fy, respectively. It also signals trivial rejection if the line is parallel to the edge and on the TABLE 3.1 CALCULATIONS FOR PARAMETRIC LINE CLIPPING ALGORITHM’ (Py ~ Pr) Clip edge, Normal N; Pr i= =NoD. Heft: x = Kain 1.0) ins 9) right: x = aus a, 0 Gea 9) @,-1) (, Yin) Nop: Y= Yous @, 1) Yn) ‘*The exact coordinates of the point P,, on each edge are irrelevant to the computation, so they have been denoted by variables x and y. For a point on the right edge, 1=xa4 a8 indicated in the first row, third entry.122 Basic Raster Graphics Algorithms for Drawing 2D Primitives void Clip2D (double +x0, double +0, double «x/, double +y/, boolean evisible) ‘/ Clip 2D line segment with endpoints (x0, y0) and (x, y1), against upright +! ‘+ clip rectangle with comers at (xmin, ymin) and (xmax, ymax); these are +! ‘J globals or could be passed as parameters also. The flag visible is set TRUE. +/ J+ if a clipped segment is returned in endpoint parameters. Ifthe line */ J» is rejected, the endpoints are not changed and visible is set to FALSE. +/ { double dx = sx! — #10; double dy = *y! — +0; ‘'* Output is generated only if line is inside all four edges. +/ -evisible = FALSE; ‘Me First test for degenerate line and clip the point; ClipPoint returns +/ ‘TRUE if the point lies inside the clip rectangle. »/ 0 && ClipPoint (4x0, «)0)) if (CLIPt (ds, xmin ~ +20, &1B, &L)) J+ Inside wet leftedge +/ if (CLIP: (—dx, «x0 — xmax, &tE, &tL)) Jo Inside wet right edge */ if (CLIPt (dy, ymin — ¥y0, &tE, &1L)) J» Inside wrt bottom edge +/ it (CLIPt (dy, +y0 — ymar, &1E, &tL)){ _/* Inside wrt top edge +/ visible = TRUE; /* Compute PL intersection, if 1L has moved +/ if (L<1){ ex] = 4x0 + th * dx, ay] = 90 + Le dy, /* Compute PE intersection, if t£ has moved */ if (1E>0) { x0 20 } A lip2D +/ boolean CLIPt (double denom, double num, double +t, double +21) Ju This function computes a new value of #£ or tL for an interior intersection «/ ‘i of a line segment and an edge. Parameter denom is -(N, # D), which reduces to »/ J £ Ax, Ay for upright rectangles (as shown in Table 3.1); its sign +/ J+ determines whether the intersection is PE or PL. Parameter num is N; ® (Po - Ps.) ¥/ ‘+ for a particular edge/line combination, which reduces to directed horizontal +/ J and vertical distances from Pp to an edge; its sign determines visibility +/ ‘ of Po and is used to trivially reject horizontal or vertical lines. Ifthe +/ J line segment can be trivially rejected, FALSE is returned; if it cannot be. +/ ‘/* TRUBis returned and the value of rE or tL is adjusted, if needed, for the +/ J+ portion of the segment that is inside the edge. */ 3.45 (Cont,).3.12 cli 123 { double if (denom > 0) { J+ PE imersection +/ t= num | denom; —/ Value of 1 atthe intersection +/ if (0> 1) J+ tE and tLorossover +/ return FALSE; /* so prepare to reject line »/ elseif (1 > 2) J Anew E has been found »/ iE } else if (denom <0) { /+ PLintersection +/ 1=num {denom; I+ Value of ! atthe intersection +) it (1 8) Js 1B and tL crossover +/ return FALSE; /s so prepare to reject line */ else J+ Anew tLhas been found +/ Lat elseif (num >0) _f Line on outside of edge ¥/ return FALSE; return TRUE; } i CLIPt «/ Fig. 3.45 Code for Liang—Barsky parametric line-clipping algorithm. outside; i.e., would be invisible. The main procedure then does the actual clipping by moving the endpoints to the most recent valves of fy and , computed, but only if there is a line segment inside all four edges. This condition is tested for by a four-deep nested if that checks the flags returned by the function signifying whether or not the line segment was rejected. In summary, the Cohen-Sutherland algorithm is efficient when outcode testing can be done cheaply (for example, by doing bitwise operations in assembly language) and trivial acceptance or rejection is applicable to the majority of line segments. Parametric line clipping wins when many line segments need to be clipped, since the actual calculation of the coordinates of the intersection points is postponed until needed, and testing can be done on parameter values. This parameter calculation is done even for endpoints that would have been trivially accepted in the Cohen-Sutherland strategy, however. The Liang-Barsky algorithm is more efficient than the Cyrus—Beck version because of additional trivial rejection testing that can avoid calculation of all four parameter values for lines that do not intersect the clip rectangle. For lines that cannot be trivially rejected by Cohen-Sutherland because they do not lie in an invisible halfplane, the rejection tests of Liang-Barsky are clearly preferable to the repeated clipping required by Cohen—Sutherland. The Nicholl et124 Basie Raster Graphics Algorithms for Drawing 2D Primitives al. algorithm of Section 19.1.1 is generally preferable to either Cohen-Sutherland or Liang—Barsky but does not generalize to 3D, as does parametric clipping. Speed-ups to Cohen-Sutherland are discussed in [DUVA90]. Exercise 3.29 concems instruction counting for the two algorithms covered here, as a means of contrasting their efficiency under various conditions. 3.13 CLIPPING CIRCLES AND ELLIPSES To clip a circle against a rectangle, we can first do a trivial accepUreject test by intersecting the circle's extent (a square of the size of the circle’s diameter) with the clip rectangle, using the algorithm in the next section for polygon clipping. If the circle intersects the rectangle, ‘we divide it into quadrants and do the trivial accepUreject test for each. These tests may lead in turn to tests for octants. We can then compute the intersection of the circle and the edge analytically by solving their equations simultaneously, and then scan convert the resulting ares using the appropriately initialized algorithm with the calculated (and suitably rounded) starting and ending points. If scan conversion is fast, or if the circle is not too large, it is probably more efficient to scissor on a pixel-by-pixel basis, testing each boundary pixel against the rectangle bounds before it is written. An extent check would certainly be useful in any case. If the circle is filled, spans of adjacent interior pixels on each scan line can be filled without bounds checking by clipping each span and then filling its interior pixels, as discussed in Section 3.7. To clip ellipses, we use extent testing at least down to the quadrant level, as with circles. ‘We can then either compute the intersections of ellipse and rectangle analytically and use those (suitably rounded) endpoints in the appropriately initialized scan-conversion algo- rithm given in the next section, or clip as we scan convert. 3.14 CLIPPING POLYGONS An algorithm that clips a polygon must deal with many different cases, as shown in Fig. 3.46. The case in part (a) is particularly noteworthy in that the concave polygon is clipped into two separate polygons. All in all, the task of clipping seems rather complex. Each edge of the polygon must be tested against each edge of the clip rectangle; new edges must be added, and existing edges must be discarded, retained, or divided. Multiple polygons may result from clipping a single polygon. We need an organized way to deal with all these 3.14.1. The Sutherland—Hodgman Polygon-Clipping Algorithm Sutherland and Hodgman's polygon-clipping algorithm [SUTH74b] uses a divide-and- conquer strategy: It solves a series of simple and identical problems that, when combined, solve the overall problem. The simple problem is to clip a polygon against a single infinite clip edge. Four clip edges, each defining one boundary of the clip rectangle (see Fig. 3.47), successively clip a polygon against a clip rectangle. Note the difference between this strategy for a polygon and the Cohen—Sutherland algorithm for clipping a line: The polygon clipper clips against four edges in succession, whereas the line clipper tests the outcode to see which edge is crossed, and clips only when3.14 Clipping Polygons 125 Clip rectangle ~— > > (a) (o) Cae - Et © Fig. 3.46 Examples of polygon clipping. (a) Multiple components. (b) Simple convex case. (c) Concave case with many exterior edges. necessary. The actual Sutherland-Hodgman algorithm is in fact more general: A polygon (convex or concave) can be clipped against any convex clipping polygon; in 3D, polygons can be clipped against convex polyhedral volumes defined by planes. The algorithm accepts aseries of polygon vertices v,, vp, . . ., ¥y- In 2D, the vertices define polygon edges from v; to v;,, and from v, to v,. The algorithm clips against a single, infinite clip edge and outputs another series of ‘vertices defining the clipped polygon. In a second pass, the partially clipped polygon is then clipped against the second clip edge, and so on. The algorithm moves around the polygon from v, to v, and then on back to v,, at each step examining the relationship between successive vertices and the clip edge. At each step, Clip rectangle ; Right cle (@ (b) Bottom of ke ee 0 boundary S) e) Fig. 3.47 Polygon clipping, edge by edge. (a) Before clipping. (b) Clip on right. {¢) Clip on bottom. (d) Clip on left. (e) Clip on top; polygon is fully clipped.126 Basic Raster Graphics Algorithms for Drawing 2D Primitives zero, one, Or two vertices are added to the output list of vertices that defines the clipped polygon, Four possible cases must be analyzed, as shown in Fig, 3.48. Let's consider the polygon edge from vertex s to vertex p in Fig. 3.48. Assume that start point s has been dealt with in the previous iteration. In case 1, when the polygon edge is completely inside the clip boundary, vertex p is added to the output list. In case 2, the intersection point iis output as a vertex because the edge intersects the boundary. In case 3, both vertices are outside the boundary, so there is no output. In case 4, the intersection point i and p are both added to the output list. Function SutherlandHodgmanPolygonClip( ) in Fig. 3.49 accepts an array inVertex- Array of vertices and creates another array outVertexArray of vertices. To keep the code simple, we show no error checking on array bounds, and we use the function Output( ) to place a vertex into outVertexArray. The function Intersect( ) calculates the intersection of the polygon edge from vertex s to vertex p with clip Boundary, which is defined by two vertices on the clip polygon’s boundary. The function Inside( ) returns true if the vertex is ‘on the inside of the clip boundary, where “‘inside"* is defined as “to the left of the clip boundary when one looks from the first vertex to the second vertex of the clip boundary."” This sense corresponds to a counterclockwise enumeration of edges. To calculate whether a point lies outside a clip boundary, we can test the sign of the dot product of the normal to the clip boundary and the polygon edge, as described in Section 3.12.4. (For the simple case of an upright clip rectangle, we need only test the sign of the horizontal or vertical distance to its boundary.) ‘Sutherland and Hodgman show how to structure the algorithm so that it is reentrant {SUTH74b]. As soon as a vertex is output, the clipper calls itself with that vertex. Clipping is performed against the next clip boundary, so that no intermediate storage is necessary for the partially clipped polygon: In essence, the polygon is passed through a “‘pipeline”” of clippers. Each step can ve implemented as special-purpose hardware with no intervening. buffer space. This property (and its generality) makes the algorithm suitable for today’s hardware implementations. In the algorithm as it stands, however, new edges may be introduced on the border of the clip rectangle, Consider Fig. 3.46 (a}—a new edge is introduced by connecting the left top of the triangle and the left top of the rectangle. A Inside | Outside Inside | Outside Inside | Outside Inside | Outside i: frst p: second output output > 8 s wan, ing clipped Pp s Clip * p:output | boundary ‘output Case 1 Case 2 Case 3 Case 4 (no output) Fig. 3.48 Four cases of polygon clipping3.15 Generating Characters 127 postprocessing phase can eliminate these edges, as discussed in Chapter 19, A polygon- clipping algorithm based on the parametric-line representation for clipping to upright rectangular clip regions is discussed, along with the Weiler algorithm for clipping polygons to polygons, in Section 19.1. 3.15 GENERATING CHARACTERS 3.15.1 Defining and Clipping Characters There are two basic techniques for defining characters. The most general but most computationally expensive way is to define each character as a curved or polygonal outline and to scan convert it as needed. We first discuss the other, simpler way, in which each character in a given font is specified as a small rectangular bitmap. Generating a character then entails simply using a copyPixel to copy the character’s image from an offscreen canvas, called a font cache, into the frame buffer at the desired position. ‘The font cache may actually be in the frame buffer, as follows. In most graphics systems in which the display is refreshed from a private frame buffer, that memory is larger than is strictly required for storing the displayed image. For example, the pixels for a ular screen may be stored in a square memory, leaving a rectangular strip of invisible"’screen memory. Alternatively, there may be enough memory for two screens, ‘one of which is being refreshed and one of which is being drawn in, to double-buffer the image. The font cache for the currently displayed font(s) is frequently stored in such invisible screen memory because the display controller's copyPixel works fastest within local image memory. A related use for such invisible memory is for saving screen arcas temporarily obscured by popped-up images, such as windows, menus, and forms. ‘The bitmaps for the font cache are usually created by scanning in enlarged pictures of characters from typesetting fonts in various sizes; a typeface designer can then use a paint program to touch up individual pixels in each character’s bitmap as necessary. Alternative- ly, the type designer may use a paint program to create, from scratch, fonts that are especially designed for screens and low-resolution printers. Since small bitmaps do not scale well, more than one bitmap must be defined for a given character in a given font just to provide various standard sizes. Furthermore, each type face requires its own set of bitmaps. Therefore, a distinct font cache is needed for each font loaded by the application, Bitmap characters are clipped automatically by SRGP as part of its implementation of copyPixel. Each character is clipped to the destination rectangle on a pixel-by-pixel basis, a technique that lets us clip a character at any row or column of its bitmap. For systems with slow copyPixel operations, a much faster, although cruder, method is to clip the character or even the entire string on an all-or-nothing basis by doing a trivial accept of the character or string extent. Only if the extent is trivially accepted is the copyPixel applied to the character or string. For systems with a fast copyPixel, it is still useful to do trivial accepU/reject testing of the string extent as a precursor to clipping individual characters during the copyPixel operation. SRGP’s simple bitmap font-cache technique stores the characters side by side in a canvas that is quite wide but is only as tall as the tallest character; Fig. 3.50 shows a portion132 Basic Raster Graphics Algorithms for Drawing 2D Primitives 3.16 SRGP_copyPixel If only WritePixel and ReadPixel low-level procedures are available, the SRGP_copyPixel procedure can be implemented as a doubly nested for loop for each pixel. For simplicity, assume first that we are working with a bilevel display and do not need to deal with the Iow-level considerations of writing bits that are not word-aligned; in Section 19.6, we cover some of these more realistic issues that take hardware-memory organization into account. In the inner loop of our simple SRGP_copyPixel, we do a ReadPixel of the source and destination pixels, logically combine them according to the SRGP write mode, and then WritePixel the result. Treating replace mode, the most common write mode, as a special case allows a simpler inner loop that does only a ReadPixel/ WritePixel of the source into the destination, without having to do a logical operation. The clip rectangle is used during address calculation to restrict the region into which destination pixels are written. 3.17 ANTIALIASING 3.17.1 Increasing Resolution ‘The primitives drawn so far have a common problem: They have jagged edges. This undesirable effect, known as the jaggies or staircasing, is the result of an all-or-nothing approach to scan conversion in which cach pixel either is replaced with the primitive’s color or is left unchanged. Jaggies are an instance of a phenomenon known as aliasing. The application of techniques that reduce or eliminate aliasing is referred to as antialiasing and primitives or images produced using these techniques are said to be antialiased. In Chapter 14, we discuss basic ideas from signal processing that explain how aliasing got its name, why it occurs, and how to reduce or eliminate it when creating pictures. Here, we content ourselves with a more intuitive explanation of why SRGP's primitives exhibit aliasing, and describe how to modify the line scan-conversion algorithm developed in this chapter to generate antialiased lines. Consider using the midpoint algorithm to draw a I-pixel-thick black line, with slope between 0 and 1, on a white background, In each column through which the line passes, the algorithm sets the color of the pixel that is closest to the line. Each time the line moves between columns in which the pixels closest to the line are not in the same row, there is a sharp jag in the line drawn into the canvas, as is clear in Fig. 3.54(a). The same is true for other scan-converted primitives that can assign only one of two intensity values to pixels. ‘Suppose we now use a display device with twice the horizontal and vertical resolution. 3.54 (b), the line passes through twice as many columns and therefore has twice as many jags, but each jag is half as large in x and in y. Although the resulting picture looks better, the improvement comes at the price of quadrupling the memory cost, memory bandwidth, and scan-conversion time. Increasing resolution is an expensive solution that only diminishes the problem of jaggies—it does not eliminate the problem. In the following sections, we look at antialiasing techniques that are less costly, yet result in significantly beiter images. 17.2 __Unweighted Ar. ‘The first approach to improving picture quality can be developed by recognizing that, although an ideal primitive such as the line has zero width, the primitive we are drawing has Sampling3.17 Antialiasing 133 a (b) Fig. 3.54 (a) Standard midpointline on a bilevel display. (b) Same line on adisplay that has twice the linear resolution. nonzero width. A scan-converted primitive occupies a finite area on the screen—even the thinnest horizontal or vertical line on a display surface is 1 pixel thick and lines at other angles have width that varies over the primitive. Thus, we think of any line as a rectangle of a desired thickness covering a portion of the grid, as shown in Fig. 3.55. It follows that a line should not set the intensity of only a single pixel in a column to black, but rather should contribute some amount of intensity to each pixel in the columns whose area it intersects. (Such varying intensity can be shown on only those displays with multiple bits per pixel, of course.) Then, for I-pixel-thick lines, only horizontal and vertical lines would affect exactly 1 pixel in their column or row. For lines at other angles, more than I pixel would now be set in a column or row, each to an appropriate intensity. But what is the geometry of a pixel? How large is it? How much intensity should a line Contribute to each pixel it intersects? It is computationally simple to assume that the pixels form an array of nonoverlapping square tiles covering the screen, centered on grid points. (When we refer to a primitive overlapping all or a portion of a pixel. we mean that it covers (part of) the tile; to emphasize this we sometimes refer to the square as the area represented by the pixel.) We also assume that a line contributes to each pixel’s intensity an amount o 1 2 3 4 5 6 7 8 9 0 Figure 3.55 Line of nonzero width from point (1,1) to point (10,4).134 Basic Raster Graphics Algorithms for Drawing 2D Primitives proportional to the percentage of the pixel’s tile it covers. A fully covered pixel on a black and white display will be colored black, whereas a partially covered pixel will be colored a gray whose intensity depends on the line's coverage of the pixel. This technique, as applied to the line shown in Fig. 3.55, is shown in Fig. 3.56. For a black line on a white background, pixel (2, 1) is about 70 percent black, whereas pixel (2, 2) is about 25 percent black. Pixels not intersected by the line, such as (2, 3), are completely white. Setting a pixel’s intensity in proportion to the amount of its area covered by the primitive softens the harsh, on—off characteristic of the edge of the primitive and yields a more gradual transition between full on and full off, This blurring makes a line look better at a distance, despite the fact that it spreads the on-off transition over multiple pixels. {ina column or row. A rough approximation to the area overlap can be found by dividing the pixel into a finer grid of rectangular subpixels, then counting the number of subpixels inside the line—for example, below the line’s top edge or above its bottom edge (see Exercise 3.32). We call the technique of setting intensity proportional to the amount of area covered unweighted area sampling. This technique produces noticeably better results than does setting pixels to full intensity or zero intensity, but there is an even more effective strategy called weighted area sampling. To explain the difference between the two forms of area sampling, we note that unweighted area sampling has the following three properties. First, the intensity of a pixel intersected by a line edge decreases as the distance between the pixel center and the edge increases: The farther away a primitive is, the less influence it has on a pixe!’s intensity. This relation obviously holds because the intensity decreases as the area of overlap decreases, and that area decreases as the line’s edge moves away from the pixel’s center and toward the boundary of the pixel. When the line covers the pixel completely, the overlap area and therefore the intensity are at a maximumy; when the primitive edge is just tangent to the boundary, the area and therefore the intensity are zero. A second property of unweighted area sampling is that a primitive cannot influence the intensity at a pixel at all if the primitive does not intersect the pixel—that is, if it does not intersect the square tile represented by the pixel. A third property of unweighted area On, Hi Sich Sa bea Baadiend? 6 lo) Hor 44 Fig. 3.56 Intensity proportional to area covered.3.17 Antialiasing = 135. sampling is that equal areas contribute equal intensity, regardless of the distance between the pixel’s center and the area; only the total amount of overlapped area matters. Thus, a small area in the corner of the pixel contributes just as much as does an equal-sized area near the pixel’s center. 3.17.3. Weighted Area Sampling In weighted area sampling, we keep unweighted area sampling’ first and second properties (intensity decreases with decreased area overlap, and primitives contribute only if they overlap the area represented by the pixel), but we alter the third property. We let equal areas Contribute unequally: A small area closer to the pixel center has greater influence than does one at a greater distance. A theoretical basis for this change is given in Chapter 14, where we discuss weighted area sampling in the context of filtering theory. ‘To retain the second property, we must make the following change in the geometry of the pixel. In unweighted area sampling, if an edge of a primitive is quite close to the boundary of the square tile we have used to represent a pixel until now, but does not actually intersect this boundary, it will not contribute to the pixel’s intensity. In our new approach, the pixel represents a circular area larger than the square tile; the primitive will intersect this larger area; hence, it will contribute to the intensity of the pixel. To explain the origin of the adjectives unweighted and weighted, we define a weighting function that determines the influence on the intensity of a pixel of a given small area dA of 4 primitive, as a function of dA’s distance from the center of the pixel. This function is constant for unweighted area sampling, and decreases with increasing distance for weighted area sampling. Think of the weighting function as a function, W(x, y), on the plane, whose height above the (x, y) plane gives the weight for the area dA at (x, y). For unweighted area sampling with the pixels represented as square tiles, the graph of W is a box, as shown in Fig. 3.57. Fig. 3.57 Box filter for square pixel.136 Basic Raster Graphics Algorithms for Drawing 2D Primitives The figure shows square pixels, with centers indicated by crosses at the intersections of arid lines; the weighting function is shown as a box whose base is that of the current pixel. The intensity coniributed by the area of the pixel covered by the primitive is the total of intensity contributions from all small areas in the region of overlap between the primitive and the pixel. The intensity contributed by each small area is proportional to the area multiplied by the weight. Therefore, the total intensity is the integral of the weighting function over the area of overlap, The volume represented by this integral, Ws, is always a fraction between O and 1, and the pixel’s intensity I is Iy,, “ Ws. In Fig. 3.57, Ws is a wedge of the box. The weighting function is also called a filter function, and the box is also called a box filter. For unweighted area sampling, the height of the box is normalized to 1. so that the box’s volume is 1, which causes a thick line covering the entire pixel to have an intensity 1 Iya? 1 = Tax Now let us construct a weighting function for weighted area sampling; it must give less weight to small areas farther away from the pixel center than it does to those closer. Let's pick a weighting function that is the simplest decreasing function of distance; for example, we choose a function that has a maximum at the center of the pixel and decreases linearly with increasing distance from the center. Because of rotational symmetry, the graph of this, function forms a circular cone. The circular base of the cone (often called the support of the filter) should have a radius larger than you might expect; the filtering theory of Chapter 14 shows that a good choice for the radius is the unit distance of the integer grid. Thus, a primitive fairly far from a pixel’s center can still influence that pixel’s intensity; also, the supports associated with neighboring pixels overlap, and therefore a single small piece of a primitive may actually contribute to several different pixels (see Fig. 3.58 ). This overlap also ensures that there are no areas of the grid not covered by some pixel, which would be the case if the circular pixels had a radius of only one-half of a grid unit."® ‘As with the box filter, the sum of all intensity contributions for the cone filter is the volume under the cone and above the intersection of the cone’s base and the primitive; this volume Ws is a vertical section of the cone, as shown in Fig. 3.58. As with the box filter, the height of the cone is first normalized so that the volume under the entire cone is 1; this allows a pixel whose support is completely covered by a primitive to be displayed at maximum intensity. Although contributions from areas of the primitive far from the pixel’s center but still intersecting the support are rather small, a pixel whose center is sufficiently close to a line receives some intensity contribution from that line. Conversely, a pixel that, in the square-geometry model, was entirely covered by a line of unit thickness" is not quite as bright as it used to be. The net effect of weighted area sampling is to decrease the contrast between adjacent pixcls, in order to provide smoother transitions. In particular, with weighted area sampling, a horizontal or vertical line of unit thickness has more than 1 pixel 4s noted in Section 3.2.1, pixels displayed on a CRT are roughly circular in cross-section, and adjacent pixels typically overlap; the model of overlapping circles used in weighted area sampling, however, is not directly retated (0 this fact and holds even for display technologies, such as the plasma panel, in which the physical pixels are actually nonoverlapping square tiles. We now say a “a line of unit thickness” rather than “‘a line 1 pixel thick” to make it clear that the unit of line width is still that of the SRGP grid, whereas the pixel’s support has grown to have a two-unit diameter.
You might also like
Basic Raster Algorithms
PDF
No ratings yet
Basic Raster Algorithms
20 pages
Basic Raster Graphics Algorithms For 2D Drawing: Materi 02 - Komputer Grafik
PDF
No ratings yet
Basic Raster Graphics Algorithms For 2D Drawing: Materi 02 - Komputer Grafik
36 pages
Unit 1b, 2,3
PDF
No ratings yet
Unit 1b, 2,3
117 pages
Unit 1 Primitive Section
PDF
No ratings yet
Unit 1 Primitive Section
113 pages
Scan Conversion
PDF
No ratings yet
Scan Conversion
11 pages
Chapter 3, Foley
PDF
No ratings yet
Chapter 3, Foley
85 pages
CG Unit Ii
PDF
No ratings yet
CG Unit Ii
21 pages
Computer Graphics
PDF
No ratings yet
Computer Graphics
263 pages
Unit 2 - Scan-Conversion of Graphics Primitives
PDF
No ratings yet
Unit 2 - Scan-Conversion of Graphics Primitives
31 pages
Output Primitives
PDF
No ratings yet
Output Primitives
74 pages
Computer Graphics Chapter-3
PDF
No ratings yet
Computer Graphics Chapter-3
50 pages
Unit Ii
PDF
No ratings yet
Unit Ii
44 pages
Midpoint
PDF
No ratings yet
Midpoint
25 pages
CG Unit 1 5 Notes
PDF
No ratings yet
CG Unit 1 5 Notes
173 pages
Graphics Lecture 02
PDF
No ratings yet
Graphics Lecture 02
24 pages
Lec 26
PDF
No ratings yet
Lec 26
38 pages
Computer Graphics Notes
PDF
No ratings yet
Computer Graphics Notes
166 pages
CG Unit 1 5 Notes
PDF
100% (1)
CG Unit 1 5 Notes
173 pages
CGIP - Mod1 - PPT - 3 (Line, Circ Algo)
PDF
No ratings yet
CGIP - Mod1 - PPT - 3 (Line, Circ Algo)
61 pages
CG 2
PDF
No ratings yet
CG 2
13 pages
Lec2 CG
PDF
No ratings yet
Lec2 CG
15 pages
Algorithm
PDF
No ratings yet
Algorithm
22 pages
Scan Conversion: Line Circle
PDF
No ratings yet
Scan Conversion: Line Circle
58 pages
CG - 03 - Output Primitives - 2021#1 - Updated
PDF
No ratings yet
CG - 03 - Output Primitives - 2021#1 - Updated
30 pages
UNIT 1 Notes
PDF
No ratings yet
UNIT 1 Notes
17 pages
CG Unit-2
PDF
No ratings yet
CG Unit-2
24 pages
UNIT 1 PPT
PDF
No ratings yet
UNIT 1 PPT
183 pages
02.ScanConversion MCA
PDF
No ratings yet
02.ScanConversion MCA
101 pages
Computer Graphics Anna University Local Author
PDF
No ratings yet
Computer Graphics Anna University Local Author
173 pages
UNIT2
PDF
No ratings yet
UNIT2
24 pages
CG
PDF
No ratings yet
CG
19 pages
DDA Circle and Ellipse Algorithm
PDF
No ratings yet
DDA Circle and Ellipse Algorithm
71 pages
Computer Graphics: Unit - I O P: P L
PDF
No ratings yet
Computer Graphics: Unit - I O P: P L
42 pages
CG Unit 1 5 Notes
PDF
No ratings yet
CG Unit 1 5 Notes
352 pages
Unit - 1: Father of Computer Graphics
PDF
No ratings yet
Unit - 1: Father of Computer Graphics
118 pages
Line Algorithm
PDF
No ratings yet
Line Algorithm
62 pages
CG Notes All Units
PDF
No ratings yet
CG Notes All Units
172 pages
Lecture O4 Scan Conversion A Line
PDF
No ratings yet
Lecture O4 Scan Conversion A Line
8 pages
Basic Raster Graphics Algorithms For 2D Drawing: Materi 02 - Komputer Grafik-2018/2019 - 3
PDF
No ratings yet
Basic Raster Graphics Algorithms For 2D Drawing: Materi 02 - Komputer Grafik-2018/2019 - 3
36 pages
CG Unit 1 Notes
PDF
No ratings yet
CG Unit 1 Notes
84 pages
Topic Scan Conversion: CSE5280 - Computer Graphics
PDF
No ratings yet
Topic Scan Conversion: CSE5280 - Computer Graphics
21 pages
Brown University Department of Computer Science Master's Project CS-89-M6
PDF
No ratings yet
Brown University Department of Computer Science Master's Project CS-89-M6
68 pages
Chapter 2
PDF
No ratings yet
Chapter 2
53 pages
Computer Graphics: Geometry and Line Generation
PDF
No ratings yet
Computer Graphics: Geometry and Line Generation
5 pages
From Vertices To Fragments: Rasterization: Frame Buffer
PDF
No ratings yet
From Vertices To Fragments: Rasterization: Frame Buffer
22 pages
Complex Objects, Such As Trees and Terrain or Furniture and Wals, Positioned at
PDF
No ratings yet
Complex Objects, Such As Trees and Terrain or Furniture and Wals, Positioned at
5 pages
557 - Chapter 2 - Graphics Primitives
PDF
No ratings yet
557 - Chapter 2 - Graphics Primitives
17 pages
GIP Unit - 2
PDF
No ratings yet
GIP Unit - 2
18 pages
CG - Chapter - 2 - Scan Conversation
PDF
No ratings yet
CG - Chapter - 2 - Scan Conversation
10 pages
Output Primitives (Rasterization)
PDF
No ratings yet
Output Primitives (Rasterization)
30 pages
Bresenham Algorithm: Implementation and Analysis in Raster Shape
PDF
No ratings yet
Bresenham Algorithm: Implementation and Analysis in Raster Shape
10 pages
An Algorithm For Line Drawing Using Parametric Equation PDF
PDF
No ratings yet
An Algorithm For Line Drawing Using Parametric Equation PDF
8 pages
Chapter 3 Scan Conversion
PDF
No ratings yet
Chapter 3 Scan Conversion
24 pages
Computer Graphics
PDF
No ratings yet
Computer Graphics
16 pages
CG1
PDF
No ratings yet
CG1
8 pages
Scan Conversion: DDA Algorithm
PDF
No ratings yet
Scan Conversion: DDA Algorithm
4 pages
Output Primitives
PDF
No ratings yet
Output Primitives
20 pages
An Efficient Line Algorithm
PDF
No ratings yet
An Efficient Line Algorithm
3 pages