Coverage for trimesh/intersections.py: 93%
262 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-22 02:08 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-22 02:08 +0000
1"""
2intersections.py
3------------------
5Primarily mesh-plane intersections (slicing).
6"""
8import numpy as np
10from . import geometry, grouping, util
11from . import transformations as tf
12from . import triangles as tm
13from .constants import tol
16def mesh_plane(
17 mesh,
18 plane_normal,
19 plane_origin,
20 return_faces=False,
21 local_faces=None,
22 cached_dots=None,
23):
24 """
25 Find a the intersections between a mesh and a plane,
26 returning a set of line segments on that plane.
28 Parameters
29 ---------
30 mesh : Trimesh object
31 Source mesh to slice
32 plane_normal : (3,) float
33 Normal vector of plane to intersect with mesh
34 plane_origin : (3,) float
35 Point on plane to intersect with mesh
36 return_faces : bool
37 If True return face index each line is from
38 local_faces : None or (m,) int
39 Limit section to just these faces.
40 cached_dots : (n, 3) float
41 If an external function has stored dot
42 products pass them here to avoid recomputing.
44 Returns
45 ----------
46 lines : (m, 2, 3) float
47 List of 3D line segments in space.
48 face_index : (m,) int
49 Index of mesh.faces for each line
50 Only returned if return_faces was True
51 """
53 def triangle_cases(signs):
54 """
55 Figure out which faces correspond to which intersection
56 case from the signs of the dot product of each vertex.
57 Does this by bitbang each row of signs into an 8 bit
58 integer.
60 code : signs : intersects
61 0 : [-1 -1 -1] : No
62 2 : [-1 -1 0] : No
63 4 : [-1 -1 1] : Yes; 2 on one side, 1 on the other
64 6 : [-1 0 0] : Yes; one edge fully on plane
65 8 : [-1 0 1] : Yes; one vertex on plane 2 on different sides
66 12 : [-1 1 1] : Yes; 2 on one side, 1 on the other
67 14 : [0 0 0] : No (on plane fully)
68 16 : [0 0 1] : Yes; one edge fully on plane
69 20 : [0 1 1] : No
70 28 : [1 1 1] : No
72 Parameters
73 ----------
74 signs: (n,3) int, all values are -1,0, or 1
75 Each row contains the dot product of all three vertices
76 in a face with respect to the plane
78 Returns
79 ---------
80 basic : (n,) bool
81 Which faces are in the basic intersection case
82 one_vertex : (n,) bool
83 Which faces are in the one vertex case
84 one_edge : (n,) bool
85 Which faces are in the one edge case
86 """
88 signs_sorted = np.sort(signs, axis=1)
89 coded = np.zeros(len(signs_sorted), dtype=np.int8) + 14
90 for i in range(3):
91 coded += signs_sorted[:, i] << 3 - i
93 # one edge fully on the plane
94 # note that we are only accepting *one* of the on- edge cases,
95 # where the other vertex has a positive dot product (16) instead
96 # of both on- edge cases ([6, 16])
97 # this is so that for regions that are co-planar with the the section plane
98 # we don't end up with an invalid boundary
99 key = np.zeros(29, dtype=bool)
100 key[16] = True
101 one_edge = key[coded]
103 # one vertex on plane, other two on different sides
104 key[:] = False
105 key[8] = True
106 one_vertex = key[coded]
108 # one vertex on one side of the plane, two on the other
109 key[:] = False
110 key[[4, 12]] = True
111 basic = key[coded]
113 return basic, one_vertex, one_edge
115 def handle_on_vertex(signs, faces, vertices):
116 # case where one vertex is on plane
117 # and two are on different sides
118 vertex_plane = faces[signs == 0]
119 edge_thru = faces[signs != 0].reshape((-1, 2))
120 point_intersect, valid = plane_lines(
121 plane_origin, plane_normal, vertices[edge_thru.T], line_segments=False
122 )
123 lines = np.column_stack((vertices[vertex_plane[valid]], point_intersect)).reshape(
124 (-1, 2, 3)
125 )
126 return lines
128 def handle_on_edge(signs, faces, vertices):
129 # case where two vertices are on the plane and one is off
130 edges = faces[signs == 0].reshape((-1, 2))
131 points = vertices[edges]
132 return points
134 def handle_basic(signs, faces, vertices):
135 # case where one vertex is on one side and two are on the other
136 unique_element = grouping.unique_value_in_row(signs, unique=[-1, 1])
137 edges = np.column_stack(
138 (
139 faces[unique_element],
140 faces[np.roll(unique_element, 1, axis=1)],
141 faces[unique_element],
142 faces[np.roll(unique_element, 2, axis=1)],
143 )
144 ).reshape((-1, 2))
145 intersections, valid = plane_lines(
146 plane_origin, plane_normal, vertices[edges.T], line_segments=False
147 )
148 # since the data has been pre- culled, any invalid intersections at all
149 # means the culling was done incorrectly and thus things are broken
150 assert valid.all()
151 return intersections.reshape((-1, 2, 3))
153 # check input plane
154 plane_normal = np.asanyarray(plane_normal, dtype=np.float64)
155 plane_origin = np.asanyarray(plane_origin, dtype=np.float64)
156 if plane_origin.shape != (3,) or plane_normal.shape != (3,):
157 raise ValueError("Plane origin and normal must be (3,)!")
159 if local_faces is None:
160 # do a cross section against all faces
161 faces = mesh.faces
162 else:
163 local_faces = np.asanyarray(local_faces, dtype=np.int64)
164 # only take the subset of faces if passed
165 faces = mesh.faces[local_faces]
167 if cached_dots is not None:
168 dots = cached_dots
169 else:
170 # dot product of each vertex with the plane normal indexed by face
171 # so for each face the dot product of each vertex is a row
172 # shape is the same as mesh.faces (n,3)
173 dots = np.dot(mesh.vertices - plane_origin, plane_normal)
175 # sign of the dot product is -1, 0, or 1
176 # shape is the same as mesh.faces (n,3)
177 signs = np.zeros(len(mesh.vertices), dtype=np.int8)
178 signs[dots < -tol.merge] = -1
179 signs[dots > tol.merge] = 1
180 signs = signs[faces]
182 # figure out which triangles are in the cross section,
183 # and which of the three intersection cases they are in
184 cases = triangle_cases(signs)
185 # handlers for each case
186 handlers = (handle_basic, handle_on_vertex, handle_on_edge)
188 # the (m, 2, 3) line segments
189 lines = np.vstack(
190 [h(signs[c], faces[c], mesh.vertices) for c, h in zip(cases, handlers)]
191 )
193 if return_faces:
194 # everything that hit something
195 index = np.hstack([np.nonzero(c)[0] for c in cases])
196 assert index.dtype.kind == "i"
197 if local_faces is None:
198 return lines, index
199 # we are considering a subset of faces
200 # so we need to take the indexes from original
201 return lines, local_faces[index]
202 return lines
205def mesh_multiplane(mesh, plane_origin, plane_normal, heights):
206 """
207 A utility function for slicing a mesh by multiple
208 parallel planes which caches the dot product operation.
210 Parameters
211 -------------
212 mesh : trimesh.Trimesh
213 Geometry to be sliced by planes
214 plane_origin : (3,) float
215 Point on a plane
216 plane_normal : (3,) float
217 Normal vector of plane
218 heights : (m,) float
219 Offset distances from plane to slice at:
220 at `height=0` it will be exactly on the passed plane.
222 Returns
223 --------------
224 lines : (m,) sequence of (n, 2, 2) float
225 Lines in space for m planes
226 to_3D : (m, 4, 4) float
227 Transform to move each section back to 3D
228 face_index : (m,) sequence of (n,) int
229 Indexes of mesh.faces for each segment
230 """
231 # check input plane
232 plane_normal = util.unitize(plane_normal)
233 plane_origin = np.asanyarray(plane_origin, dtype=np.float64)
234 heights = np.asanyarray(heights, dtype=np.float64)
236 # dot product of every vertex with plane
237 vertex_dots = np.dot(plane_normal, (mesh.vertices - plane_origin).T)
239 # reconstruct transforms for each 2D section
240 base_transform = geometry.plane_transform(origin=plane_origin, normal=plane_normal)
241 base_transform = np.linalg.inv(base_transform)
243 # alter translation Z inside loop
244 translation = np.eye(4)
246 # store results
247 transforms = []
248 face_index = []
249 segments = []
251 # loop through user specified heights
252 for height in heights:
253 # offset the origin by the height
254 new_origin = plane_origin + (plane_normal * height)
255 # offset the dot products by height and index by faces
256 new_dots = vertex_dots - height
257 # run the intersection with the cached dot products
258 lines, index = mesh_plane(
259 mesh=mesh,
260 plane_origin=new_origin,
261 plane_normal=plane_normal,
262 return_faces=True,
263 cached_dots=new_dots,
264 )
266 # get the transforms to 3D space and back
267 translation[2, 3] = height
268 to_3D = np.dot(base_transform, translation)
269 to_2D = np.linalg.inv(to_3D)
270 transforms.append(to_3D)
272 # transform points to 2D frame
273 lines_2D = tf.transform_points(lines.reshape((-1, 3)), to_2D)
275 # if we didn't screw up the transform all
276 # of the Z values should be zero
277 # assert np.allclose(lines_2D[:, 2], 0.0)
279 # reshape back in to lines and discard Z
280 lines_2D = lines_2D[:, :2].reshape((-1, 2, 2))
281 # store (n, 2, 2) float lines
282 segments.append(lines_2D)
283 # store (n,) int indexes of mesh.faces
284 face_index.append(index)
286 # (n, 4, 4) transforms from 2D to 3D
287 transforms = np.array(transforms, dtype=np.float64)
289 return segments, transforms, face_index
292def plane_lines(plane_origin, plane_normal, endpoints, line_segments=True):
293 """
294 Calculate plane-line intersections
296 Parameters
297 ---------
298 plane_origin : (3,) float
299 Point on plane
300 plane_normal : (3,) float
301 Plane normal vector
302 endpoints : (2, n, 3) float
303 Points defining lines to be tested
304 line_segments : bool
305 If True, only returns intersections as valid if
306 vertices from endpoints are on different sides
307 of the plane.
309 Returns
310 ---------
311 intersections : (m, 3) float
312 Cartesian intersection points
313 valid : (n, 3) bool
314 Indicate whether a valid intersection exists
315 for each input line segment
316 """
317 endpoints = np.asanyarray(endpoints)
318 plane_origin = np.asanyarray(plane_origin).reshape(3)
319 line_dir = util.unitize(endpoints[1] - endpoints[0])
320 plane_normal = util.unitize(np.asanyarray(plane_normal).reshape(3))
322 t = np.dot(plane_normal, (plane_origin - endpoints[0]).T)
323 b = np.dot(plane_normal, line_dir.T)
325 # If the plane normal and line direction are perpendicular, it means
326 # the vector is 'on plane', and there isn't a valid intersection.
327 # We discard on-plane vectors by checking that the dot product is nonzero
328 valid = np.abs(b) > tol.zero
329 if line_segments:
330 test = np.dot(plane_normal, np.transpose(plane_origin - endpoints[1]))
331 different_sides = np.sign(t) != np.sign(test)
332 nonzero = np.logical_or(np.abs(t) > tol.zero, np.abs(test) > tol.zero)
333 valid = np.logical_and(valid, different_sides)
334 valid = np.logical_and(valid, nonzero)
336 d = np.divide(t[valid], b[valid])
337 intersection = endpoints[0][valid]
338 intersection = intersection + np.reshape(d, (-1, 1)) * line_dir[valid]
340 return intersection, valid
343def planes_lines(
344 plane_origins,
345 plane_normals,
346 line_origins,
347 line_directions,
348 return_distance=False,
349 return_denom=False,
350):
351 """
352 Given one line per plane find the intersection points.
354 Parameters
355 -----------
356 plane_origins : (n,3) float
357 Point on each plane
358 plane_normals : (n,3) float
359 Normal vector of each plane
360 line_origins : (n,3) float
361 Point at origin of each line
362 line_directions : (n,3) float
363 Direction vector of each line
364 return_distance : bool
365 Return distance from origin to point also
366 return_denom : bool
367 Return denominator, so you can check for small values
369 Returns
370 ----------
371 on_plane : (n,3) float
372 Points on specified planes
373 valid : (n,) bool
374 Did plane intersect line or not
375 distance : (n,) float
376 [OPTIONAL] Distance from point
377 denom : (n,) float
378 [OPTIONAL] Denominator
379 """
381 # check input types
382 plane_origins = np.asanyarray(plane_origins, dtype=np.float64)
383 plane_normals = np.asanyarray(plane_normals, dtype=np.float64)
384 line_origins = np.asanyarray(line_origins, dtype=np.float64)
385 line_directions = np.asanyarray(line_directions, dtype=np.float64)
387 # vector from line to plane
388 origin_vectors = plane_origins - line_origins
390 projection_ori = util.diagonal_dot(origin_vectors, plane_normals)
391 projection_dir = util.diagonal_dot(line_directions, plane_normals)
393 valid = np.abs(projection_dir) > 1e-5
395 distance = np.divide(projection_ori[valid], projection_dir[valid])
397 on_plane = line_directions[valid] * distance.reshape((-1, 1))
398 on_plane += line_origins[valid]
400 result = [on_plane, valid]
402 if return_distance:
403 result.append(distance)
404 if return_denom:
405 result.append(projection_dir)
407 return result
410def slice_faces_plane(
411 vertices,
412 faces,
413 plane_normal,
414 plane_origin,
415 uv=None,
416 face_index=None,
417 cached_dots=None,
418):
419 """
420 Slice a mesh (given as a set of faces and vertices) with a plane, returning a
421 new mesh (again as a set of faces and vertices) that is the
422 portion of the original mesh to the positive normal side of the plane.
424 Parameters
425 ---------
426 vertices : (n, 3) float
427 Vertices of source mesh to slice
428 faces : (n, 3) int
429 Faces of source mesh to slice
430 plane_normal : (3,) float
431 Normal vector of plane to intersect with mesh
432 plane_origin : (3,) float
433 Point on plane to intersect with mesh
434 uv : (n, 2) float, optional
435 UV coordinates of source mesh to slice
436 face_index : ((m,) int)
437 Indexes of faces to slice. When no mask is provided, the
438 default is to slice all faces.
439 cached_dots : (n, 3) float
440 If an external function has stored dot
441 products pass them here to avoid recomputing
443 Returns
444 ----------
445 new_vertices : (n, 3) float
446 Vertices of sliced mesh
447 new_faces : (n, 3) int
448 Faces of sliced mesh
449 new_uv : (n, 2) int or None
450 UV coordinates of sliced mesh
451 """
453 if len(vertices) == 0:
454 return vertices, faces, uv
456 have_uv = uv is not None
458 # Construct a mask for the faces to slice.
459 if face_index is None:
460 mask = np.ones(len(faces), dtype=bool)
461 else:
462 mask = np.zeros(len(faces), dtype=bool)
463 mask[face_index] = True
465 if cached_dots is not None:
466 dots = cached_dots
467 else:
468 # dot product of each vertex with the plane normal indexed by face
469 # so for each face the dot product of each vertex is a row
470 # shape is the same as faces (n,3)
471 dots = np.dot(vertices - plane_origin, plane_normal)
473 # Find vertex orientations w.r.t. faces for all triangles:
474 # -1 -> vertex "inside" plane (positive normal direction)
475 # 0 -> vertex on plane
476 # 1 -> vertex "outside" plane (negative normal direction)
477 signs = np.zeros(len(vertices), dtype=np.int8)
478 signs[dots < -tol.merge] = 1
479 signs[dots > tol.merge] = -1
480 signs = signs[faces]
482 # Find all triangles that intersect this plane
483 # onedge <- indices of all triangles intersecting the plane
484 # inside <- indices of all triangles "inside" the plane (positive normal)
485 # adding the int8 columns is ~10x faster than `sum(axis=1)` here
486 signs_abs = np.abs(signs)
487 signs_sum = signs[:, 0] + signs[:, 1] + signs[:, 2]
488 signs_asum = signs_abs[:, 0] + signs_abs[:, 1] + signs_abs[:, 2]
490 # Cases:
491 # (0,0,0), (-1,0,0), (-1,-1,0), (-1,-1,-1) <- inside
492 # (1,0,0), (1,1,0), (1,1,1) <- outside
493 # (1,0,-1), (1,-1,-1), (1,1,-1) <- onedge
494 onedge = np.logical_and(signs_asum >= 2, np.abs(signs_sum) <= 1) & mask
496 # faces not in the mask are kept unchanged
497 inside = (signs_sum == -signs_asum) | ~mask
499 # for any faces that lie exactly on-the-plane
500 # we want to only include them if their normal
501 # is backwards from the slicing normal
502 on_plane = (signs_asum == 0) & mask
503 if on_plane.any():
504 # compute the normals and whether
505 # face is degenerate here
506 check, valid = tm.normals(vertices[faces[on_plane]])
507 # only include faces back from normal
508 dot_check = np.dot(check, plane_normal)
509 # exclude any degenerate faces from the result
510 inside[on_plane] = valid
511 # exclude the degenerate face from our mask
512 on_plane[on_plane] = valid
513 # apply results for this subset
514 inside[on_plane] = dot_check < 0.0
516 # Automatically include all faces that are "inside"
517 new_faces = faces[inside]
519 # Separate faces on the edge into two cases: those which will become
520 # quads (two vertices inside plane) and those which will become triangles
521 # (one vertex inside plane)
522 cut_triangles = vertices[faces[onedge]]
523 cut_faces_quad = faces[np.logical_and(onedge, signs_sum < 0)]
524 cut_faces_tri = faces[np.logical_and(onedge, signs_sum >= 0)]
525 cut_signs_quad = signs[np.logical_and(onedge, signs_sum < 0)]
526 cut_signs_tri = signs[np.logical_and(onedge, signs_sum >= 0)]
528 # If no faces to cut, the surface is not in contact with this plane.
529 # Thus, return a mesh with only the inside faces
530 if len(cut_faces_quad) + len(cut_faces_tri) == 0:
531 if len(new_faces) == 0:
532 # if no new faces at all return empty arrays
533 empty = (
534 np.zeros((0, 3), dtype=np.float64),
535 np.zeros((0, 3), dtype=np.int64),
536 np.zeros((0, 2), dtype=np.float64) if have_uv else None,
537 )
538 return empty
540 # find the unique indices in the new faces
541 # using an integer-only unique function
542 unique, inverse = grouping.unique_bincount(
543 new_faces.reshape(-1), minlength=len(vertices), return_inverse=True
544 )
546 # use the unique indices for our final vertices and faces
547 final_vert = vertices[unique]
548 final_face = inverse.reshape((-1, 3))
549 final_uv = uv[unique] if have_uv else None
551 return final_vert, final_face, final_uv
553 # Extract the intersections of each triangle's edges with the plane
554 origins = cut_triangles
555 directions = np.roll(origins, -1, axis=1) - origins
556 numerator = (plane_origin - origins).dot(plane_normal)
557 denominator = np.dot(directions, plane_normal)
558 denominator[denominator == 0.0] = 1e-12 # prevent division by zero
559 dist = np.divide(numerator, denominator)
560 # Vertices classified on the plane must be reused as edge endpoints.
561 # Recomputing their intersections can create nearby, distinct vertices
562 # and leave cracks when the sliced boundary is capped.
563 cut_signs = signs[onedge]
564 dist[cut_signs == 0] = 0.0
565 dist[np.roll(cut_signs, -1, axis=1) == 0] = 1.0
566 # intersection points for each segment
567 int_points = dist[:, :, None] * directions + origins
568 if have_uv:
569 # UVs are interpolated along each cut edge exactly like positions
570 uv_origins = uv[faces[onedge]]
571 uv_directions = np.roll(uv_origins, -1, axis=1) - uv_origins
572 int_points = np.concatenate(
573 (int_points, dist[:, :, None] * uv_directions + uv_origins), axis=2
574 )
576 # Initialize the array of new vertices with the current vertices
577 new_vertices = vertices
578 new_quad_vertices = np.zeros((0, int_points.shape[2]))
579 new_tri_vertices = np.zeros((0, int_points.shape[2]))
581 # Handle the case where a new quad is formed by the intersection
582 # First, extract the intersection points belonging to a new quad
583 quad_int_points = int_points[(signs_sum < 0)[onedge], :, :]
584 num_quads = len(quad_int_points)
585 if num_quads > 0:
586 # Extract the vertex on the outside of the plane, then get the vertices
587 # (in CCW order of the inside vertices)
588 quad_int_inds = np.where(cut_signs_quad == 1)[1]
589 quad_int_verts = cut_faces_quad[
590 np.stack((range(num_quads), range(num_quads)), axis=1),
591 np.stack(((quad_int_inds + 1) % 3, (quad_int_inds + 2) % 3), axis=1),
592 ]
594 # Fill out new quad faces with the intersection points as vertices
595 new_quad_faces = np.append(
596 quad_int_verts,
597 np.arange(len(new_vertices), len(new_vertices) + 2 * num_quads).reshape(
598 num_quads, 2
599 ),
600 axis=1,
601 )
603 # Extract correct intersection points from int_points and order them in
604 # the same way as they were added to faces
605 new_quad_vertices = quad_int_points[
606 np.stack((range(num_quads), range(num_quads)), axis=1),
607 np.stack((((quad_int_inds + 2) % 3).T, quad_int_inds.T), axis=1),
608 :,
609 ].reshape(2 * num_quads, -1)
611 # Add new vertices to existing vertices, triangulate quads, and add the
612 # resulting triangles to the new faces
613 new_vertices = np.append(new_vertices, new_quad_vertices[:, :3], axis=0)
614 new_tri_faces_from_quads = geometry.triangulate_quads(new_quad_faces)
615 new_faces = np.append(new_faces, new_tri_faces_from_quads, axis=0)
617 # Handle the case where a new triangle is formed by the intersection
618 # First, extract the intersection points belonging to a new triangle
619 tri_int_points = int_points[(signs_sum >= 0)[onedge], :, :]
620 num_tris = len(tri_int_points)
621 if num_tris > 0:
622 # Extract the single vertex for each triangle inside the plane and get the
623 # inside vertices (CCW order)
624 tri_int_inds = np.where(cut_signs_tri == -1)[1]
625 tri_int_verts = cut_faces_tri[range(num_tris), tri_int_inds].reshape(num_tris, 1)
627 # Fill out new triangles with the intersection points as vertices
628 new_tri_faces = np.append(
629 tri_int_verts,
630 np.arange(len(new_vertices), len(new_vertices) + 2 * num_tris).reshape(
631 num_tris, 2
632 ),
633 axis=1,
634 )
636 # Extract correct intersection points and order them in the same way as
637 # the vertices were added to the faces
638 new_tri_vertices = tri_int_points[
639 np.stack((range(num_tris), range(num_tris)), axis=1),
640 np.stack((tri_int_inds.T, ((tri_int_inds + 2) % 3).T), axis=1),
641 :,
642 ].reshape(2 * num_tris, -1)
644 # Append new vertices and new faces
645 new_vertices = np.append(new_vertices, new_tri_vertices[:, :3], axis=0)
646 new_faces = np.append(new_faces, new_tri_faces, axis=0)
648 # find the unique indices in the new faces
649 # using an integer-only unique function
650 unique, inverse = grouping.unique_bincount(
651 new_faces.reshape(-1), minlength=len(new_vertices), return_inverse=True
652 )
654 # use the unique indexes for our final vertex and faces
655 final_vert = new_vertices[unique]
656 final_face = inverse.reshape((-1, 3))
658 final_uv = None
659 if have_uv:
660 # the UVs of the new vertices were carried in the extra columns
661 new_uv = np.concatenate((new_quad_vertices[:, 3:], new_tri_vertices[:, 3:]))
662 final_uv = np.concatenate([uv, new_uv])[unique]
664 return final_vert, final_face, final_uv
667def slice_mesh_plane(
668 mesh,
669 plane_normal,
670 plane_origin,
671 face_index=None,
672 cap=False,
673 engine=None,
674 **kwargs,
675):
676 """
677 Slice a mesh with a plane returning a new mesh that is the
678 portion of the original mesh to the positive normal side
679 of the plane.
681 Parameters
682 ---------
683 mesh : Trimesh object
684 Source mesh to slice
685 plane_normal : (3,) float
686 Normal vector of plane to intersect with mesh
687 plane_origin : (3,) float
688 Point on plane to intersect with mesh
689 cap : bool
690 If True, cap the result with a triangulated polygon
691 face_index : ((m,) int)
692 Indexes of mesh.faces to slice. When no mask is provided, the
693 default is to slice all faces.
694 cached_dots : (n, 3) float
695 If an external function has stored dot
696 products pass them here to avoid recomputing
697 engine : None or str
698 Triangulation engine passed to `triangulate_polygon`
699 kwargs : dict
700 Passed to the newly created sliced mesh
702 Returns
703 ----------
704 new_mesh : Trimesh object
705 Sliced mesh
706 """
707 # check input for none
708 if mesh is None:
709 return None
711 # avoid circular import
712 from scipy.spatial import cKDTree
714 from .base import Trimesh
715 from .creation import triangulate_polygon
716 from .path import polygons
717 from .visual import TextureVisuals
719 # check input plane
720 plane_normal = np.asanyarray(plane_normal, dtype=np.float64)
721 plane_origin = np.asanyarray(plane_origin, dtype=np.float64)
723 # check to make sure origins and normals have acceptable shape
724 shape_ok = (
725 (plane_origin.shape == (3,) or util.is_shape(plane_origin, (-1, 3)))
726 and (plane_normal.shape == (3,) or util.is_shape(plane_normal, (-1, 3)))
727 and plane_origin.shape == plane_normal.shape
728 )
729 if not shape_ok:
730 raise ValueError("plane origins and normals must be (n, 3)!")
732 # start with copy of original mesh, faces, and vertices
733 vertices = mesh.vertices.copy()
734 faces = mesh.faces.copy()
736 # We copy the UV coordinates if available
737 has_uv = (
738 hasattr(mesh.visual, "uv") and np.shape(mesh.visual.uv) == (len(mesh.vertices), 2)
739 ) and not cap
740 uv = mesh.visual.uv.copy() if has_uv else None
742 if "process" not in kwargs:
743 kwargs["process"] = False
745 # slice away specified planes
746 for origin, normal in zip(
747 plane_origin.reshape((-1, 3)), plane_normal.reshape((-1, 3))
748 ):
749 # save the new vertices and faces
750 vertices, faces, uv = slice_faces_plane(
751 vertices=vertices,
752 faces=faces,
753 uv=uv,
754 plane_normal=normal,
755 plane_origin=origin,
756 face_index=face_index,
757 )
758 # check if cap arg specified
759 if cap:
760 if face_index:
761 # This hasn't been implemented yet.
762 raise NotImplementedError("face_index and cap can't be used together")
764 # start by deduplicating vertices again
765 unique, inverse = grouping.unique_rows(vertices)
766 vertices = vertices[unique]
767 # will collect additional faces
768 f = inverse[faces]
769 # remove degenerate faces by checking to make sure
770 # that each face has three unique indices
771 f = f[(f[:, :1] != f[:, 1:]).all(axis=1)]
772 # transform to the cap plane
773 to_2D = geometry.plane_transform(origin=origin, normal=-normal)
774 to_3D = np.linalg.inv(to_2D)
776 vertices_2D = tf.transform_points(vertices, to_2D)
777 edges = geometry.faces_to_edges(f)
778 edges.sort(axis=1)
780 on_plane = np.abs(vertices_2D[:, 2]) < 1e-8
781 edges = edges[on_plane[edges].all(axis=1)]
782 edges = edges[edges[:, 0] != edges[:, 1]]
784 unique_edge = grouping.group_rows(edges, require_count=1)
785 if len(unique) < 3:
786 continue
788 tree = cKDTree(vertices)
789 # collect new faces
790 faces = [f]
791 for p in polygons.edges_to_polygons(edges[unique_edge], vertices_2D[:, :2]):
792 # triangulate cap and raise an error if any new vertices were inserted
793 vn, fn = triangulate_polygon(p, engine=engine, force_vertices=True)
794 # collect the original index for the new vertices
795 vn3 = tf.transform_points(util.stack_3D(vn), to_3D)
796 distance, vid = tree.query(vn3)
797 if distance.max() > 1e-8:
798 util.log.debug("triangulate may have inserted vertex!")
799 # triangulation should not have inserted vertices
800 nf = vid[fn]
801 # hmm but it may have returned faces that are now degenerate
802 nf_ok = (nf[:, 1:] != nf[:, :1]).all(axis=1) & (nf[:, 1] != nf[:, 2])
803 faces.append(nf[nf_ok])
805 faces = np.vstack(faces)
807 visual = (
808 TextureVisuals(uv=uv, material=mesh.visual.material.copy()) if has_uv else None
809 )
811 # return the sliced mesh
812 return Trimesh(vertices=vertices, faces=faces, visual=visual, **kwargs)