What is the endpoint calculation in the Xiaolin Wu algorithm doing? - graphics

The Xiaolin Wu algorithm draws an anti-aliased line between two points. The points can be at sub-pixel, i.e. non-integer coordinates. I'll assume the reader is familiar with the algorithm and just recall the important features. We loop across the major (longer) axis of the line, let's say it's the x-axis, basically proceeding column-by-column. In each column we color two pixels. The computation is equivalent to this: place a 1x1 square centered on the line, at the point whose x coordinate is the center of the the given column of pixels. Let's call it S. If we think of each pixel as a 1x1 square in the plane, we now calculate the area of intersection between S and each of the two pixels it straddles, and use those areas as the intensities with which to color each pixel.
That's nice and clear, but what is going on with the calculations for the endpoints? Because the endpoints can be at non-integer positions, they have to be treated as a special case. Here's the pseudocode from the linked Wikipedia article for handling the first endpoint x0, y0:
// handle first endpoint
xend := round(x0)
yend := y0 + gradient * (xend - x0)
xgap := rfpart(x0 + 0.5)
xpxl1 := xend // this will be used in the main loop
ypxl1 := ipart(yend)
plot(ypxl1, xpxl1, rfpart(yend) * xgap)
plot(ypxl1+1, xpxl1, fpart(yend) * xgap)
I edited out the if (steep) condition, so this is the code for the case when the slope of the line is less than 1. rfpart is 1-fpart, and fpart is the fractional part. ipart is the integer part.
I just have no idea what this calculation is supposed to be doing, and I can't find any explanations online. I can see that yend is the y-coordinate of the line above xend, and xend is the x coordinate of the pixel that the starting point (x0, y0) is inside of. Why are we even bothering to calculate yend? It's as if we're extending the line until the nearest integer x-coordinate.
I realize that we're coloring both the pixel that the endpoint is in, and the pixel either immediately above or below it, using certain intensities. I just don't understand the logic behind where those intensities come from.

With the Xiaolin Wu algorithm (and sub-pixel rendering techniques in general) we imagine that the screen is a continuous geometric plane, and each pixel is a 1x1 square region of that plane. We identify the centers of the pixels as being the points with integer coordinates.
First, we find the so-called "major axis" of the line, the axis along which the line is longest. Let's say that it's the x axis. We now loop across each one-pixel-wide column that the line passes through. For each column, we find the point on the line which is at the center of that column, i.e. such that the x-axis is an integer. We imagine there's a 1x1 square centered at that point. That square will completely fill the width of that column and will overlap two different pixels. We color each of those pixels according to the area of the overlap between the square and the pixel.
For the endpoints, we do things slightly differently: we still draw a square centered at the place where the line crosses the centerline of the column, but we cut that square off in the horizontal direction at the endpoint of the line. This is illustrated below.
This is a zoomed-in view of four pixels. The black crosses represent the centers of those pixels, and the red line is the line we want to draw. The red circle (x0, y0) is the starting point for the line, the line should extend from that point off to the right.
You can see the grey squares centered on the red crosses. Each pixel is going to be colored according to the area of overlap with those squares. However, in the left-hand column, we cut-off the square at x-coordinate x0. In light grey you can see the entire square, but only the part in dark grey is used for the area calculation. There are probably other ways we could have handled the endpoints, for instance we could have shifted the dark grey region up a bit so it's vertically centered at the y-coordinate y0. Presumably it doesn't make much visible difference, and this is computationally efficient.
I've annotated the drawing using the names of variables from the pseudocode on Wikipedia.

The algorithm is approximate at endpoints. This is justified because exact computation would be fairly complex (and depend on the type of endpoint), for a result barely perceivable. What matters is aliasing along the segment.

Related

How to calculate overlapping area of a pixel and a line going through it?

I have two endpoint of a line segment. I calculated the pixels to be colored using Mid Point Line algorithm. Now, I want to apply unweighted antialiasing to those pixels which provides the intensity of a pixel based on the area overlapping of that pixel and line.
I am asking for suggestions on how to find out those percentage of overlapping area?
It is not necessary that pixels are to be considered as rectangle only.

Given two curves(both formed of certain points),firgure out point count of one curve over another

