snake_geometry.cpp 10.4 KB
Newer Older
1 2 3 4 5 6 7 8
#include "snake_geometry.h"
#include <mapbox/polylabel.hpp>
#include <mapbox/geometry.hpp>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>

Valentin Platzgummer's avatar
Valentin Platzgummer committed
9 10 11 12

#include <GeographicLib/Geocentric.hpp>
#include <GeographicLib/LocalCartesian.hpp>

13
using namespace mapbox;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
14 15
using namespace snake_geometry;
using namespace std;
16

Valentin Platzgummer's avatar
Valentin Platzgummer committed
17 18 19
namespace bg = bg;
namespace trans = bg::strategy::transform;

20 21 22 23 24
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)


namespace snake_geometry {

Valentin Platzgummer's avatar
Valentin Platzgummer committed
25
void toENU(const GeoPoint3D &WGS84Reference, const GeoPoint3D &WGS84Position, Point3D &ENUPosition)
26
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
27 28
    GeographicLib::Geocentric earth(GeographicLib::Constants::WGS84_a(), GeographicLib::Constants::WGS84_f());
    GeographicLib::LocalCartesian proj(WGS84Reference[0], WGS84Reference[1], WGS84Reference[2], earth);
29

Valentin Platzgummer's avatar
Valentin Platzgummer committed
30
    proj.Forward(WGS84Position[0], WGS84Position[1], WGS84Position[2], ENUPosition[0], ENUPosition[1], ENUPosition[2]);
31 32
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
33
void fromENU(const Point3D &WGS84Reference, const Point3D &CartesianPosition, GeoPoint3D &GeoPosition)
34
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
35 36
    GeographicLib::Geocentric earth(GeographicLib::Constants::WGS84_a(), GeographicLib::Constants::WGS84_f());
    GeographicLib::LocalCartesian proj(WGS84Reference[0], WGS84Reference[1], WGS84Reference[2], earth);
37

Valentin Platzgummer's avatar
Valentin Platzgummer committed
38
    proj.Reverse(CartesianPosition[0], CartesianPosition[1], CartesianPosition[2], GeoPosition[0], GeoPosition[1], GeoPosition[2]);
39 40
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
41
void polygonCenter(const BoostPolygon &polygon, BoostPoint &center)
42
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
43 44
   if (polygon.outer().empty())
       return;
45 46
   geometry::polygon<double> p;
   geometry::linear_ring<double> lr1;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
47 48
   for (size_t i = 0; i < polygon.outer().size(); ++i) {
       geometry::point<double> vertex(polygon.outer()[i].get<0>(), polygon.outer()[i].get<1>());
49 50 51
       lr1.push_back(vertex);
   }
   p.push_back(lr1);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
52
   geometry::point<double> c = polylabel(p);
53

Valentin Platzgummer's avatar
Valentin Platzgummer committed
54 55
   center.set<0>(c.x);
   center.set<1>(c.y);
56 57
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
58
void minimalBoundingBox(const BoostPolygon &polygon, min_bbox_rt &minBBox)
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
{
    /*
    Find the minimum-area bounding box of a set of 2D points

    The input is a 2D convex hull, in an Nx2 numpy array of x-y co-ordinates.
    The first and last points points must be the same, making a closed polygon.
    This program finds the rotation angles of each edge of the convex polygon,
    then tests the area of a bounding box aligned with the unique angles in
    90 degrees of the 1st Quadrant.
    Returns the

    Tested with Python 2.6.5 on Ubuntu 10.04.4 (original version)
    Results verified using Matlab

    Copyright (c) 2013, David Butterworth, University of Queensland
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

        * Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.
        * Neither the name of the Willow Garage, Inc. nor the names of its
          contributors may be used to endorse or promote products derived from
          this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
    */

Valentin Platzgummer's avatar
Valentin Platzgummer committed
101 102 103 104
    if (polygon.outer().empty())
        return;
    BoostPolygon convex_hull;
    bg::convex_hull(polygon, convex_hull);
105

Valentin Platzgummer's avatar
Valentin Platzgummer committed
106
    //cout << "Convex hull: " << bg::wkt<BoostPolygon2D>(convex_hull) << endl;
107 108

    //# Compute edges (x2-x1,y2-y1)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
109
    std::vector<BoostPoint> edges;
110
    auto convex_hull_outer = convex_hull.outer();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
111
    for (size_t i=0; i < convex_hull_outer.size()-1; ++i) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
112 113
        BoostPoint p1      = convex_hull_outer.at(i);
        BoostPoint p2      = convex_hull_outer.at(i+1);
114 115
        double edge_x   = p2.get<0>() - p1.get<0>();
        double edge_y   = p2.get<1>() - p1.get<1>();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        edges.push_back(BoostPoint{edge_x, edge_y});
    }

//    cout << "Edges: ";
//    for (auto e : edges)
//        cout << e.get<0>() << " " << e.get<1>() << ",";
//    cout << endl;

