|
|||||||||||||
АвтоАвтоматизацияАрхитектураАстрономияАудитБиологияБухгалтерияВоенное делоГенетикаГеографияГеологияГосударствоДомДругоеЖурналистика и СМИИзобретательствоИностранные языкиИнформатикаИскусствоИсторияКомпьютерыКулинарияКультураЛексикологияЛитератураЛогикаМаркетингМатематикаМашиностроениеМедицинаМенеджментМеталлы и СваркаМеханикаМузыкаНаселениеОбразованиеОхрана безопасности жизниОхрана ТрудаПедагогикаПолитикаПравоПриборостроениеПрограммированиеПроизводствоПромышленностьПсихологияРадиоРегилияСвязьСоциологияСпортСтандартизацияСтроительствоТехнологииТорговляТуризмФизикаФизиологияФилософияФинансыХимияХозяйствоЦеннообразованиеЧерчениеЭкологияЭконометрикаЭкономикаЭлектроникаЮриспунденкция |
Bresenham's Circle Algorithm
In computer graphics, the midpoint circle algorithm is an algorithm used to determine the points needed for drawing a circle. The algorithm is a variant of Bresenham's line algorithm, and is thus sometimes known as Bresenham's circle algorithm, although not actually invented by Bresenham [5]. The algorithm starts accordingly with the circle equation x2 + y2 = r2. So, the center of the circle is located at (0,0). We consider first only the first octant and draw a curve which starts at point (r,0) and proceeds upwards and to the left, reaching the angle of 45°. The "fast" direction here is the y direction. The algorithm always does a step in the positive y direction (upwards), and every now and then also has to do a step in the "slow" direction, the negative x direction. The frequent computations of squares in the circle equation, trigonometric expressions or square roots can again be avoided by dissolving everything into single steps and recursive computation of the quadratic terms from the preceding ones. (From the circle equation we obtain the transformed equation x2 + y2 − r2 = 0, where r2 is computed only a single time during initialization). Let the points on the circle be a sequence of coordinates of the vector to the point (in the usual basis). Let n denote which point to be looked at, starting at the one on the horizontal axis, on the first quadrant. Then for each point we also holds: (4.3) Likewise for the next point: (4.4) That is: (4.5) Likewise for the next point: (4.6) In general, it is true that: (4.7) So we refashion our next-point-equation into a recursive one by substituting : (4.8) Because of the continuity of the circle and because it is a circle (i.e. maximum along both axes is the same) we know we will not be skipping x points as we advance in the sequence. Mostly we will either stay on the same x coordinate or advance by one. Additionally we need to add the midpoint coordinates when setting a pixel. These frequent integer additions do not limit the performance much, as we can spare those square (root) computations in the inner loop in turn. Again the zero in the transformed circle equation is replaced by the error term. The initialization of the error term is derived from an offset of 0.5 pixel at the start. Until the intersection with the perpendicular line, this leads to an accumulated value of r in the error term, so that this value is used for initialization. Here another variable for recursive computation of the quadratic terms is used, which corresponds with the term 2 n + 1 above. It just has to be increased by 2 from one step to the next: void rasterCircle(int x0, int y0, int radius) { int f = 1 - radius; int ddF_x = 1; int ddF_y = -2 * radius; int x = 0; int y = radius;
setPixel(x0, y0 + radius); setPixel(x0, y0 - radius); setPixel(x0 + radius, y0); setPixel(x0 - radius, y0);
while(x < y) { // ddF_x == 2 * x + 1; // ddF_y == -2 * y; // f == x*x + y*y - radius*radius + 2*x - y + 1; if(f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; setPixel(x0 + x, y0 + y); setPixel(x0 - x, y0 + y); setPixel(x0 + x, y0 - y); setPixel(x0 - x, y0 - y); setPixel(x0 + y, y0 + x); setPixel(x0 - y, y0 + x); setPixel(x0 + y, y0 - x); setPixel(x0 - y, y0 - x); } } Note: There is correlation between this algorithm and the sum of first N odd numbers, which this one basically does. That is, (4.9) When we compare sum of N odd numbers to this algorithm we have.
In any case there should be addition of 1 driven out of outer loop.
The following adaption of the circle algorithm is useful for machines where registers are scarce. Only three variables are needed in the main loop to perform the calculation. Although written in C, the code has been written to better reflect how it might be implemented in assembly code. // 'cx' and 'cy' denote the offset of the circle centre from the origin. void circle(int cx, int cy, int radius) { int error = -radius; int x = radius; int y = 0;
// The following while loop may altered to 'while (x > y)' for a // performance benefit, as long as a call to 'plot4points' follows // the body of the loop. This allows for the elimination of the // '(x!= y') test in 'plot8points', providing a further benefit. // // For the sake of clarity, this is not shown here. while (x >= y) { plot8points(cx, cy, x, y);
error += y; ++y; error += y;
// The following test may be implemented in assembly language in // most machines by testing the carry flag after adding 'y' to // the value of 'error' in the previous step, since 'error' // nominally has a negative value. if (error >= 0) { --x; error -= x; error -= x; } } }
void plot8points(int cx, int cy, int x, int y) { plot4points(cx, cy, x, y); if (x!= y) plot4points(cx, cy, y, x); }
// The '(x!= 0 && y!= 0)' test in the last line of this function // may be omitted for a performance benefit if the radius of the // circle is known to be non-zero. void plot4points(int cx, int cy, int x, int y) { setPixel(cx + x, cy + y); if (x!= 0) setPixel(cx - x, cy + y); if (y!= 0) setPixel(cx + x, cy - y); if (x!= 0 && y!= 0) setPixel(cx - x, cy - y); The implementations above always only draw complete octants or circles. To draw only a certain arc from an angle α to an angle β, the algorithm needs first to calculate the x and y coordinates of these end points, where it is necessary to resort to trigonometric or square root computations. Then the Bresenham algorithm is run over the complete octant or circle and sets the pixels only if they fall into the wanted interval. After finishing this arc, the algorithm can be ended prematurely. Note that if the angles are given as slopes, then no trigonometry or square roots are required: one simply checks that y/x is between the desired slopes. Поиск по сайту: |
Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Студалл.Орг (0.009 сек.) |