As the pic show, both curves are of spline line, and have limited points. I want to figure out the count of green points. Is there any idea?
I assume the black curve is x-monotone (otherwise the "one above the other" term can be ambiguous).
A simple approach is to consider the black curve as a polygonal line and for each point p on the red curve find the point q on the polygonal line with the same x-coordinate. Then the green points are those p that have a larger y-coordinate than their corresponding q.
Finding the point q corresponding to a given p amounts to going over the segments of the polygonal line and identifying segments that have one endpoint with smaller x-coordinate and the other with larger. Once you have such a segment the y-value of q is just a linear interpolation.
Since the polygonal line is x-monotone, the x-coordinates of the points are sorted. Therefore, the search for the corresponding segments can be done efficiently using logarithmic binary-search.

Is there a simple algorithm that can find the envelope of several circles?

Given a number of points on a 2d surface and radiuses for these points I can easily paint circles for them. What I need is an algorithm that only paints the envelope (right word for what I am looking for?) or outer bound of these combined circles. Additionally a second set of circles can 'encroach' on these circles, resulting in a kind of 'border'.
Image of what I am looking for
A quick way to draw the outline of the union of the disks is to
fill all disks in yellow, then
fill all disks in white with a smaller radius.
This can be adapted to the "encroached" circles, provided you only fill the remaining portions of the disks. Unfortunately, in a general setting finding the remaining portions can be an uneasy geometric problem.
There is an alternative approach which can work in all cases:
fill an image with zeroes, then for all disks fill every pixel with the value of the distance to the circumference (maximum at the center), but only keep the highest value so far.
while you do this, fill a second image with the color of the disk that achieved that highest value. (Initialize the image with the background color.)
At the end of this process, the first image will represent a "terrain" made of intersecting cones; and for every point of the terrain, you will know the color.
finally, color the pixels that have a height smaller than the desired stroke width, using the color map.
You can do the drawing in two steps.
1) Draw the outline using the following method: For each point, draw a circle using your favorite circle-drawing method, but before drawing a pixel, ensure that it is not contained inside any other circle. Do this for every point and you will get your outline.
2) Draw the borders between different sets using the following method: For each pair of points from different sets, calculate the two intersection points of the circles. If there is an intersection, the border can be drawn as a segment joining these two points. However, you have to make two lines, one for circle A, and another for circle B. To draw the line for circle A, slightly offset the segment towards point A. Then, use your favorite line-drawing method, but before drawing a pixel, ensure that it is closer to point A that any other point of the opposite set. After drawing the line, repeat the process for circle B. Note that both segment are not guaranteed to be the same length since the asymmetry of the points of the different sets. It will, however, always form a closed shape when all outlines and borders are drawn.

How to calculate what percentage of a pixel is within the bounds of a shape

I have a 2d grid where pixel centers are at the intersection of two half-grid lines, as shown below.
I also have a shape that is drawn on this grid. In my case the shape is a glyph, and is described by segments. Each segment has a start point, end point and a number of off-curve points. These segments can be quadratic curves or lines. What's important is that I can know the points and functions that make up the outline of the shape.
The rule for deciding which pixels should be turned on is simple: if the center of the pixel falls within the shape outline, turn that pixel on. The following image shows an example of applying this rule.
Now the problem I'm facing has to do with anti aliasing. What I'd like to do is to calculate what percentage of the area of a given pixel falls within the outline. As an example, in the image above, I've drawn a red square around a pixel that would be about 15% inside the shape.
The purpose of this would be so that I can then turn that pixel on only by 15% and thus get some cleaner edges for the final raster image.
While I was able to find algorithms for determining if a given point falls within a polygon (ray casting), I wasn't able to find anything about this type of problem.
Can someone can point me toward some algorithms to achieve this? Also let me know if I'm going about this problem in the wrong way!
This sounds like an X, Y problem.
You are asking for a way to calculate the perecentage of pixel coverage, but based on your question, it sounds that what you want to do is anti alias a polygon.
If you are working only with single color 2D shapes (i.e red, blue, magenta... squares, lines, curves...) A very simple solution is to create your image and blur the result afterwards.
This will automatically give you a smooth outline and is simple to implement in many languages.

fast calculation of the intersection area of a triangle and the unit square

