How can I create a GPC polygon to use with Math::Geometry::Planar::GpcClip?

373 views Asked by At

I am trying to use the GpcClip() function from Math::Geometry::Planar to find the intersection of two polygons. I built two polygons by using Math::Geometry::Planar->new(); but I got the following error when I used them in GpcClip():

Type error in argument 2 of gpc_polygon_clip. Expected _p_gpc_polygon at c:/strawberry/perl/site/lib/math/geometry/planar.pm line 2028

How can I convert the object returned by Math::Geometry::Planar->new() into a GPC polygon?

2

There are 2 answers

5
ThisSuitIsBlackNot On

According to the documentation, you can use the convert2gpc method:

$polygon->convert2gpc;

Converts a polygon/contour to a gpc structure and returns the resulting gpc structure

Example:

use strict;
use warnings 'all';

use Math::Geometry::Planar;

my $outer = Math::Geometry::Planar->new;
my $inner = Math::Geometry::Planar->new;
$outer->points([[0, 0], [0, 3], [3, 3], [3, 0]]);
$inner->points([[1, 1], [1, 2], [2, 2], [2, 1]]);

my $diff = GpcClip('DIFFERENCE', $outer->convert2gpc, $inner->convert2gpc);
2
s.pan On
use strict;
use warnings 'all';
use Data::Dumper;
use Math::Geometry::Planar;

my $outer = Math::Geometry::Planar->new;
my $inner = Math::Geometry::Planar->new;
$outer->points([[0, 0], [0, 3], [3, 3], [3, 0],[0,0]]);
$inner->points([[2, 0], [2, 2], [4, 2], [4, 0],[2,0]]);

my $diff = GpcClip('INTERSECTION', $outer->convert2gpc, $inner->convert2gpc);
#first polygon rep the outer poly, the rest of them are holes
my @pgons = Gpc2Polygons($diff);  

#since here we don't have holes, only the first one is a valid polygon 
print Dumper($pgons[0]->polygons->[0]);

#convert the points into Planar Polygon
my $result = Math::Geometry::Planar->new;
$result->points($pgons[0]->polygons->[0]);

print Dumper($result);

Appreciate the help from @ThisSuitlsBlackNot . By the way, do you have any idea to find a random point inside a polygon, this polygon doesn't have hole. Thanks again