Sunday, 1 May 2011

Polygonal approximation to circle

In order to be able to tackle the "cutting tool" for my TDPhysicsEngine, I need to work with polygon approximations instead of a full drawn circle using the Canvas.Ellipse Delphi function. To achieve this in the view layer is as easy as using Canvas.Polygon function to draw a polygon using a list of calculated points. To calculate the points, we need to divide the circle in discrete chunks and then let the function draw the lines between points. The main reason what I'm doing that is to be sure that I can cut up a polygon and then use the resulting pieces as new objects that will behave as independent objects:


The function below will help you to draw the polygon:

procedure GDIRenderer.CircleApproximation(xcenter, ycenter, Radius, Rotate: Double; style: TStyle);
var
    PArrow: array [1 .. points] of TPoint;
    i: integer;
    theta: Double;
    x, y : double;
    beforeBrushColor, beforePenColor: TColor;
    beforePenWidth: integer;
begin
    beforeBrushColor := FCanvas.Brush.color;
    beforePenColor := FCanvas.Pen.color;
    beforePenWidth := FCanvas.Pen.Width;

    FCanvas.Pen.color := style.PenColor;
    FCanvas.Pen.Width := style.penWidth;
    FCanvas.Brush.color := style.BrushColor;

    for i := 1 to points do
    begin
        theta := Pi * ((i-1)/(points/2));
        x := xcenter + (Radius* Cos(theta));
        y := ycenter + (Radius* Sin(theta));
        PArrow[i] := Point(Round(x), Round(y));
    end;
    FCanvas.Polygon(PArrow);

    FCanvas.Brush.color := beforeBrushColor;
    FCanvas.Pen.color := beforePenColor;
    FCanvas.Pen.Width := beforePenWidth;
end;

The big difficulty here is to model this behaviour in the model. I need to work more and think about it because for the moment it's adjusted as a sphere and it's not a good approximation.

0 comments:

Post a Comment