simplify cut_polygon_with_line()
@@ -154,7 +154,12 @@ def cut_polygon_with_line(polygon: Polygon, line: LineString):
last = points.popleft()
while points:
current = points.popleft()
- if current.polygon == last.polygon:
+
+ # don't to anything between different polygons
+ if current.polygon != last.polygon:
+ last = current
+ continue
+
polygon = polygons[current.polygon]
segment = cut_line_with_point(cut_line_with_point(line, last.point)[-1], current.point)[0]
if current.ring != last.ring:
@@ -179,10 +184,10 @@ def cut_polygon_with_line(polygon: Polygon, line: LineString):
points = deque((cutpoint(item.point, item.polygon, mapping[item.ring])
if (item.polygon == current.polygon and item.ring in mapping) else item)
for item in points)
- current = cutpoint(current.point, current.polygon, new_i)
+ last = cutpoint(current.point, current.polygon, new_i)
+ continue
- elif current.ring == 0:
- # cut polygon
+ # cut polygon?
new_i = len(polygons)
exterior = cut_line_with_point(polygon[0], current.point)
exterior = cut_line_with_point(LinearRing(exterior[1].coords[:-1] +
@@ -203,8 +208,11 @@ def cut_polygon_with_line(polygon: Polygon, line: LineString):
while angle_segment > angle_forwards:
angle_segment -= 2*math.pi
- # cut polygon only if segment is inside polygon
- if angle_backwards < angle_segment < angle_forwards:
+ # don't cut polygon if segment is not inside polygon (= we don't cut through emptyness)
+ if not (angle_backwards < angle_segment < angle_forwards):
+ last = current
+ continue
+
exterior1 = LinearRing(exterior[0].coords[:-1] + segment.coords[0:])
exterior2 = LinearRing(exterior[1].coords[:-1] + segment.coords[::-1])
geom = Polygon(exterior1)
@@ -224,7 +232,6 @@ def cut_polygon_with_line(polygon: Polygon, line: LineString):
if (item.polygon == current.polygon and item.ring == 0 and
not exterior1.contains(item.point)) else item)
for item in points)
- current = cutpoint(current.point, new_i, 0)
- last = current
+ last = cutpoint(current.point, new_i, 0)
return tuple(Polygon(polygon[0], tuple(ring for ring in polygon[1:] if ring is not None))
for polygon in polygons)
