Coverage for trimesh/scene/scene.py: 90%
515 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
2import uuid
3import warnings
4from copy import deepcopy
5from hashlib import sha256
6from typing import TypeAlias
8# ruff doesn't recognize this correctly when we re-import it from trimesh.typed -_-
9import numpy as np
11from .. import caching, convex, grouping, inertia, transformations, units, util
12from ..constants import log
13from ..exchange import export
14from ..parent import Geometry, Geometry3D
15from ..registration import procrustes
16from ..typed import (
17 ArrayLike,
18 Floating,
19 Hashable,
20 Integer,
21 Iterable,
22 NDArray,
23 Sequence,
24 ViewerType,
25 float64,
26 int64,
27)
28from ..util import unique_name
29from . import cameras, lighting
30from .transforms import SceneGraph
32# the types of objects we can create a scene from
33GeometryInput: TypeAlias = Geometry | Iterable[Geometry] | dict[str, Geometry] | ArrayLike
36class Scene(Geometry3D):
37 """
38 A simple scene graph which can be rendered directly via
39 pyglet/openGL or through other endpoints such as a
40 raytracer. Meshes are added by name, which can then be
41 moved by updating transform in the transform tree.
42 """
44 def __init__(
45 self,
46 geometry: GeometryInput | None = None,
47 base_frame: Hashable = "world",
48 metadata: dict | None = None,
49 graph: SceneGraph | None = None,
50 camera: cameras.Camera | None = None,
51 lights: Sequence[lighting.Light] | None = None,
52 camera_transform: NDArray | None = None,
53 ):
54 """
55 Create a new Scene object.
57 Parameters
58 -------------
59 geometry : Trimesh, Path2D, Path3D PointCloud or list
60 Geometry to initially add to the scene
61 base_frame
62 Name of base frame
63 metadata
64 Any metadata about the scene
65 graph
66 A passed transform graph to use
67 camera : Camera or None
68 A passed camera to use
69 lights : [trimesh.scene.lighting.Light] or None
70 A passed lights to use
71 camera_transform
72 Homogeneous (4, 4) camera transform in the base frame
73 """
74 # mesh name : Trimesh object
75 self.geometry = collections.OrderedDict()
77 # create a new graph
78 self.graph = SceneGraph(base_frame=base_frame)
80 # create our cache
81 self._cache = caching.Cache(id_function=self.__hash__)
83 if geometry is not None:
84 # add passed geometry to scene
85 self.add_geometry(geometry)
87 # hold metadata about the scene
88 self.metadata = {}
89 if isinstance(metadata, dict):
90 self.metadata.update(metadata)
92 if graph is not None:
93 # if we've been passed a graph override the default
94 self.graph = graph
96 if lights is not None:
97 self.lights = lights
98 if camera is not None:
99 self.camera = camera
100 if camera_transform is not None:
101 self.camera_transform = camera_transform
103 def apply_transform(self, transform):
104 """
105 Apply a transform to all children of the base frame
106 without modifying any geometry.
108 Parameters
109 --------------
110 transform : (4, 4)
111 Homogeneous transformation matrix.
112 """
113 base = self.graph.base_frame
114 for child in self.graph.transforms.children[base]:
115 combined = np.dot(transform, self.graph[child][0])
116 self.graph.update(frame_from=base, frame_to=child, matrix=combined)
117 return self
119 def add_geometry(
120 self,
121 geometry: GeometryInput,
122 node_name: Hashable | None = None,
123 geom_name: str | None = None,
124 parent_node_name: Hashable | None = None,
125 transform: NDArray | None = None,
126 metadata: dict | None = None,
127 ):
128 """
129 Add a geometry to the scene.
131 If the mesh has multiple transforms defined in its
132 metadata, they will all be copied into the
133 TransformForest of the current scene automatically.
135 Parameters
136 ----------
137 geometry : Trimesh, Path2D, Path3D PointCloud or list
138 Geometry to initially add to the scene
139 node_name : None or str
140 Name of the added node.
141 geom_name : None or str
142 Name of the added geometry.
143 parent_node_name : None or str
144 Name of the parent node in the graph.
145 transform : None or (4, 4) float
146 Transform that applies to the added node.
147 metadata : None or dict
148 Optional metadata for the node.
150 Returns
151 ----------
152 node_name : str
153 Name of single node in self.graph (passed in) or None if
154 node was not added (eg. geometry was null or a Scene).
155 """
157 if geometry is None:
158 return
159 # PointCloud objects will look like a sequence
160 elif util.is_sequence(geometry):
161 # if passed a sequence add all elements
162 return [
163 self.add_geometry(
164 geometry=value,
165 node_name=node_name,
166 geom_name=geom_name,
167 parent_node_name=parent_node_name,
168 transform=transform,
169 metadata=metadata,
170 )
171 for value in geometry # type: ignore
172 ]
173 elif isinstance(geometry, dict):
174 # if someone passed us a dict of geometry
175 return {
176 k: self.add_geometry(geometry=v, geom_name=k, metadata=metadata)
177 for k, v in geometry.items()
178 }
180 elif isinstance(geometry, Scene):
181 # concatenate current scene with passed scene
182 concat = self + geometry
183 # replace geometry in-place
184 self.geometry.clear()
185 self.geometry.update(concat.geometry)
186 # replace graph data with concatenated graph
187 self.graph.transforms = concat.graph.transforms
188 return
190 # get or create a name to reference the geometry by
191 if geom_name is not None:
192 # if name is passed use it
193 name = geom_name
194 elif "name" in geometry.metadata:
195 # if name is in metadata use it
196 name = geometry.metadata["name"]
197 elif geometry.source.file_name is not None:
198 name = geometry.source.file_name
199 else:
200 # try to create a simple name
201 name = "geometry_" + str(len(self.geometry))
203 # if its already taken use our unique name logic
204 name = unique_name(start=name, contains=self.geometry.keys())
205 # save the geometry reference
206 self.geometry[name] = geometry
208 # create a unique node name if not passed
209 if node_name is None:
210 # if the name of the geometry is also a transform node
211 # which graph nodes already exist
212 existing = self.graph.transforms.node_data.keys()
213 # find a name that isn't contained already starting
214 # at the name we have
215 node_name = unique_name(name, existing)
216 assert node_name not in existing
218 if transform is None:
219 # create an identity transform from parent_node
220 transform = np.eye(4)
222 self.graph.update(
223 frame_to=node_name,
224 frame_from=parent_node_name,
225 matrix=transform,
226 geometry=name,
227 geometry_flags={"visible": True},
228 metadata=metadata,
229 )
231 return node_name
233 def delete_geometry(self, names: set | str | Sequence) -> None:
234 """
235 Delete one more multiple geometries from the scene and also
236 remove any node in the transform graph which references it.
238 Parameters
239 --------------
240 names : str | set | Sequence
241 One or more names that reference self.geometry
242 """
243 # make sure we have a set we can check
244 if isinstance(names, str):
245 names = [names]
246 names = set(names)
248 # remove the geometry reference from relevant nodes
249 self.graph.remove_geometries(names)
250 # remove the geometries from our geometry store
251 [self.geometry.pop(name, None) for name in names]
253 def strip_visuals(self) -> None:
254 """
255 Strip visuals from every Trimesh geometry
256 and set them to an empty `ColorVisuals`.
257 """
258 from ..visual.color import ColorVisuals
260 for geometry in self.geometry.values():
261 if util.is_instance_named(geometry, "Trimesh"):
262 geometry.visual = ColorVisuals(mesh=geometry)
264 def simplify_quadric_decimation(
265 self,
266 percent: Floating | None = None,
267 face_count: Integer | None = None,
268 aggression: Integer | None = None,
269 ) -> None:
270 """
271 Apply in-place `mesh.simplify_quadric_decimation` to any meshes
272 in the scene.
274 Parameters
275 -----------
276 percent
277 A number between 0.0 and 1.0 for how much
278 face_count
279 Target number of faces desired in the resulting mesh.
280 aggression
281 An integer between `0` and `10`, the scale being roughly
282 `0` is "slow and good" and `10` being "fast and bad."
284 """
285 # save the updates for after the loop
286 updates = {}
287 for k, v in self.geometry.items():
288 if hasattr(v, "simplify_quadric_decimation"):
289 updates[k] = v.simplify_quadric_decimation(
290 percent=percent, face_count=face_count, aggression=aggression
291 )
292 self.geometry.update(updates)
294 def __hash__(self) -> int:
295 """
296 Return information about scene which is hashable.
298 Returns
299 ---------
300 hashed
301 String hashing scene.
302 """
303 # avoid accessing attribute in tight loop
304 geometry = self.geometry
305 # hash of geometry and transforms
306 # start with the last modified time of the scene graph
307 hashable = [hex(self.graph.transforms.__hash__())]
308 # take the re-hex string of the hash
309 hashable.extend(hex(geometry[k].__hash__()) for k in geometry.keys())
310 return caching.hash_fast("".join(hashable).encode("utf-8"))
312 @property
313 def is_empty(self) -> bool:
314 """
315 Does the scene have anything in it.
317 Returns
318 ----------
319 is_empty
320 True if nothing is in the scene
321 """
323 return len(self.geometry) == 0
325 @property
326 def is_valid(self) -> bool:
327 """
328 Is every geometry connected to the root node.
330 Returns
331 -----------
332 is_valid : bool
333 Does every geometry have a transform
334 """
335 if len(self.geometry) == 0:
336 return True
338 try:
339 referenced = {self.graph[i][1] for i in self.graph.nodes_geometry}
340 except BaseException:
341 # if connectivity to world frame is broken return false
342 return False
344 # every geometry is referenced
345 return referenced == set(self.geometry.keys())
347 @caching.cache_decorator
348 def bounds_corners(self) -> dict[str, NDArray[float64]]:
349 """
350 Get the post-transform AABB for each node
351 which has geometry defined.
353 Returns
354 -----------
355 corners
356 Bounds for each node with vertices:
357 {node_name : (2, 3) float}
358 """
359 # collect AABB for each geometry
360 corners = {}
361 # collect vertices for every mesh
362 vertices = {
363 k: m.vertices if hasattr(m, "vertices") and len(m.vertices) > 0 else m.bounds
364 for k, m in self.geometry.items()
365 }
366 # handle 2D geometries
367 vertices.update(
368 {
369 k: np.column_stack((v, np.zeros(len(v))))
370 for k, v in vertices.items()
371 if v is not None and v.shape[1] == 2
372 }
373 )
375 # loop through every node with geometry
376 for node_name in self.graph.nodes_geometry:
377 # access the transform and geometry name from node
378 transform, geometry_name = self.graph[node_name]
379 # will be None if no vertices for this node
380 points = vertices.get(geometry_name)
381 # skip empty geometries
382 if points is None:
383 continue
384 # apply just the rotation to skip N multiplies
385 dot = np.dot(transform[:3, :3], points.T)
386 # append the AABB with translation applied after
387 corners[node_name] = np.array(
388 [dot.min(axis=1) + transform[:3, 3], dot.max(axis=1) + transform[:3, 3]]
389 )
390 return corners
392 @caching.cache_decorator
393 def bounds(self) -> NDArray[float64] | None:
394 """
395 Return the overall bounding box of the scene.
397 Returns
398 --------
399 bounds : (2, 3) float or None
400 Position of [min, max] bounding box
401 Returns None if no valid bounds exist
402 """
403 bounds_corners = self.bounds_corners
404 if len(bounds_corners) == 0:
405 return None
406 # combine each geometry node AABB into a larger list
407 corners = np.vstack(list(self.bounds_corners.values()))
408 return np.array([corners.min(axis=0), corners.max(axis=0)], dtype=np.float64)
410 @caching.cache_decorator
411 def extents(self) -> NDArray[float64] | None:
412 """
413 Return the axis aligned box size of the current scene
414 or None if the scene is empty.
416 Returns
417 ----------
418 extents
419 Bounding box sides length or None for empty scene.
420 """
421 bounds = self.bounds
422 if bounds is None:
423 return None
424 return np.diff(bounds, axis=0).reshape(-1)
426 @caching.cache_decorator
427 def scale(self) -> float:
428 """
429 The approximate scale of the mesh
431 Returns
432 -----------
433 scale : float
434 The mean of the bounding box edge lengths
435 """
436 extents = self.extents
437 if extents is None:
438 return 1.0
439 return float((extents**2).sum() ** 0.5)
441 @caching.cache_decorator
442 def centroid(self) -> NDArray[float64] | None:
443 """
444 Return the center of the bounding box for the scene.
446 Returns
447 --------
448 centroid : (3) float
449 Point for center of bounding box
450 """
451 bounds = self.bounds
452 if bounds is None:
453 return None
454 centroid = np.mean(self.bounds, axis=0)
455 return centroid
457 @caching.cache_decorator
458 def center_mass(self) -> NDArray:
459 """
460 Find the center of mass for every instance in the scene.
462 Returns
463 ------------
464 center_mass : (3,) float
465 The center of mass of the scene
466 """
467 # get the center of mass and volume for each geometry
468 center_mass = {
469 k: m.center_mass
470 for k, m in self.geometry.items()
471 if hasattr(m, "center_mass")
472 }
473 mass = {k: m.mass for k, m in self.geometry.items() if hasattr(m, "mass")}
475 # get the geometry name and transform for each instance
476 graph = self.graph
477 instance = [graph[n] for n in graph.nodes_geometry]
479 # only instances whose geometry has mass properties can
480 # contribute to the center of mass: other geometry types
481 # (e.g. Path3D) have neither a center of mass nor a mass, and
482 # including them here either raised a KeyError or misaligned
483 # the transformed centers with their weights
484 instance = [(mat, g) for mat, g in instance if g in center_mass and g in mass]
485 if len(instance) == 0:
486 raise ValueError(
487 "Scene has no geometry with mass properties: center of mass is undefined"
488 )
490 # get the transformed center of mass for each instance
491 transformed = np.array(
492 [np.dot(mat, np.append(center_mass[g], 1))[:3] for mat, g in instance],
493 dtype=np.float64,
494 )
495 # weight the center of mass locations by volume
496 weights = np.array([mass[g] for _, g in instance], dtype=np.float64)
497 weights /= weights.sum()
498 return (transformed * weights.reshape((-1, 1))).sum(axis=0)
500 @caching.cache_decorator
501 def moment_inertia(self):
502 """
503 Return the moment of inertia of the current scene with
504 respect to the center of mass of the current scene.
506 Returns
507 ------------
508 inertia : (3, 3) float
509 Inertia with respect to cartesian axis at `scene.center_mass`
510 """
511 return inertia.scene_inertia(
512 scene=self, transform=transformations.translation_matrix(self.center_mass)
513 )
515 def moment_inertia_frame(self, transform):
516 """
517 Return the moment of inertia of the current scene relative
518 to a transform from the base frame.
520 Parameters
521 transform : (4, 4) float
522 Homogeneous transformation matrix.
524 Returns
525 -------------
526 inertia : (3, 3) float
527 Inertia tensor at requested frame.
528 """
529 return inertia.scene_inertia(scene=self, transform=transform)
531 @caching.cache_decorator
532 def area(self) -> float:
533 """
534 What is the summed area of every geometry which
535 has area.
537 Returns
538 ------------
539 area : float
540 Summed area of every instanced geometry
541 """
542 # get the area of every geometry that has an area property
543 areas = {n: g.area for n, g in self.geometry.items() if hasattr(g, "area")}
544 # sum the area including instancing
545 return sum(
546 (areas.get(self.graph[n][1], 0.0) for n in self.graph.nodes_geometry), 0.0
547 )
549 @caching.cache_decorator
550 def volume(self) -> float64:
551 """
552 What is the summed volume of every geometry which
553 has volume
555 Returns
556 ------------
557 volume : float
558 Summed area of every instanced geometry
559 """
560 # get the area of every geometry that has a volume attribute
561 volume = {n: g.volume for n, g in self.geometry.items() if hasattr(g, "volume")}
562 # sum the volume including instancing
563 return float64(
564 sum(
565 (volume.get(self.graph[n][1], 0.0) for n in self.graph.nodes_geometry),
566 0.0,
567 )
568 )
570 @caching.cache_decorator
571 def triangles(self) -> NDArray[float64]:
572 """
573 Return a correctly transformed polygon soup of the
574 current scene.
576 Returns
577 ----------
578 triangles : (n, 3, 3) float
579 Triangles in space
580 """
581 triangles = []
582 triangles_node = []
583 for node_name in self.graph.nodes_geometry:
584 # which geometry does this node refer to
585 transform, geometry_name = self.graph[node_name]
587 # get the actual potential mesh instance
588 geometry = self.geometry[geometry_name]
589 if not hasattr(geometry, "triangles"):
590 continue
591 # append the (n, 3, 3) triangles to a sequence
592 triangles.append(
593 transformations.transform_points(
594 geometry.triangles.copy().reshape((-1, 3)), matrix=transform
595 )
596 )
597 # save the node names for each triangle
598 triangles_node.append(np.tile(node_name, len(geometry.triangles)))
599 # save the resulting nodes to the cache
600 self._cache["triangles_node"] = np.hstack(triangles_node)
601 return np.vstack(triangles).reshape((-1, 3, 3))
603 @caching.cache_decorator
604 def triangles_node(self):
605 """
606 Which node of self.graph does each triangle come from.
608 Returns
609 ---------
610 triangles_index : (len(self.triangles),)
611 Node name for each triangle
612 """
613 populate = self.triangles # NOQA
614 return self._cache["triangles_node"]
616 @caching.cache_decorator
617 def geometry_identifiers(self) -> dict[str, str]:
618 """
619 Look up geometries by identifier hash.
621 Returns
622 ---------
623 identifiers
624 {Identifier hash: key in self.geometry}
625 """
626 return {mesh.identifier_hash: name for name, mesh in self.geometry.items()}
628 @caching.cache_decorator
629 def identifier_hash(self) -> str:
630 """
631 Get a unique identifier for the scene.
632 """
633 dump = "".join(g.identifier_hash for g in self.geometry.values()) + str(
634 hash(self.graph)
635 )
636 return sha256(dump.encode()).hexdigest()
638 @caching.cache_decorator
639 def duplicate_nodes(self) -> list[list[str]]:
640 """
641 Return a sequence of node keys of identical meshes.
643 Will include meshes with different geometry but identical
644 spatial hashes as well as meshes repeated by self.nodes.
646 Returns
647 -----------
648 duplicates
649 Keys of self.graph that represent identical geometry
650 """
651 # if there is no geometry we can have no duplicate nodes
652 if len(self.geometry) == 0:
653 return []
655 # geometry name : hash of mesh
656 hashes = {
657 k: int(m.identifier_hash, 16)
658 for k, m in self.geometry.items()
659 if hasattr(m, "identifier_hash")
660 }
662 # bring into local scope for loop
663 graph = self.graph
664 # get a hash for each node name
665 # scene.graph node name : hashed geometry
666 node_hash = {node: hashes.get(graph[node][1]) for node in graph.nodes_geometry}
668 # collect node names for each hash key
669 duplicates = collections.defaultdict(list)
670 # use a slightly off-label list comprehension
671 # for debatable function call overhead avoidance
672 [
673 duplicates[hashed].append(node)
674 for node, hashed in node_hash.items()
675 if hashed is not None
676 ]
678 # we only care about the values keys are garbage
679 return list(duplicates.values())
681 def reconstruct_instances(self, cost_threshold: Floating = 1e-5) -> "Scene":
682 """
683 If a scene has been "baked" with meshes it means that
684 the duplicate nodes have *corresponding vertices* but are
685 rigidly transformed to different places.
687 This means the problem of finding ab instance transform can
688 use the `procrustes` analysis which is *very* fast relative
689 to more complicated registration problems that require ICP
690 and nearest-point-on-surface calculations.
692 TODO : construct a parent non-geometry node for containing every group.
694 Parameters
695 ----------
696 cost_threshold
697 The maximum value for `procrustes` cost which is "squared mean
698 vertex distance between pair". If the fit is above this value
699 the instance will be left even if it is a duplicate.
701 Returns
702 ---------
703 dedupe
704 A copy of the scene de-duplicated as much as possible.
705 """
706 return reconstruct_instances(self, cost_threshold=cost_threshold)
708 def set_camera(
709 self, angles=None, distance=None, center=None, resolution=None, fov=None
710 ) -> cameras.Camera:
711 """
712 Create a camera object for self.camera, and add
713 a transform to self.graph for it.
715 If arguments are not passed sane defaults will be figured
716 out which show the mesh roughly centered.
718 Parameters
719 -----------
720 angles : (3,) float
721 Initial euler angles in radians
722 distance : float
723 Distance from centroid
724 center : (3,) float
725 Point camera should be center on
726 """
728 if fov is None:
729 fov = np.array([60, 45])
731 # if no geometry nothing to set camera to
732 if len(self.geometry) == 0:
733 self._camera = cameras.Camera(fov=fov)
734 self.graph[self._camera.name] = np.eye(4)
735 return self._camera
736 # set with no rotation by default
737 if angles is None:
738 angles = np.zeros(3)
740 rotation = transformations.euler_matrix(*angles)
741 transform = cameras.look_at(
742 self.bounds, fov=fov, rotation=rotation, distance=distance, center=center
743 )
745 if hasattr(self, "_camera") and self._camera is not None:
746 self._camera.fov = fov
747 if resolution is not None:
748 self._camera.resolution = resolution
749 else:
750 # create a new camera object
751 self._camera = cameras.Camera(fov=fov, resolution=resolution)
753 self.graph[self._camera.name] = transform
755 return self._camera
757 @property
758 def camera_transform(self):
759 """
760 Get camera transform in the base frame.
762 Returns
763 -------
764 camera_transform : (4, 4) float
765 Camera transform in the base frame
766 """
767 return self.graph[self.camera.name][0]
769 @camera_transform.setter
770 def camera_transform(self, matrix: ArrayLike):
771 """
772 Set the camera transform in the base frame
774 Parameters
775 ----------
776 camera_transform : (4, 4) float
777 Camera transform in the base frame
778 """
779 self.graph[self.camera.name] = matrix
781 def camera_rays(self) -> tuple[NDArray[float64], NDArray[float64], NDArray[int64]]:
782 """
783 Calculate the trimesh.scene.Camera origin and ray
784 direction vectors. Returns one ray per pixel as set
785 in camera.resolution
787 Returns
788 --------------
789 origin: (n, 3) float
790 Ray origins in space
791 vectors: (n, 3) float
792 Ray direction unit vectors in world coordinates
793 pixels : (n, 2) int
794 Which pixel does each ray correspond to in an image
795 """
796 # get the unit vectors of the camera
797 vectors, pixels = self.camera.to_rays()
798 # find our scene's transform for the camera
799 transform = self.camera_transform
800 # apply the rotation to the unit ray direction vectors
801 vectors = transformations.transform_points(vectors, transform, translate=False)
802 # camera origin is single point so extract from
803 origins = np.ones_like(vectors) * transformations.translation_from_matrix(
804 transform
805 )
806 return origins, vectors, pixels
808 @property
809 def camera(self) -> cameras.Camera:
810 """
811 Get the single camera for the scene. If not manually
812 set one will abe automatically generated.
814 Returns
815 ----------
816 camera : trimesh.scene.Camera
817 Camera object defined for the scene
818 """
819 # no camera set for the scene yet
820 if not self.has_camera:
821 # will create a camera with everything in view
822 return self.set_camera()
823 assert self._camera is not None
825 return self._camera
827 @camera.setter
828 def camera(self, camera: cameras.Camera | None):
829 """
830 Set a camera object for the Scene.
832 Parameters
833 -----------
834 camera : trimesh.scene.Camera
835 Camera object for the scene
836 """
837 if camera is None:
838 return
839 self._camera = camera
841 @property
842 def has_camera(self) -> bool:
843 return hasattr(self, "_camera") and self._camera is not None
845 @property
846 def lights(self) -> list[lighting.Light]:
847 """
848 Get a list of the lights in the scene. If nothing is
849 set it will generate some automatically.
851 Returns
852 -------------
853 lights : [trimesh.scene.lighting.Light]
854 Lights in the scene.
855 """
856 if not hasattr(self, "_lights") or self._lights is None:
857 # do some automatic lighting
858 lights, transforms = lighting.autolight(self)
859 # assign the transforms to the scene graph
860 for L, T in zip(lights, transforms):
861 self.graph[L.name] = T
862 # set the lights
863 self._lights = lights
864 return self._lights
866 @lights.setter
867 def lights(self, lights: Sequence[lighting.Light]):
868 """
869 Assign a list of light objects to the scene
871 Parameters
872 --------------
873 lights : [trimesh.scene.lighting.Light]
874 Lights in the scene.
875 """
876 self._lights = lights
878 def rezero(self) -> None:
879 """
880 Move the current scene so that the AABB of the whole
881 scene is centered at the origin.
883 Does this by changing the base frame to a new, offset
884 base frame.
885 """
886 if self.is_empty or np.allclose(self.centroid, 0.0):
887 # early exit since what we want already exists
888 return
890 # the transformation to move the overall scene to AABB centroid
891 matrix = np.eye(4)
892 matrix[:3, 3] = -self.centroid
894 # we are going to change the base frame
895 new_base = str(self.graph.base_frame) + "_I"
896 self.graph.update(
897 frame_from=new_base, frame_to=self.graph.base_frame, matrix=matrix
898 )
899 self.graph.base_frame = new_base
901 def dump(self, concatenate: bool = False) -> list[Geometry]:
902 """
903 Get a list of every geometry moved to its instance position,
904 i.e. freezing or "baking" transforms.
906 Parameters
907 ------------
908 concatenate
909 KWARG IS DEPRECATED FOR REMOVAL APRIL 2025
910 Concatenate results into single geometry.
911 This keyword argument will make the type hint incorrect and
912 you should replace `Scene.dump(concatenate=True)` with:
913 - `Scene.to_geometry()` for a Trimesh, Path2D or Path3D
914 - `Scene.to_mesh()` for only `Trimesh` components.
916 Returns
917 ----------
918 dumped
919 Copies of `Scene.geometry` transformed to their instance position.
920 """
922 result = []
923 for node_name in self.graph.nodes_geometry:
924 transform, geometry_name = self.graph[node_name]
925 # get a copy of the geometry
926 current = self.geometry[geometry_name].copy()
928 # if the geometry is 2D see if we have to upgrade to 3D
929 if hasattr(current, "to_3D"):
930 # check to see if the scene is transforming the path out of plane
931 check = util.isclose(transform, util._IDENTITY, atol=1e-8)
932 check[:2, :3] = True
933 if not check.all():
934 # transform moves in 3D so we put this on the Z=0 plane
935 current = current.to_3D()
936 else:
937 # transform moves in 2D so clip off the last row and column
938 transform = transform[:3, :3]
940 # move the geometry vertices into the requested frame
941 current.apply_transform(transform)
942 current.metadata["name"] = geometry_name
943 current.metadata["node"] = node_name
945 # save to our list of meshes
946 result.append(current)
948 if concatenate:
949 warnings.warn(
950 "`Scene.dump(concatenate=True)` DEPRECATED FOR REMOVAL APRIL 2025: replace with `Scene.to_geometry()`",
951 category=DeprecationWarning,
952 stacklevel=2,
953 )
954 # if scene has mixed geometry this may drop some of it
955 return util.concatenate(result) # type: ignore
957 return result
959 def to_mesh(self) -> "trimesh.Trimesh": # noqa: F821
960 """
961 Concatenate every mesh instances in the scene into a single mesh,
962 applying transforms and "baking" the result. Will drop any geometry
963 in the scene that is not a `Trimesh` object.
965 Returns
966 ----------
967 mesh
968 All meshes in the scene concatenated into one.
969 """
970 from ..base import Trimesh
972 # concatenate only meshes
973 return util.concatenate([d for d in self.dump() if isinstance(d, Trimesh)])
975 def to_geometry(self) -> Geometry:
976 """
977 Concatenate geometry in the scene into a single like-typed geometry,
978 applying the transforms and "baking" the result. May drop geometry
979 if the scene has mixed geometry.
981 Returns
982 ---------
983 concat
984 Either a Trimesh, Path2D, or Path3D depending on what is in the scene.
985 """
986 # concatenate everything and return the most-occurring type.
987 return util.concatenate(self.dump())
989 def subscene(self, node: Hashable) -> "Scene":
990 """
991 Get part of a scene that succeeds a specified node.
993 Parameters
994 ------------
995 node : Hashable
996 Key in `scene.graph`
998 Returns
999 -----------
1000 subscene
1001 Partial scene generated from current.
1002 """
1003 # get every node that is a successor to specified node
1004 # this includes `node`
1005 graph = self.graph
1006 nodes = graph.transforms.successors(node)
1007 # get every edge that has an included node
1008 edges = [e for e in graph.to_edgelist() if e[0] in nodes]
1010 # create a scene graph when
1011 graph = SceneGraph(base_frame=node)
1012 graph.from_edgelist(edges)
1014 geometry_names = {e[2]["geometry"] for e in edges if "geometry" in e[2]}
1015 geometry = {k: self.geometry[k] for k in geometry_names}
1016 result = Scene(geometry=geometry, graph=graph)
1017 return result
1019 @caching.cache_decorator
1020 def convex_hull(self):
1021 """
1022 The convex hull of the whole scene.
1024 Returns
1025 ---------
1026 hull : trimesh.Trimesh
1027 Trimesh object which is a convex hull of all meshes in scene
1028 """
1029 points = util.vstack_empty([m.vertices for m in self.dump()]) # type: ignore
1030 return convex.convex_hull(points)
1032 def export(self, file_obj=None, file_type=None, **kwargs):
1033 """
1034 Export a snapshot of the current scene.
1036 Parameters
1037 ----------
1038 file_obj : str, file-like, or None
1039 File object to export to
1040 file_type : str or None
1041 What encoding to use for meshes
1042 IE: dict, dict64, stl
1044 Returns
1045 ----------
1046 export : bytes
1047 Only returned if file_obj is None
1048 """
1049 return export.export_scene(
1050 scene=self, file_obj=file_obj, file_type=file_type, **kwargs
1051 )
1053 def save_image(self, resolution=None, **kwargs) -> bytes:
1054 """
1055 Get a PNG image of a scene.
1057 Parameters
1058 -----------
1059 resolution : (2,) int
1060 Resolution to render image
1061 **kwargs
1062 Passed to SceneViewer constructor
1064 Returns
1065 -----------
1066 png : bytes
1067 Render of scene as a PNG
1068 """
1069 from ..viewer.windowed import render_scene
1071 return render_scene(
1072 scene=self, resolution=resolution, fullscreen=False, resizable=False, **kwargs
1073 )
1075 @property
1076 def units(self) -> str | None:
1077 """
1078 Get the units for every model in the scene. If the scene has
1079 mixed units or no units this will return None.
1081 Returns
1082 -----------
1083 units
1084 Units for every model in the scene or None
1085 if there are no units or mixed units
1086 """
1087 # get a set of the units of every geometry
1088 existing = {i.units for i in self.geometry.values()}
1089 if len(existing) == 1:
1090 return existing.pop()
1091 elif len(existing) > 1:
1092 log.warning(f"Mixed units `{existing}` returning None")
1093 return None
1095 @units.setter
1096 def units(self, value: str):
1097 """
1098 Set the units for every model in the scene without
1099 converting any units just setting the tag.
1101 Parameters
1102 ------------
1103 value : str
1104 Value to set every geometry unit value to
1105 """
1106 value = value.strip().lower()
1107 for m in self.geometry.values():
1108 m.units = value
1110 def convert_units(self, desired: str, guess: bool = False) -> "Scene":
1111 """
1112 If geometry has units defined convert them to new units.
1114 Returns a new scene with geometries and transforms scaled.
1116 Parameters
1117 ----------
1118 desired : str
1119 Desired final unit system: 'inches', 'mm', etc.
1120 guess : bool
1121 Is the converter allowed to guess scale when models
1122 don't have it specified in their metadata.
1124 Returns
1125 ----------
1126 scaled : trimesh.Scene
1127 Copy of scene with scaling applied and units set
1128 for every model
1129 """
1130 # if there is no geometry do nothing
1131 if len(self.geometry) == 0:
1132 return self.copy()
1134 current = self.units
1135 if current is None:
1136 # will raise ValueError if not in metadata
1137 # and not allowed to guess
1138 current = units.units_from_metadata(self, guess=guess)
1140 # find the float conversion
1141 scale = units.unit_conversion(current=current, desired=desired)
1143 # apply scaling factor or exit early if scale ~= 1.0
1144 result = self.scaled(scale=scale)
1146 # apply the units to every geometry of the scaled result
1147 result.units = desired
1149 return result
1151 def explode(self, vector=None, origin=None) -> None:
1152 """
1153 Explode the current scene in-place around a point and vector.
1155 Parameters
1156 -----------
1157 vector : (3,) float or float
1158 Explode radially around a direction vector or spherically
1159 origin : (3,) float
1160 Point to explode around
1161 """
1162 if origin is None:
1163 origin = self.centroid
1164 if vector is None:
1165 vector = self.scale / 25.0
1167 vector = np.asanyarray(vector, dtype=np.float64)
1168 origin = np.asanyarray(origin, dtype=np.float64)
1170 for node_name in self.graph.nodes_geometry:
1171 transform, geometry_name = self.graph[node_name]
1172 centroid = self.geometry[geometry_name].centroid
1173 # transform centroid into nodes location
1174 centroid = np.dot(transform, np.append(centroid, 1))[:3]
1176 if vector.shape == ():
1177 # case where our vector is a single number
1178 offset = (centroid - origin) * vector
1179 elif np.shape(vector) == (3,):
1180 projected = np.dot(vector, (centroid - origin))
1181 offset = vector * projected
1182 else:
1183 raise ValueError("explode vector wrong shape!")
1185 # original transform is read-only
1186 T_new = transform.copy()
1187 T_new[:3, 3] += offset
1188 self.graph[node_name] = T_new
1190 def scaled(self, scale: Floating | ArrayLike) -> "Scene":
1191 """
1192 Return a copy of the current scene, with meshes and scene
1193 transforms scaled to the requested factor.
1195 Parameters
1196 -----------
1197 scale : float or (3,) float
1198 Factor to scale meshes and transforms
1200 Returns
1201 -----------
1202 scaled : trimesh.Scene
1203 A copy of the current scene but scaled
1204 """
1205 result = self.copy()
1207 # a scale of 1.0 is a no-op
1208 if np.allclose(scale, 1.0):
1209 return result
1211 # convert 2D geometries to 3D for 3D scaling factors
1212 scale_is_3D = isinstance(scale, (list, tuple, np.ndarray)) and len(scale) == 3
1214 if scale_is_3D and np.all(np.asarray(scale) == scale[0]):
1215 # scale is uniform
1216 scale = float(scale[0])
1217 scale_is_3D = False
1218 elif not scale_is_3D:
1219 scale = float(scale)
1221 # result is a copy
1223 if scale_is_3D:
1224 # Copy all geometries that appear multiple times in the scene,
1225 # such that no two nodes share the same geometry.
1226 # This is required since the non-uniform scaling will most likely
1227 # affect the same geometry in different poses differently.
1228 # Note, that this is not needed in the case of uniform scaling.
1229 for geom_name in result.graph.geometry_nodes:
1230 nodes_with_geom = result.graph.geometry_nodes[geom_name]
1231 if len(nodes_with_geom) > 1:
1232 geom = result.geometry[geom_name]
1233 for n in nodes_with_geom:
1234 p = result.graph.transforms.parents[n]
1235 result.add_geometry(
1236 geometry=geom.copy(),
1237 geom_name=geom_name,
1238 node_name=n,
1239 parent_node_name=p,
1240 transform=result.graph.transforms.edge_data[(p, n)].get(
1241 "matrix", None
1242 ),
1243 metadata=result.graph.transforms.edge_data[(p, n)].get(
1244 "metadata", None
1245 ),
1246 )
1247 result.delete_geometry(geom_name)
1249 # Convert all 2D paths to 3D paths
1250 for geom_name in result.geometry:
1251 if result.geometry[geom_name].vertices.shape[1] == 2:
1252 result.geometry[geom_name] = result.geometry[geom_name].to_3D()
1254 for key in result.graph.nodes_geometry:
1255 T, geom_name = result.graph.get(key)
1256 # transform from graph should be read-only
1257 T = T.copy()
1258 T[:3, 3] = 0.0
1260 # Get geometry transform w.r.t. base frame
1261 result.geometry[geom_name].apply_transform(T).apply_scale(
1262 scale
1263 ).apply_transform(np.linalg.inv(T))
1265 # Scale all transformations in the scene graph
1266 edge_data = result.graph.transforms.edge_data
1267 for uv in edge_data:
1268 if "matrix" in edge_data[uv]:
1269 props = edge_data[uv]
1270 T = edge_data[uv]["matrix"].copy()
1271 T[:3, 3] *= scale
1272 props["matrix"] = T
1273 result.graph.update(frame_from=uv[0], frame_to=uv[1], **props)
1274 # Clear cache
1275 result.graph.transforms._cache = {}
1276 result.graph.transforms._modified = str(uuid.uuid4())
1277 result.graph._cache.clear()
1278 else:
1279 # matrix for 2D scaling
1280 scale_2D = np.eye(3) * scale
1281 # matrix for 3D scaling
1282 scale_3D = np.eye(4) * scale
1284 # preallocate transforms and geometries
1285 nodes = np.array(self.graph.nodes_geometry)
1286 transforms = np.zeros((len(nodes), 4, 4))
1287 geometries = [None] * len(nodes)
1289 # collect list of transforms
1290 for i, node in enumerate(nodes):
1291 transforms[i], geometries[i] = self.graph[node]
1293 # remove all existing transforms
1294 result.graph.clear()
1296 for group in grouping.group(geometries):
1297 # hashable reference to self.geometry
1298 geometry = geometries[group[0]]
1299 # original transform from world to geometry
1300 original = transforms[group[0]]
1301 # transform for geometry
1302 new_geom = np.dot(scale_3D, original)
1304 if result.geometry[geometry].vertices.shape[1] == 2:
1305 # if our scene is 2D only scale in 2D
1306 result.geometry[geometry].apply_transform(scale_2D)
1307 else:
1308 # otherwise apply the full transform
1309 result.geometry[geometry].apply_transform(new_geom)
1311 for node, T in zip(nodes[group], transforms[group]):
1312 # generate the new transforms
1313 transform = util.multi_dot([scale_3D, T, np.linalg.inv(new_geom)])
1314 # apply scale to translation
1315 transform[:3, 3] *= scale
1316 # update scene with new transforms
1317 result.graph.update(
1318 frame_to=node, matrix=transform, geometry=geometry
1319 )
1321 # remove camera from copied
1322 result._camera = None
1324 return result
1326 def copy(self) -> "Scene":
1327 """
1328 Return a deep copy of the current scene
1330 Returns
1331 ----------
1332 copied : trimesh.Scene
1333 Copy of the current scene
1334 """
1335 # use the geometries copy method to
1336 # allow them to handle references to unpickle-able objects
1337 geometry = {n: g.copy() for n, g in self.geometry.items()}
1339 if not hasattr(self, "_camera") or self._camera is None:
1340 # if no camera set don't include it
1341 camera = None
1342 else:
1343 # otherwise get a copy of the camera
1344 camera = self.camera.copy()
1345 # create a new scene with copied geometry and graph
1346 copied = Scene(
1347 geometry=geometry,
1348 graph=self.graph.copy(),
1349 metadata=self.metadata.copy(),
1350 camera=camera,
1351 )
1352 return copied
1354 def show(
1355 self,
1356 viewer: ViewerType = None,
1357 **kwargs,
1358 ):
1359 """
1360 Display the current scene.
1362 Parameters
1363 -----------
1364 viewer
1365 What kind of viewer to use, such as
1366 `gl` to open a pyglet window
1367 `jupyter` for a jupyter notebook
1368 `marimo'` for a marimo notebook
1369 None for a "best guess"
1370 kwargs
1371 Passed to viewer, such as `smooth=False` which will turn
1372 off automatic smooth shading
1373 """
1375 if viewer is None:
1376 # check to see if we are in a notebook or not
1377 from ..viewer import in_notebook
1379 # returns a literal for what kind of notebook, or False
1380 viewer = in_notebook()
1381 if not viewer:
1382 viewer = "gl"
1384 if viewer == "gl":
1385 # this imports pyglet, and will raise an ImportError
1386 # if pyglet is not available
1387 from ..viewer import SceneViewer
1389 return SceneViewer(self, **kwargs)
1390 elif viewer == "jupyter":
1391 from ..viewer import scene_to_notebook
1393 return scene_to_notebook(self, **kwargs)
1394 elif viewer == "marimo":
1395 from ..viewer import scene_to_mo_notebook
1397 return scene_to_mo_notebook(self, **kwargs)
1398 elif callable(viewer):
1399 # if a callable method like a custom class
1400 # constructor was passed run using that
1401 return viewer(self, **kwargs)
1402 else:
1403 raise ValueError(
1404 "Invalid value for viewer: not 'gl', 'jupyter', 'marimo', callable, or None"
1405 )
1407 def __add__(self, other):
1408 """
1409 Concatenate the current scene with another scene or mesh.
1411 Parameters
1412 ------------
1413 other : trimesh.Scene, trimesh.Trimesh, trimesh.Path
1414 Other object to append into the result scene
1416 Returns
1417 ------------
1418 appended : trimesh.Scene
1419 Scene with geometry from both scenes
1420 """
1421 result = append_scenes([self, other], common=[self.graph.base_frame])
1422 return result
1425def split_scene(geometry, **kwargs):
1426 """
1427 Given a geometry, list of geometries, or a Scene
1428 return them as a single Scene object.
1430 Parameters
1431 ----------
1432 geometry : splittable
1434 Returns
1435 ---------
1436 scene: trimesh.Scene
1437 """
1438 # already a scene, so return it
1439 if isinstance(geometry, Scene):
1440 return geometry
1442 # save metadata
1443 metadata = {}
1445 # a list of things
1446 if util.is_sequence(geometry):
1447 [metadata.update(getattr(g, "metadata", {})) for g in geometry]
1449 scene = Scene(geometry, metadata=metadata)
1450 scene._source = next((g.source for g in geometry if g.source is not None), None)
1451 else:
1452 # a single geometry so we are going to split
1453 scene = Scene(
1454 geometry.split(**kwargs),
1455 metadata=deepcopy(geometry.metadata),
1456 )
1457 scene._source = deepcopy(geometry.source)
1459 return scene
1462def append_scenes(iterable, common=None, base_frame="world"):
1463 """
1464 Concatenate multiple scene objects into one scene.
1466 Parameters
1467 -------------
1468 iterable : (n,) Trimesh or Scene
1469 Geometries that should be appended
1470 common : (n,) str
1471 Nodes that shouldn't be remapped
1472 base_frame : str
1473 Base frame of the resulting scene
1475 Returns
1476 ------------
1477 result : trimesh.Scene
1478 Scene containing all geometry
1479 """
1480 if isinstance(iterable, Scene):
1481 return iterable
1483 if common is None:
1484 common = [base_frame]
1486 result = Scene(base_frame=base_frame)
1487 # save geometry in dict
1488 geometry = {}
1489 # save transforms as edge tuples
1490 edges = []
1492 # nodes which shouldn't be remapped
1493 common = set(common)
1494 # nodes which are consumed and need to be remapped
1495 consumed = set()
1497 def node_remap(node: Hashable) -> Hashable:
1498 """
1499 Remap node to new name if necessary
1501 Parameters
1502 -------------
1503 node : Hashable
1504 Node name in original scene
1506 Returns
1507 -------------
1508 name : Hashable
1509 Node name in concatenated scene
1510 """
1512 # if we've already remapped a node use it
1513 if node in map_node:
1514 return map_node[node]
1516 # if a node is consumed and isn't one of the nodes
1517 # we're going to hold common between scenes remap it
1518 if node not in common and node in consumed:
1519 # generate a name not in consumed
1520 name = node + util.unique_id()
1521 map_node[node] = name
1522 node = name
1524 # keep track of which nodes have been used
1525 # in the current scene
1526 current.add(node)
1527 return node
1529 # loop through every geometry
1530 for s in iterable:
1531 # allow Trimesh/Path2D geometry to be passed
1532 if hasattr(s, "scene"):
1533 s = s.scene()
1534 # if we don't have a scene raise an exception
1535 if not isinstance(s, Scene):
1536 raise ValueError(f"{type(s).__name__} is not a scene!")
1538 # remap geometries if they have been consumed
1539 map_geom = {}
1540 for k, v in s.geometry.items():
1541 # if a geometry already exists add a UUID to the name
1542 name = unique_name(start=k, contains=geometry.keys())
1543 # store name mapping
1544 map_geom[k] = name
1545 # store geometry with new name
1546 geometry[name] = v
1548 # remap nodes and edges so duplicates won't
1549 # stomp all over each other
1550 map_node = {}
1551 # the nodes used in this scene
1552 current = set()
1553 for a, b, attr in s.graph.to_edgelist():
1554 # remap node names from local names
1555 a, b = node_remap(a), node_remap(b)
1556 # remap geometry keys
1557 # if key is not in map_geom it means one of the scenes
1558 # referred to geometry that doesn't exist
1559 # rather than crash here we ignore it as the user
1560 # possibly intended to add in geometries back later
1561 if "geometry" in attr and attr["geometry"] in map_geom:
1562 attr["geometry"] = map_geom[attr["geometry"]]
1563 # save the new edge
1564 edges.append((a, b, attr))
1565 # Geometry references are remapped by the edges above.
1566 for node, attr in s.graph.transforms.node_data.items():
1567 data = {k: v for k, v in attr.items() if k != "geometry"}
1568 if data:
1569 result.graph.transforms.node_data[node_remap(node)].update(deepcopy(data))
1570 # mark nodes from current scene as consumed
1571 consumed.update(current)
1573 # add geometry and transforms to the scene
1574 result.graph.from_edgelist(edges)
1575 result.geometry.update(geometry)
1577 return result
1580def reconstruct_instances(scene: Scene, cost_threshold: Floating = 1e-6) -> Scene:
1581 """
1582 If a scene has been "baked" with meshes it means that
1583 the duplicate nodes have *corresponding vertices* but are
1584 rigidly transformed to different places.
1586 This means the problem of finding ab instance transform can
1587 use the `procrustes` analysis which is *very* fast relative
1588 to more complicated registration problems that require ICP
1589 and nearest-point-on-surface calculations.
1591 TODO : construct a parent non-geometry node for containing every group.
1593 Parameters
1594 ----------
1595 scene
1596 The scene to handle.
1597 cost_threshold
1598 The maximum value for `procrustes` cost which is "squared mean
1599 vertex distance between pair". If the fit is above this value
1600 the instance will be left even if it is a duplicate.
1602 Returns
1603 ---------
1604 dedupe
1605 A copy of the scene de-duplicated as much as possible.
1606 """
1607 # start with the original scene graph and modify in-loop
1608 graph = scene.graph.copy()
1610 for group in scene.duplicate_nodes:
1611 # not sure if this ever includes
1612 if len(group) < 2:
1613 continue
1615 # we are going to use one of the geometries and try to register the others to it
1616 node_base = group[0]
1617 # get the geometry name for this base node
1618 _, geom_base = scene.graph[node_base]
1619 # get the vertices of the base model
1620 base = scene.geometry[geom_base].vertices.view(np.ndarray)
1622 for node in group[1:]:
1623 # the original pose of this node in the scene
1624 node_mat, node_geom = scene.graph[node]
1625 # procrustes matches corresponding point arrays very quickly
1626 # but we have to make sure that they actual correspond in shape
1627 node_vertices = scene.geometry[node_geom].vertices.view(np.ndarray)
1629 # procrustes only works on corresponding point clouds!
1630 if node_vertices.shape != base.shape:
1631 continue
1633 # solve for a pose moving this instance into position
1634 matrix, _p, cost = procrustes(
1635 base, node_vertices, translation=True, scale=False, reflection=False
1636 )
1637 if cost < cost_threshold:
1638 # add the transform we found
1639 graph.update(node, matrix=np.dot(node_mat, matrix), geometry=geom_base)
1641 # get from the new graph which geometry ends up with a reference
1642 referenced = set(graph.geometry_nodes.keys())
1644 # return a scene with the de-duplicated graph and a copy of any geometry
1645 return Scene(
1646 geometry={k: v.copy() for k, v in scene.geometry.items() if k in referenced},
1647 graph=graph,
1648 )