c04_a_custom_triangle_example.cpp

The custom triangle example goes even further and implements a custom ring, where the area calculation algorithm is optimized for a triangle

    //Boost.Geometry(akaGGL,GenericGeometryLibrary)

    //Copyright(c)2007-2012BarendGehrels,Amsterdam,theNetherlands.
    //Copyright(c)2008-2012BrunoLalande,Paris,France.
    //Copyright(c)2009-2012MateuszLoskot,London,UK.

    //Use,modificationanddistributionissubjecttotheBoostSoftwareLicense,
    //Version1.0.(SeeaccompanyingfileLICENSE_1_0.txtorcopyat
    //http://www.boost.org/LICENSE_1_0.txt)
    //
    //CustomTriangleExample

    #include<iostream>

    #include<boost/array.hpp>

    #include<boost/geometry/algorithms/area.hpp>
    #include<boost/geometry/algorithms/centroid.hpp>
    #include<boost/geometry/geometries/point_xy.hpp>
    #include<boost/geometry/geometries/register/ring.hpp>
    #include<boost/geometry/strategies/strategies.hpp>
    #include<boost/geometry/io/dsv/write.hpp>

    structtriangle:publicboost::array<boost::geometry::model::d2::point_xy<double>,4>
    {
    inlinevoidclose()
    {
    (*this)[3]=(*this)[0];
    }
    };

    //Registertriangleasaring
    BOOST_GEOMETRY_REGISTER_RING(triangle)

    //Specializationsofalgorithms,whereuseful.Ifnotspecializedthedefaultones
    //(forlinearrings)willbeusedfortriangle.WhichisOKaslongasthetriangle
    //isclosed,thatmeans,has4points(thelastonebeingthefirst).
    namespaceboost{namespacegeometry{

    template<>
    inlinedoublearea<triangle>(consttriangle&t)
    {
    /*C
    /\
    /\
    A-----B

    ((Bx-Ax)*(Cy-Ay))-((Cx-Ax)*(By-Ay))
    -------------------------------------------------
    2
    */

    return0.5*((t[1].x()-t[0].x())*(t[2].y()-t[0].y())
    -(t[2].x()-t[0].x())*(t[1].y()-t[0].y()));
    }

    }}//namespaceboost::geometry

    intmain()
    {
    trianglet;

    t[0].x(0);
    t[0].y(0);
    t[1].x(5);
    t[1].y(0);
    t[2].x(2.5);
    t[2].y(2.5);

    t.close();

    std::cout<<"Triangle:"<<boost::geometry::dsv(t)<<std::endl;
    std::cout<<"Area:"<<boost::geometry::area(t)<<std::endl;

    boost::geometry::model::d2::point_xy<double>c;
    boost::geometry::centroid(t,c);
    std::cout<<"Centroid:"<<boost::geometry::dsv(c)<<std::endl;

    return0;
    }