Skip to content

Commit

Permalink
Fix linestring to path (#2352)
Browse files Browse the repository at this point in the history
This PR fixes an issues with converting `shapely.Linestring` to
`Path3D`.
  • Loading branch information
mikedh authored Feb 11, 2025
2 parents 5cb5aa5 + 4bca2ea commit 53d120a
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
38 changes: 38 additions & 0 deletions tests/test_exchange.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from trimesh.path.exchange.misc import linestrings_to_path
from trimesh.path.exchange.load import load_path

from shapely.geometry import LineString, MultiLineString


def test_linestrings_to_path():
line = LineString([(0, 0), (1, 1), (2, 0)])

result = linestrings_to_path(line)

assert len(result["entities"]) == 1
assert len(result["vertices"]) == 3


def test_multilinestrings_to_path():
line = MultiLineString([
LineString([(0, 0), (1, 0), (2, 0)]),
LineString([(0, 1), (1, 1), (2, 1)])
])

result = linestrings_to_path(line)

assert len(result["entities"]) == 2
assert len(result["vertices"]) == 6


def test_load_path_with_multilinestrings():
line = MultiLineString([
LineString([(0, 0), (1, 0), (2, 0)]),
LineString([(0, 1), (1, 1), (2, 1)])
])

result = load_path(line)

assert len(result.entities) == 2
assert len(result.vertices) == 6
assert result.length == 4
20 changes: 12 additions & 8 deletions trimesh/path/exchange/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def dict_to_path(as_dict):

def lines_to_path(lines: ArrayLike, index: Optional[NDArray[np.int64]] = None) -> Dict:
"""
Turn line segments into a Path2D or Path3D object.
Turn line segments into argument to be used for a Path2D or Path3D.
Parameters
------------
Expand All @@ -50,7 +50,7 @@ def lines_to_path(lines: ArrayLike, index: Optional[NDArray[np.int64]] = None) -
Returns
-----------
kwargs : dict
kwargs : Dict
kwargs for Path constructor
"""
lines = np.asanyarray(lines, dtype=np.float64)
Expand Down Expand Up @@ -120,25 +120,29 @@ def polygon_to_path(polygon):
return kwargs


def linestrings_to_path(multi):
def linestrings_to_path(multi) -> Dict:
"""
Load shapely LineString objects into a trimesh.path.Path2D object
Load shapely LineString objects into arguments to create a Path2D or Path3D.
Parameters
-------------
multi : shapely.geometry.LineString or MultiLineString
Input 2D geometry
Input 2D or 3D geometry
Returns
-------------
kwargs : dict
Keyword arguments for Path2D constructor
kwargs : Dict
Keyword arguments for Path2D or Path3D constructor
"""
import shapely

# append to result as we go
entities = []
vertices = []

if not util.is_sequence(multi):
if isinstance(multi, shapely.MultiLineString):
multi = list(multi.geoms)
else:
multi = [multi]

for line in multi:
Expand Down

0 comments on commit 53d120a

Please sign in to comment.