Coverage for trimesh/collision.py: 85%
264 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
1import collections
3import numpy as np
5from .typed import Hashable
7try:
8 # pip install python-fcl
9 import fcl
10except BaseException:
11 fcl = None
14# contact cap per pair
15COLLISION_PER_PAIR_CAP = 100000
18def _fcl_collide_callback(o1, o2, cdata):
19 # unlike fcl.defaultCollisionCallback never halt traversal
20 # early that would silently drop later colliding pairs
21 fcl.collide(o1=o1, o2=o2, request=cdata.request, result=cdata.result)
22 return False
25def _fcl_collision_data(return_names, return_data):
26 # build (cdata, callback) sized for what the caller actually needs
27 if not (return_names or return_data):
28 return fcl.CollisionData(), fcl.defaultCollisionCallback
29 # one contact identifies a pair only ask for more if the
30 # caller wants the contact data itself
31 request = fcl.CollisionRequest(
32 num_max_contacts=COLLISION_PER_PAIR_CAP if return_data else 1,
33 enable_contact=True,
34 )
35 return fcl.CollisionData(request=request), _fcl_collide_callback
38class ContactData:
39 """
40 Data structure for holding information about a collision contact.
41 """
43 def __init__(self, names, contact):
44 """
45 Initialize a ContactData.
47 Parameters
48 ----------
49 names : list of str
50 The names of the two objects in order.
51 contact : fcl.Contact
52 The contact in question.
53 """
54 self.names = set(names)
55 self._inds = {names[0]: contact.b1, names[1]: contact.b2}
56 self._normal = contact.normal
57 self._point = contact.pos
58 self._depth = contact.penetration_depth
60 @property
61 def normal(self):
62 """
63 The 3D intersection normal for this contact.
65 Returns
66 -------
67 normal : (3,) float
68 The intersection normal.
69 """
70 return self._normal
72 @property
73 def point(self):
74 """
75 The 3D point of intersection for this contact.
77 Returns
78 -------
79 point : (3,) float
80 The intersection point.
81 """
82 return self._point
84 @property
85 def depth(self):
86 """
87 The penetration depth of the 3D point of intersection for this contact.
89 Returns
90 -------
91 depth : float
92 The penetration depth.
93 """
94 return self._depth
96 def index(self, name):
97 """
98 Returns the index of the face in contact for the mesh with
99 the given name.
101 Parameters
102 ----------
103 name : str
104 The name of the target object.
106 Returns
107 -------
108 index : int
109 The index of the face in collision
110 """
111 return self._inds[name]
114class DistanceData:
115 """
116 Data structure for holding information about a distance query.
117 """
119 def __init__(self, names, result):
120 """
121 Initialize a DistanceData.
123 Parameters
124 ----------
125 names : list of str
126 The names of the two objects in order.
127 contact : fcl.DistanceResult
128 The distance query result.
129 """
130 self.names = set(names)
131 self._inds = {names[0]: result.b1, names[1]: result.b2}
132 self._points = {
133 names[0]: result.nearest_points[0],
134 names[1]: result.nearest_points[1],
135 }
136 self._distance = result.min_distance
138 @property
139 def distance(self):
140 """
141 Returns the distance between the two objects.
143 Returns
144 -------
145 distance : float
146 The euclidean distance between the objects.
147 """
148 return self._distance
150 def index(self, name):
151 """
152 Returns the index of the closest face for the mesh with
153 the given name.
155 Parameters
156 ----------
157 name : str
158 The name of the target object.
160 Returns
161 -------
162 index : int
163 The index of the face in collisoin.
164 """
165 return self._inds[name]
167 def point(self, name):
168 """
169 The 3D point of closest distance on the mesh with the given name.
171 Parameters
172 ----------
173 name : str
174 The name of the target object.
176 Returns
177 -------
178 point : (3,) float
179 The closest point.
180 """
181 return self._points[name]
184class CollisionManager:
185 """
186 A mesh-mesh collision manager.
187 """
189 def __init__(self):
190 """
191 Initialize a mesh-mesh collision manager.
192 """
193 if fcl is None:
194 raise ValueError("No FCL Available! Please install the python-fcl library")
195 # {name: {geom:, obj}}
196 self._objs = {}
197 # {id(bvh) : str, name}
198 # unpopulated values will return None
199 self._names = collections.defaultdict(lambda: None)
201 self._manager = fcl.DynamicAABBTreeCollisionManager()
202 self._manager.setup()
204 def add_object(self, name, mesh, transform=None):
205 """
206 Add an object to the collision manager.
208 If an object with the given name is already in the manager,
209 replace it.
211 Parameters
212 ----------
213 name : str
214 An identifier for the object
215 mesh : Trimesh object
216 The geometry of the collision object
217 transform : (4,4) float
218 Homogeneous transform matrix for the object
219 """
221 # if no transform passed, assume identity transform
222 if transform is None:
223 transform = np.eye(4)
224 transform = np.asanyarray(transform, dtype=np.float32)
225 if transform.shape != (4, 4):
226 raise ValueError("transform must be (4,4)!")
228 # create BVH/Convex
229 geom = self._get_fcl_obj(mesh)
231 # create the FCL transform from (4,4) matrix
232 t = fcl.Transform(transform[:3, :3], transform[:3, 3])
233 o = fcl.CollisionObject(geom, t)
235 # Add collision object to set
236 if name in self._objs:
237 self._manager.unregisterObject(self._objs[name])
238 self._objs[name] = {"obj": o, "geom": geom}
239 # store the name of the geometry
240 self._names[id(geom)] = name
242 self._manager.registerObject(o)
243 self._manager.update()
244 return o
246 def remove_object(self, name):
247 """
248 Delete an object from the collision manager.
250 Parameters
251 ----------
252 name : str
253 The identifier for the object
254 """
255 if name in self._objs:
256 self._manager.unregisterObject(self._objs[name]["obj"])
257 self._manager.update(self._objs[name]["obj"])
258 # remove objects from _objs
259 geom_id = id(self._objs.pop(name)["geom"])
260 # remove names
261 self._names.pop(geom_id)
262 else:
263 raise ValueError(f"{name} not in collision manager!")
265 def set_transform(self, name, transform):
266 """
267 Set the transform for one of the manager's objects.
268 This replaces the prior transform.
270 Parameters
271 ----------
272 name : str
273 An identifier for the object already in the manager
274 transform : (4,4) float
275 A new homogeneous transform matrix for the object
276 """
277 if name in self._objs:
278 o = self._objs[name]["obj"]
279 o.setRotation(transform[:3, :3])
280 o.setTranslation(transform[:3, 3])
281 self._manager.update(o)
282 else:
283 raise ValueError(f"{name} not in collision manager!")
285 def in_collision_single(
286 self, mesh, transform=None, return_names=False, return_data=False
287 ):
288 """
289 Check a single object for collisions against all objects in the
290 manager.
292 Parameters
293 ----------
294 mesh : Trimesh object
295 The geometry of the collision object
296 transform : (4,4) float
297 Homogeneous transform matrix
298 return_names : bool
299 If true, a set is returned containing the names
300 of all objects in collision with the object
301 return_data : bool
302 If true, a list of ContactData is returned as well
304 Returns
305 ------------
306 is_collision : bool
307 True if a collision occurs and False otherwise
308 names : set of str
309 [OPTIONAL] The set of names of objects that collided with the
310 provided one
311 contacts : list of ContactData
312 [OPTIONAL] All contacts detected
313 """
314 if transform is None:
315 transform = np.eye(4)
317 # create BVH/Convex
318 geom = self._get_fcl_obj(mesh)
320 # create the FCL transform from (4,4) matrix
321 t = fcl.Transform(transform[:3, :3], transform[:3, 3])
322 o = fcl.CollisionObject(geom, t)
324 cdata, callback = _fcl_collision_data(return_names, return_data)
325 self._manager.collide(o, cdata, callback)
326 result = cdata.result.is_collision
328 # If we want to return the objects that were collision, collect them.
329 objs_in_collision = set()
330 contact_data = []
331 if return_names or return_data:
332 for contact in cdata.result.contacts:
333 cg = contact.o1
334 if cg == geom:
335 cg = contact.o2
336 name = self._extract_name(cg)
338 names = (name, "__external")
339 if cg == contact.o2:
340 names = tuple(reversed(names))
342 if return_names:
343 objs_in_collision.add(name)
344 if return_data:
345 contact_data.append(ContactData(names, contact))
347 if return_names and return_data:
348 return result, objs_in_collision, contact_data
349 elif return_names:
350 return result, objs_in_collision
351 elif return_data:
352 return result, contact_data
353 else:
354 return result
356 def in_collision_internal(self, return_names=False, return_data=False):
357 """
358 Check if any pair of objects in the manager collide with one another.
360 Parameters
361 ----------
362 return_names : bool
363 If true, a set is returned containing the names
364 of all pairs of objects in collision.
365 return_data : bool
366 If true, a list of ContactData is returned as well
368 Returns
369 -------
370 is_collision : bool
371 True if a collision occurred between any pair of objects
372 and False otherwise
373 names : set of 2-tup
374 The set of pairwise collisions. Each tuple
375 contains two names in alphabetical order indicating
376 that the two corresponding objects are in collision.
377 contacts : list of ContactData
378 All contacts detected
379 """
380 cdata, callback = _fcl_collision_data(return_names, return_data)
381 self._manager.collide(cdata, callback)
383 result = cdata.result.is_collision
385 objs_in_collision = set()
386 contact_data = []
387 if return_names or return_data:
388 for contact in cdata.result.contacts:
389 names = (self._extract_name(contact.o1), self._extract_name(contact.o2))
391 if return_names:
392 objs_in_collision.add(tuple(sorted(names)))
393 if return_data:
394 contact_data.append(ContactData(names, contact))
396 if return_names and return_data:
397 return result, objs_in_collision, contact_data
398 elif return_names:
399 return result, objs_in_collision
400 elif return_data:
401 return result, contact_data
402 else:
403 return result
405 def in_collision_other(self, other_manager, return_names=False, return_data=False):
406 """
407 Check if any object from this manager collides with any object
408 from another manager.
410 Parameters
411 -------------------
412 other_manager : CollisionManager
413 Another collision manager object
414 return_names : bool
415 If true, a set is returned containing the names
416 of all pairs of objects in collision.
417 return_data : bool
418 If true, a list of ContactData is returned as well
420 Returns
421 -------------
422 is_collision : bool
423 True if a collision occurred between any pair of objects
424 and False otherwise
425 names : set of 2-tup
426 The set of pairwise collisions. Each tuple
427 contains two names (first from this manager,
428 second from the other_manager) indicating
429 that the two corresponding objects are in collision.
430 contacts : list of ContactData
431 All contacts detected
432 """
433 cdata, callback = _fcl_collision_data(return_names, return_data)
434 self._manager.collide(other_manager._manager, cdata, callback)
435 result = cdata.result.is_collision
437 objs_in_collision = set()
438 contact_data = []
439 if return_names or return_data:
440 for contact in cdata.result.contacts:
441 reverse = False
442 names = (
443 self._extract_name(contact.o1),
444 other_manager._extract_name(contact.o2),
445 )
446 if names[0] is None:
447 names = (
448 self._extract_name(contact.o2),
449 other_manager._extract_name(contact.o1),
450 )
451 reverse = True
453 if return_names:
454 objs_in_collision.add(names)
455 if return_data:
456 if reverse:
457 names = tuple(reversed(names))
458 contact_data.append(ContactData(names, contact))
460 if return_names and return_data:
461 return result, objs_in_collision, contact_data
462 elif return_names:
463 return result, objs_in_collision
464 elif return_data:
465 return result, contact_data
466 else:
467 return result
469 def min_distance_single(
470 self, mesh, transform=None, return_name=False, return_data=False
471 ):
472 """
473 Get the minimum distance between a single object and any
474 object in the manager.
476 Parameters
477 ---------------
478 mesh : Trimesh object
479 The geometry of the collision object
480 transform : (4,4) float
481 Homogeneous transform matrix for the object
482 return_name : bool
483 If true, return name of the closest object
484 return_data : bool
485 If true, a DistanceData object is returned as well
487 Returns
488 -------------
489 distance : float
490 Min distance between mesh and any object in the manager
491 name : str
492 The name of the object in the manager that was closest
493 data : DistanceData
494 Extra data about the distance query
495 """
496 if transform is None:
497 transform = np.eye(4)
499 # create BVH/Convex
500 geom = self._get_fcl_obj(mesh)
502 # create the FCL transform from (4,4) matrix
503 t = fcl.Transform(transform[:3, :3], transform[:3, 3])
504 o = fcl.CollisionObject(geom, t)
506 # Collide with manager's objects
507 ddata = fcl.DistanceData(fcl.DistanceRequest(enable_signed_distance=True))
508 if return_data:
509 ddata = fcl.DistanceData(
510 fcl.DistanceRequest(
511 enable_nearest_points=True, enable_signed_distance=True
512 ),
513 fcl.DistanceResult(),
514 )
516 self._manager.distance(o, ddata, fcl.defaultDistanceCallback)
518 distance = ddata.result.min_distance
520 # If we want to return the objects that were collision, collect them.
521 name, data = None, None
522 if return_name or return_data:
523 cg = ddata.result.o1
524 if cg == geom:
525 cg = ddata.result.o2
527 name = self._extract_name(cg)
529 names = (name, "__external")
530 if cg == ddata.result.o2:
531 names = tuple(reversed(names))
532 data = DistanceData(names, ddata.result)
534 if return_name and return_data:
535 return distance, name, data
536 elif return_name:
537 return distance, name
538 elif return_data:
539 return distance, data
540 else:
541 return distance
543 def min_distance_internal(self, name=None, return_names=False, return_data=False):
544 """
545 Get the minimum distance between objects in the manager.
547 If name is provided, computes the minimum distance between the
548 specified object and any other object in the manager.
549 If name is None, computes the minimum distance between any pair
550 of objects in the manager.
552 Parameters
553 -------------
554 name : str or None
555 If provided, the identifier for the object already in the manager
556 to compute distances from. If None, computes distances between
557 all pairs of objects.
558 return_names : bool
559 If true, a 2-tuple is returned containing the names
560 of the closest objects.
561 return_data : bool
562 If true, a DistanceData object is returned as well
564 Returns
565 -----------
566 distance : float
567 Min distance between objects
568 names : (2,) str
569 The names of the closest objects
570 data : DistanceData
571 Extra data about the distance query
572 """
573 ddata = fcl.DistanceData(fcl.DistanceRequest(enable_signed_distance=True))
574 if return_data:
575 ddata = fcl.DistanceData(
576 fcl.DistanceRequest(
577 enable_nearest_points=True,
578 enable_signed_distance=True,
579 ),
580 fcl.DistanceResult(),
581 )
583 # If name is provided, compute distance from that object to others
584 if name is not None:
585 if name not in self._objs:
586 raise ValueError(f"{name} not in collision manager!")
587 obj = self._objs[name]["obj"]
588 # remove object from manager temporarily
589 self._manager.unregisterObject(obj)
590 self._manager.update(obj)
592 # compute distance
593 self._manager.distance(obj, ddata, fcl.defaultDistanceCallback)
595 # add it back to the manager
596 self._manager.registerObject(obj)
597 self._manager.update()
599 else:
600 # Compute distance between any pair of objects
601 self._manager.distance(ddata, fcl.defaultDistanceCallback)
603 distance = ddata.result.min_distance
605 names, data = None, None
606 if return_names or return_data:
607 names = (
608 self._extract_name(ddata.result.o1),
609 self._extract_name(ddata.result.o2),
610 )
611 data = DistanceData(names, ddata.result)
612 names = tuple(sorted(names))
614 if return_names and return_data:
615 return distance, names, data
616 elif return_names:
617 return distance, names
618 elif return_data:
619 return distance, data
620 else:
621 return distance
623 def min_distance_other(self, other_manager, return_names=False, return_data=False):
624 """
625 Get the minimum distance between any pair of objects,
626 one in each manager.
628 Parameters
629 ----------
630 other_manager : CollisionManager
631 Another collision manager object
632 return_names : bool
633 If true, a 2-tuple is returned containing
634 the names of the closest objects.
635 return_data : bool
636 If true, a DistanceData object is returned as well
638 Returns
639 -----------
640 distance : float
641 The min distance between a pair of objects,
642 one from each manager.
643 names : 2-tup of str
644 A 2-tuple containing two names (first from this manager,
645 second from the other_manager) indicating
646 the two closest objects.
647 data : DistanceData
648 Extra data about the distance query
649 """
650 ddata = fcl.DistanceData(fcl.DistanceRequest(enable_signed_distance=True))
651 if return_data:
652 ddata = fcl.DistanceData(
653 fcl.DistanceRequest(
654 enable_nearest_points=True,
655 enable_signed_distance=True,
656 ),
657 fcl.DistanceResult(),
658 )
660 self._manager.distance(other_manager._manager, ddata, fcl.defaultDistanceCallback)
662 distance = ddata.result.min_distance
664 names, data = None, None
665 if return_names or return_data:
666 reverse = False
667 names = (
668 self._extract_name(ddata.result.o1),
669 other_manager._extract_name(ddata.result.o2),
670 )
671 if names[0] is None:
672 reverse = True
673 names = (
674 self._extract_name(ddata.result.o2),
675 other_manager._extract_name(ddata.result.o1),
676 )
678 dnames = tuple(names)
679 if reverse:
680 dnames = tuple(reversed(dnames))
681 data = DistanceData(dnames, ddata.result)
683 if return_names and return_data:
684 return distance, names, data
685 elif return_names:
686 return distance, names
687 elif return_data:
688 return distance, data
689 else:
690 return distance
692 def _get_fcl_obj(self, mesh):
693 """
694 Get a BVH or Convex for a mesh.
696 Parameters
697 -------------
698 mesh : Trimesh
699 Mesh to create BVH/Convex for
701 Returns
702 --------------
703 obj : fcl.BVHModel or fcl.Convex
704 BVH/Convex object of source mesh
705 """
707 if mesh.is_convex:
708 obj = mesh_to_convex(mesh)
709 else:
710 obj = mesh_to_BVH(mesh)
711 return obj
713 def _extract_name(self, geom) -> Hashable:
714 """
715 Retrieve the name of an object from the manager by its
716 CollisionObject, raising a KeyError if not found.
718 Parameters
719 -----------
720 geom : CollisionObject or BVHModel
721 Input model
723 Returns
724 ------------
725 name : Hashable
726 Name of input geometry
727 """
728 return self._names[id(geom)]
731def mesh_to_BVH(mesh):
732 """
733 Create a BVHModel object from a Trimesh object
735 Parameters
736 -----------
737 mesh : Trimesh
738 Input geometry
740 Returns
741 ------------
742 bvh : fcl.BVHModel
743 BVH of input geometry
744 """
745 bvh = fcl.BVHModel()
746 bvh.beginModel(num_tris_=len(mesh.faces), num_vertices_=len(mesh.vertices))
747 bvh.addSubModel(verts=mesh.vertices, triangles=mesh.faces)
748 bvh.endModel()
749 return bvh
752def mesh_to_convex(mesh):
753 """
754 Create a Convex object from a Trimesh object
756 Parameters
757 -----------
758 mesh : Trimesh
759 Input geometry
761 Returns
762 ------------
763 convex : fcl.Convex
764 Convex of input geometry
765 """
766 fs = np.concatenate(
767 (3 * np.ones((len(mesh.faces), 1), dtype=np.int64), mesh.faces), axis=1
768 )
769 return fcl.Convex(mesh.vertices, len(fs), fs.flatten())
772def scene_to_collision(scene):
773 """
774 Create collision objects from a trimesh.Scene object.
776 Parameters
777 ------------
778 scene : trimesh.Scene
779 Scene to create collision objects for
781 Returns
782 ------------
783 manager : CollisionManager
784 CollisionManager for objects in scene
785 objects: {node name: CollisionObject}
786 Collision objects for nodes in scene
787 """
788 manager = CollisionManager()
789 objects = {}
790 for node in scene.graph.nodes_geometry:
791 T, geometry = scene.graph[node]
792 objects[node] = manager.add_object(
793 name=node, mesh=scene.geometry[geometry], transform=T
794 )
795 return manager, objects