Skip to content

Commit

Permalink
fix(polygon): Add a method to snap Polygon2D to a grid
Browse files Browse the repository at this point in the history
  • Loading branch information
chriswmackey authored and Chris Mackey committed Apr 3, 2024
1 parent dd1d57a commit 5ccd0f0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions ladybug_geometry/geometry2d/polygon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
13 changes: 13 additions & 0 deletions tests/polygon2d_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 5ccd0f0

Please sign in to comment.