user1454345
user1454345

Reputation: 77

Calculating points around a circle in sequence

I have adapted some code from a great article I found about circle drawing by Mukund Sivaraman to execute a passed function for each point on a given circle:

template<class Function>
static void For_each_point_on_circle(Image *image, int radius, Function function)
{
    int x, y;
    int l;
    l = (int) radius * cos (M_PI / 4);
    for (x = 0; x <= l; x++)
    {
        y = (int) sqrt ((double) (radius * radius) - (x * x));
        function(image, x, y);
        function(image, x, -y);
        function(image, -x, y);
        function(image, -x, -y);
        function(image, y, x);
        function(image, y, -x);
        function(image, -y, x);
        function(image, -y, -x);
  }
}

However, what I really need is to calculate the points around the circle in sequence, so the calls to function(image, x, y) will go from 0 to 360 degrees in sequence rather than skipping about, which is acceptable when drawing the circle.

I could calculate all the points and sort them, but I was hoping someone may know a way to do it properly, maybe using multiple loops each calculating a segment each?

Many thanks.

Upvotes: 2

Views: 2192

Answers (2)

atb
atb

Reputation: 1462

something like this should do it:

template<class Function>
static void For_each_point_on_circle(Image *image, int radius, Function function)
{
    int x, y;
    int l;
    l = (int) radius * cos (M_PI / 4);
    for (x = -l; x < l; x++)
    {
        y = (int) sqrt ((double) (radius * radius) - (x * x));
        function(image, x, y);
    }
    for (x = -l; x < l; x++)
    {
        y = (int) sqrt ((double) (radius * radius) - (x * x));
        function(image, y, -x);
    }
    for (x = -l; x < l; x++)
    {
        y = (int) sqrt ((double) (radius * radius) - (x * x));
        function(image, -x, -y);
    }
    for (x = -l; x < l; x++)
    {
        y = (int) sqrt ((double) (radius * radius) - (x * x));
        function(image, -y, x);
    }
}

Upvotes: 4

Falmarri
Falmarri

Reputation: 48559

Here's an article on pathing out a circle in discrete steps. Its motivation is for a CNC machine stepper motor controller, but maybe it will work for your purposes.

https://github.com/Falmarri/cnc/blob/master/BresenHam-3D-helix.pdf

Upvotes: 2

Related Questions