In my current project I need to calculate the intersection area of triangles and the unit squares in an infinite grid.
For every triangle (given by three pairs of floating point numbers) I need to know the area (in the interval (0,1]) it has in common with every square it intersects.
Right now I convert both (the triangle and the square) to polygons and use Sutherland-Hodgman polygon clipping to calculate the intersection polygon, which I then use to calculate its area.
This approach now shows to be a performance bottleneck in my application. I guess a more specialized (analytical) algorithm would be much faster. Is there a standard solution for this problem, or do you have any idea? I only need the areas, not the shape of the intersections.
Your polygon are convex. There are some algorithms for convex polygons faster than general ones. I've used O'Rourke algorithm with success (code from his book here, I believe that good description exists). Note that some values may be precomputed for your squares.
If your polygons not always intersect, then you may at first check the fact of intersection with separating axes method.
Another option to try- Liang-Barski algorithm for clipping every triangle edge by square.
Edit: You can quickly find all intersections of triangle edges with grid using algorthm of Amanatides and Woo (example in grid traversal section here)
To process this task with hi performance , i suggest some modifications of
Vatti line sweep clipping.
http://en.wikipedia.org/wiki/Vatti_clipping_algorithm
Stepping from minimal Y vertex of your Triangle make such steps:
sort vertexes by Y coordinate
step Y higher to MIN(nextVertex.Y, nextGridBottom)
Calculate points of intersection of grid with edges.
Collect current trapezoid
repeat from step2 until vertex with highest Y coordinate.
Split trapezoids by X coordinate if required.
here is example of Trapezoidalization in X direction
http://www.personal.kent.edu/~rmuhamma/Compgeometry/MyCG/PolyPart/polyPartition.htm
It illustrate main idea of line sweep algorithm. Good luck.
You are not mentioning what precision you are looking for. In case you are looking for a analytical method, disregard this answer, but if you just want to do antialiasing I suggest a scanline edge-flag algorithm by Kiia Kallio. I have used it a few times and it is quite fast and can be set up for very high precision. I have a java implementation if you are interested.
You can take advantage of the regular pattern of squares.
I'm assuming the reason this is a bottleneck is because you have to wait while your algorithm finds all squares intersecting any of the triangles and computes all the areas of intersection. So we'll compute all the areas, but in batches for each triangle in order to get the most information from the fewest calculations.
First, as explained by others, for each edge of the triangle, you can find the sequence of squares that edge passes through, as well as the points at which it crosses each vertical or horizontal edge of a square.
Do this for all three sides, keeping a list of all the squares you encounter, but keep only one copy of each square. It may be useful to store the squares in multiple lists, so that all squares on a given row are all kept in the same list.
When you've found all squares the triangle's edges pass through, if two of those squares were on the same row, any squares between those two that are not in the list are completely inside the triangle, so 100% of each of those squares is covered.
For the other squares, the calculation of area can depend on how many vertices of the triangle are in the square (0, 1, 2, or 3) and where the edges of the triangle intersect the sides of the square. You can summarize all the cases in a few pencil-and-paper drawings, and come up with calculations for each one. For example, when an edge of triangle crosses two sides of the square, with one corner of the square on the "outside" side of the edge, that corner is one angle of a small triangle "cut off" by that edge of the larger triangle; use the points of intersection on the square's sides to compute the area of the small triangle and deduct it from the area of the square. If two points instead of one are "outside", you have a trapezoid whose two base lengths are found from the points of intersection, and whose height is the width of the square; deduct its area from the square. If three points are outside, deduct the entire area of the square and then add the area of the small triangle.
One vertex of the large triangle inside the square, three corners of the square outside that angle: draw a line from the remaining corner to the triangle's vertex, so you have two small triangles, deduct the entire square and add those triangles' areas. Two corners of the square outside the angle, draw lines to the vertex to get three small triangles, etc.
I'm phrasing this so that you always assume you start with the entire area of the square and reduce the area by some amount depending on how the edge of the triangle intersects the square. That way, in the case where the edges of the triangle intersect the square more than twice--such as one edge cuts across one corner of the square and another edge cuts across a different corner, you can just deduct the area cut off by the first edge, then deduct the area cut off by the second edge.
This will be a considerable number of special cases, though you can take advantage of symmetry; for example, you don't have to write the complete calculation for "cut off a triangle in one corner" four times.
You'll write a lot more code than if you just took someone's convex-polygon library off the shelf, and you will want to test the living daylights out of it to make sure you didn't forget to code any cases, but once you get it working, it shouldn't take much more effort to make it reasonably fast.

Resources