Home > matGeom > polygons2d > clipPolygon.m

clipPolygon

PURPOSE ^

CLIPPOLYGON Clip a polygon with a rectangular box.

SYNOPSIS ^

function poly2 = clipPolygon(polygon, w)

DESCRIPTION ^

CLIPPOLYGON Clip a polygon with a rectangular box.

   POLY2 = clipPolygon(POLY, BOX);
   POLY is N-by-2 array of points
   BOX has the form: [XMIN XMAX YMIN YMAX].
   Returns the polygon created by the intersection of the polygon POLY and
   the bounding box BOX.

   Note: Works only for convex polygons at the moment.

   See also:
     polygons2d, boxes2d, clipPolygonHP, clipPolyline

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SOURCE CODE ^

0001 function poly2 = clipPolygon(polygon, w)
0002 %CLIPPOLYGON Clip a polygon with a rectangular box.
0003 %
0004 %   POLY2 = clipPolygon(POLY, BOX);
0005 %   POLY is N-by-2 array of points
0006 %   BOX has the form: [XMIN XMAX YMIN YMAX].
0007 %   Returns the polygon created by the intersection of the polygon POLY and
0008 %   the bounding box BOX.
0009 %
0010 %   Note: Works only for convex polygons at the moment.
0011 %
0012 %   See also:
0013 %     polygons2d, boxes2d, clipPolygonHP, clipPolyline
0014 %
0015 
0016 % ---------
0017 % author : David Legland
0018 % created the 14/05/2005.
0019 % Copyright 2010 INRA - Cepia Software Platform.
0020 
0021 %   HISTORY
0022 %   2007/09/14 fix doc
0023 
0024 % check case of polygons stored in cell array
0025 if iscell(polygon)
0026     poly2 = cell(1, length(polygon));
0027     for i = 1:length(polygon)
0028         poly2{i} = clipPolygon(polygon{i}, w);
0029     end
0030     return;
0031 end
0032 
0033 % check case of empty polygon
0034 N = size(polygon, 1);
0035 if N == 0
0036     poly2 = zeros(0, 2);
0037     return
0038 end
0039 
0040 % create edges array of polygon
0041 edges = [polygon polygon([2:N 1], :)];
0042 
0043 % clip edges
0044 edges = clipEdge(edges, w);
0045 
0046 % select non empty edges, and get their vertices
0047 ind = sum(abs(edges), 2) > 1e-14;
0048 pts = unique([edges(ind, 1:2); edges(ind, 3:4)], 'rows');
0049 
0050 % add vertices of window corner
0051 corners = [w(1) w(3); w(1) w(4);w(2) w(3);w(2) w(4)];
0052 ind = inpolygon(corners(:,1), corners(:,2), polygon(:,1), polygon(:,2));
0053 pts = [pts; corners(ind, :)];
0054 
0055 % polygon totally outside the window
0056 if size(pts, 1)==0
0057     poly2 = pts;
0058     return;
0059 end
0060 
0061 % compute centroid of visible polygon
0062 pc = centroid(pts);
0063 
0064 % sort vertices around polygon
0065 angle = edgeAngle([repmat(pc, [size(pts, 1) 1]) pts]);
0066 [dummy, I] = sort(angle); %#ok<ASGLU>
0067 
0068 % create resulting polygon
0069 poly2 = pts(I, :);

Generated on Wed 16-Feb-2022 15:10:47 by m2html © 2003-2019