將多邊形實體進行旋正

      在進行幾何實體操作時,有時候是需要將實體安裝”最長邊“進行旋轉,例如:

旋轉之前
旋轉之後

       從第一個圖中可以看出,實體最長的邊是有很多個節點,如果我們直接安照多邊形中最長的邊進行旋轉那麼最終的結果是下圖這樣的:

直接按照最長邊

       這樣就不是我們想要的結果,所以在計算旋轉角度的時候,我們需要先將一些共線的點給忽略掉,這樣我們就可以計算出最長的邊。

       移除共線的點方法:

//點與線的位置關係

enum PointLocation
{
    Line_Left,
    Line_Right,
    Collinear_Left,
    Collinear_Right,
    Collinear_Contain
};

PointLocation collinearTest(const Point &P, const Point &Q1, const Point &Q2)
{
    Vector A = Vector(P.x - Q1.x, P.y - Q1.y);
    Vector D = Vector(Q2.x - Q1.x, Q2.y - Q1.y);
    Vector N = -D.perpVector();
    double val = N.dotProduct(A);
    if(val > 0) return Line_Left;
    else if(val < 0) return Line_Right;
    val = D.dotProduct(A);
    if(val < 0) return Collinear_Left;
    else if(val > D.dotProduct(D)) return Collinear_Right;
    return Collinear_Contain;
}

PointArray removeSurplusPoint(const PointArray &node)
{
    int len = node.length(); PointArray node1;
    for(int idx = 1; idx < node.length(); ++idx)
    {
        Point p1 = node[(idx - 1) % len];
        Point p2 = node[(idx + 0) % len];
        Point p3 = node[(idx + 1) % len];
        if(Collinear_Contain == collinearTest(p2, p1, p3)) continue;
        node1.append(p2);
    }
    return node1;
}

//計算旋轉角度
double rotateAngle(const PointArray &node)
{
    double ang= 0.0, dist = 0.0;
    int len = node.length();
    for(int idx = 0; idx < len; ++idx)
    {
        Point spt = node[idx];
        Point ept = node[(idx + 1) % len];
        double temp = spt.distance(ept);
        if(temp > dist) { dist = temp; ang= angle(spt, ept); }
    }
    return -ang;
}

計算出旋轉角度之後,我們就可以對實體進行旋轉。旋轉的結果就是第二個圖。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章