    // Calculate unique edge angles  atan2(y/x)
    double angle_scale = 1e3;
    std::set<long> angles_long;
    for (auto vertex : edges) {
        double angle = std::fmod(atan2(vertex.get<1>(), vertex.get<0>()), M_PI / 2);
        angle = angle < 0 ? angle + M_PI / 2 : angle; // want strictly positive answers
        angles_long.insert(long(round(angle*angle_scale)));
131
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
132 133 134
    std::vector<double> edge_angles;
    for (auto a : angles_long)
        edge_angles.push_back(double(a)/angle_scale);
135 136


Valentin Platzgummer's avatar
Valentin Platzgummer committed
137 138 139 140
//    cout << "Unique angles: ";
//    for (auto e : edge_angles)
//        cout << e*180/M_PI << ",";
//    cout << endl;
141 142 143 144 145 146

    double min_area = std::numeric_limits<double>::infinity();
    // Test each angle to find bounding box with smallest area
    // print "Testing", len(edge_angles), "possible rotations for bounding box... \n"
    for (double angle : edge_angles){

Valentin Platzgummer's avatar
Valentin Platzgummer committed
147 148 149 150
        trans::rotate_transformer<bg::degree, double, 2, 2> rotate(angle*180/M_PI);
        BoostPolygon hull_rotated;
        bg::transform(convex_hull, hull_rotated, rotate);
        //cout << "Convex hull rotated: " << bg::wkt<BoostPolygon2D>(hull_rotated) << endl;
151

Valentin Platzgummer's avatar
Valentin Platzgummer committed
152 153 154
        bg::model::box<BoostPoint> box;
        bg::envelope(hull_rotated, box);
//        cout << "Bounding box: " << bg::wkt<bg::model::box<BoostPoint2D>>(box) << endl;
155 156

        //# print "Rotated hull points are \n", rot_points
Valentin Platzgummer's avatar
Valentin Platzgummer committed
157 158
        BoostPoint min_corner = box.min_corner();
        BoostPoint max_corner = box.max_corner();
159
        double min_x = min_corner.get<0>();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
160 161
        double max_x = max_corner.get<0>();
        double min_y = min_corner.get<1>();
162
        double max_y = max_corner.get<1>();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
163 164 165 166
//        cout << "min_x: " << min_x << endl;
//        cout << "max_x: " << max_x << endl;
//        cout << "min_y: " << min_y << endl;
//        cout << "max_y: " << max_y << endl;
167 168 169 170 171

        // Calculate height/width/area of this bounding rectangle
        double width    = max_x - min_x;
        double height   = max_y - min_y;
        double area     = width * height;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
172 173 174 175
//        cout << "Width: " << width << endl;
//        cout << "Height: " << height << endl;
//        cout << "area: " << area << endl;
//        cout << "angle: " << angle*180/M_PI << endl;
176 177 178

        // Store the smallest rect found first (a simple convex hull might have 2 answers with same area)
        if (area < min_area){
Valentin Platzgummer's avatar
Valentin Platzgummer committed
179 180 181 182 183 184 185 186 187 188 189
            min_area = area;
            minBBox.angle  = angle;
            minBBox.width  = width;
            minBBox.height = height;

            minBBox.corners.clear();
            minBBox.corners.outer().push_back(BoostPoint{min_x, min_y});
            minBBox.corners.outer().push_back(BoostPoint{min_x, max_y});
            minBBox.corners.outer().push_back(BoostPoint{max_x, max_y});
            minBBox.corners.outer().push_back(BoostPoint{max_x, min_y});
            minBBox.corners.outer().push_back(BoostPoint{min_x, min_y});
190
        }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
191
        //cout << endl << endl;
192 193
    }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
194 195

    // Transform corners of minimal bounding box.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    trans::rotate_transformer<bg::degree, double, 2, 2> rotate(-minBBox.angle*180/M_PI);
    BoostPolygon rotated_polygon;
    bg::transform(minBBox.corners, rotated_polygon, rotate);
    minBBox.corners = rotated_polygon;
}

void toBoost(const Point2D &point, BoostPoint &boost_point)
{
    boost_point.set<0>(point[0]);
    boost_point.set<1>(point[1]);
}

void fromBoost(const BoostPoint &boost_point, Point2D &point)
{
    point[0] = boost_point.get<0>();
    point[1] = boost_point.get<1>();
}

void toBoost(const Point2DList &point_list, BoostPolygon &boost_polygon)
{
    for (auto vertex : point_list) {
        BoostPoint boost_vertex;
        toBoost(vertex, boost_vertex);
        boost_polygon.outer().push_back(boost_vertex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
220
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
221 222
    bg::correct(boost_polygon);
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
223

Valentin Platzgummer's avatar
Valentin Platzgummer committed
224 225 226 227 228 229
void fromBoost(const BoostPolygon &boost_polygon, Point2DList &point_list)
{
    for (auto boost_vertex : boost_polygon.outer()) {
        Point2D vertex;
        fromBoost(boost_vertex, vertex);
        point_list.push_back(vertex);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
230
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
}

void rotateDeg(const Point2DList &point_list, Point2DList &rotated_point_list, double degree)
{
    trans::rotate_transformer<bg::degree, double, 2, 2> rotate(degree);
    BoostPolygon boost_polygon;
    toBoost(point_list, boost_polygon);
    BoostPolygon rotated_polygon;
    bg::transform(boost_polygon, rotated_polygon, rotate);
    fromBoost(rotated_polygon, rotated_point_list);
}

void rotateRad(const Point2DList &point_list, Point2DList &rotated_point_list, double rad)
{
    rotateDeg(point_list, rotated_point_list, rad*180/M_PI);
}

bool isClockwise(const Point2DList &point_list)
{
    double orientaion = 0;
    double len = point_list.size();
    for (size_t i=0; i < len-1; ++i){
        Point2D v1 = point_list[i];
        Point2D v2 = point_list[i+1];
        orientaion += (v2[0]-v1[0])*(v2[1]+v1[1]);
    }
    Point2D v1 = point_list[len-1];
    Point2D v2 = point_list[0];
    orientaion += (v2[0]-v1[0])*(v2[1]+v1[1]);

    return orientaion > 0 ? true : false;
}

void offsetPolygon(const BoostPolygon &polygon, BoostPolygon &polygonOffset, double offset)
{
    bg::strategy::buffer::distance_symmetric<double> distance_strategy(offset);
    bg::strategy::buffer::join_miter join_strategy(3);
    bg::strategy::buffer::end_flat end_strategy;
    bg::strategy::buffer::point_square point_strategy;
    bg::strategy::buffer::side_straight side_strategy;


    bg::model::multi_polygon<BoostPolygon> result;

    bg::buffer(polygon, result, distance_strategy, side_strategy, join_strategy, end_strategy, point_strategy);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
276

Valentin Platzgummer's avatar
Valentin Platzgummer committed
277
    polygonOffset = result[0];
Valentin Platzgummer's avatar
Valentin Platzgummer committed
278

279
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
280 281

} // end namespace snake_geometry