Chapter 6: Drawing Shapes and Polygons
Building upon basic line and circle drawing, we can now construct more complex geometric shapes.
Rectangles and Squares
Rectangles are the simplest polygons. A rectangle is defined by two points: the top-left corner and the bottom-right corner .
- Outline: Draw four lines:
- to
- to
- to
- to
- Filled: Iterate through every from to and draw a horizontal line from to .
Polygons
A polygon is a closed 2D shape with straight sides. It is defined by a list of vertices: .
Convex vs. Concave Polygons
- Convex: Any line segment connecting two internal points stays entirely inside the polygon. All internal angles are less than 180°.
- Concave: At least one line segment between two internal points passes outside the polygon. At least one internal angle is greater than 180°.
Filling Shapes: The Scanline Approach
Filling a polygon is the process of identifying which pixels lie within its boundaries. The most common technique is the Scanline Fill Algorithm.
- Find the minimum and maximum values of the polygon to define the range of scanlines.
- For each scanline :
- Find the intersection points of the scanline with all edges of the polygon.
- Sort the intersection points by their coordinates.
- Fill the pixels between pairs of intersection points (e.g., between the 1st and 2nd, the 3rd and 4th, etc.).
Handling Special Cases
- Vertices: If a scanline passes through a vertex, it could count as one or two intersections. A common rule is to count it as one intersection if it's a local minimum or maximum, and two otherwise.
- Horizontal Edges: These can be ignored during the intersection calculation as the scanline will handle them.
Even-Odd Rule and Winding Number
To determine if a point is "inside" a complex, self-intersecting polygon, we use mathematical rules.
Even-Odd Rule
- Draw a ray from the point to infinity in any direction.
- Count the number of times the ray crosses an edge of the polygon.
- If the number is odd, the point is inside. If even, it's outside.
Winding Number
- Initialize a counter to zero.
- Draw a ray from the point.
- Every time an edge crosses the ray from left-to-right, add 1.
- Every time an edge crosses from right-to-left, subtract 1.
- If the final number is non-zero, the point is inside.
Summary
Moving from lines to shapes introduces the need for robust filling algorithms. The scanline approach is a powerful and general-purpose method for rasterizing any polygon, while the even-odd and winding number rules provide the logic necessary for handling complex, overlapping geometries.