diff --git a/ladybug_geometry/geometry2d/polygon.py b/ladybug_geometry/geometry2d/polygon.py index c7c07248..a1364f37 100644 --- a/ladybug_geometry/geometry2d/polygon.py +++ b/ladybug_geometry/geometry2d/polygon.py @@ -1150,6 +1150,25 @@ def snap_to_polygon(self, polygon, tolerance): new_verts.append(pt) return Polygon2D(new_verts) + def snap_to_grid(self, grid_increment): + """Snap this polygon's vertices to the nearest grid node defined by an increment. + + Args: + grid_increment: A positive number for dimension of each grid cell. This + typically should be equal to the tolerance or larger but should + not be larger than the smallest detail of the polygon that you + wish to resolve. + + Returns: + A version of this polygon that is snapped to the grid. + """ + new_verts = [] + for pt in self.vertices: + new_x = grid_increment * round(pt.x / grid_increment) + new_y = grid_increment * round(pt.y / grid_increment) + new_verts.append(Point2D(new_x, new_y)) + return Polygon2D(new_verts) + def to_dict(self): """Get Polygon2D as a dictionary.""" return {'type': 'Polygon2D', diff --git a/tests/polygon2d_test.py b/tests/polygon2d_test.py index 6a21918d..71c446a4 100644 --- a/tests/polygon2d_test.py +++ b/tests/polygon2d_test.py @@ -721,6 +721,19 @@ def test_distance_to_point(): assert polygon.distance_from_edge_to_point(Point2D(1, 1)) != 0 +def test_snap_to_grid(): + """Test the snap_to_grid method.""" + pts = (Point2D(0.2, 0), Point2D(4.1, 0), Point2D(4.1, 4), Point2D(0, 4.2)) + snapped_pts = (Point2D(0, 0), Point2D(4, 0), Point2D(4, 4), Point2D(0, 4)) + polygon = Polygon2D(pts) + + new_poly = polygon.snap_to_grid(0.5) + assert new_poly.vertices == snapped_pts + + new_poly = polygon.snap_to_grid(0.01) + assert new_poly.vertices == pts + + def test_intersect_segments(): """Tests that polygons within tolerance distance have vertices updated.""" tolerance = 0.02