Coverage for trimesh/primitives.py: 94%
368 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-12 17:18 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-12 17:18 +0000
1"""
2primitives.py
3----------------
5Subclasses of Trimesh objects that are parameterized as primitives.
7Useful because you can move boxes and spheres around
8and then use trimesh operations on them at any point.
9"""
11import abc
13import numpy as np
15from . import creation, inertia, sample, triangles, util
16from . import transformations as tf
17from .base import Trimesh
18from .caching import cache_decorator
19from .constants import log, tol
20from .typed import ArrayLike, Integer, Number, Seed
22# immutable identity matrix for checks
23_IDENTITY = np.eye(4)
24_IDENTITY.flags.writeable = False
27class Primitive(Trimesh):
28 """
29 Geometric Primitives which are a subclass of Trimesh.
30 Mesh is generated lazily when vertices or faces are requested.
31 """
33 # ignore superclass copy directives
34 __copy__ = None
35 __deepcopy__ = None
37 def __init__(self):
38 # run the Trimesh constructor with no arguments
39 super().__init__()
41 # remove any data
42 self._data.clear()
43 self._validate = False
45 # make sure any cached numpy arrays have
46 # set `array.flags.writable = False`
47 self._cache.force_immutable = True
49 def __repr__(self):
50 return f"<trimesh.primitives.{type(self).__name__}>"
52 @property
53 def faces(self):
54 stored = self._cache["faces"]
55 if util.is_shape(stored, (-1, 3)):
56 return stored
57 self._create_mesh()
58 return self._cache["faces"]
60 @faces.setter
61 def faces(self, values):
62 if values is not None:
63 raise ValueError("primitive faces are immutable: not setting!")
65 @property
66 def vertices(self):
67 stored = self._cache["vertices"]
68 if util.is_shape(stored, (-1, 3)):
69 return stored
71 self._create_mesh()
72 return self._cache["vertices"]
74 @vertices.setter
75 def vertices(self, values):
76 if values is not None:
77 raise ValueError("primitive vertices are immutable: not setting!")
79 @property
80 def face_normals(self):
81 # if the mesh hasn't been created yet do that
82 # before checking to see if the mesh creation
83 # already populated the face normals
84 if "vertices" not in self._cache:
85 self._create_mesh()
87 # we need to avoid the logic in the superclass that
88 # is specific to the data model prioritizing faces
89 stored = self._cache["face_normals"]
90 if util.is_shape(stored, (-1, 3)):
91 return stored
93 # if the creation did not populate normals we have to do it
94 # just calculate if not stored
95 unit, valid = triangles.normals(self.triangles)
96 normals = np.zeros((len(valid), 3))
97 normals[valid] = unit
98 # store and return
99 self._cache["face_normals"] = normals
100 return normals
102 @face_normals.setter
103 def face_normals(self, values):
104 if values is not None:
105 log.warning("Primitive face normals are immutable!")
107 @property
108 def transform(self):
109 """
110 The transform of the Primitive object.
112 Returns
113 -------------
114 transform : (4, 4) float
115 Homogeneous transformation matrix
116 """
117 return self.primitive.transform
119 @abc.abstractmethod
120 def to_dict(self):
121 """
122 Should be implemented by each primitive.
123 """
124 raise NotImplementedError()
126 def copy(self, include_visual=True, **kwargs):
127 """
128 Return a copy of the Primitive object.
130 Returns
131 -------------
132 copied : object
133 Copy of current primitive
134 """
135 # preserve attributes omitted by the serialization schema
136 for key in self.primitive._defaults:
137 kwargs.setdefault(key, self._data[key])
138 # get the constructor arguments
139 kwargs.update(self.to_dict())
140 # remove the type indicator, i.e. `Cylinder`
141 kwargs.pop("kind")
142 # create a new object with kwargs
143 primitive_copy = type(self)(**kwargs)
145 if include_visual:
146 # copy visual information
147 primitive_copy.visual = self.visual.copy()
149 # copy metadata
150 primitive_copy.metadata = self.metadata.copy()
152 # carry over values stored outside the constructor
153 # arguments, like an overridden density or center mass
154 primitive_copy._data.update(
155 {k: v for k, v in self._data.data.items() if k not in primitive_copy._data}
156 )
158 return primitive_copy
160 def to_mesh(self, **kwargs):
161 """
162 Return a copy of the Primitive object as a Trimesh.
164 Parameters
165 -----------
166 kwargs : dict
167 Passed to the Trimesh object constructor.
169 Returns
170 ------------
171 mesh : trimesh.Trimesh
172 Tessellated version of the primitive.
173 """
174 result = Trimesh(
175 vertices=self.vertices.copy(),
176 faces=self.faces.copy(),
177 face_normals=self.face_normals.copy(),
178 process=kwargs.pop("process", False),
179 **kwargs,
180 )
181 return result
183 def apply_transform(self, matrix):
184 """
185 Apply a transform to the current primitive by
186 applying a new transform on top of existing
187 `self.primitive.transform`. If the matrix
188 contains scaling it will change parameters
189 like `radius` or `height` automatically.
191 Parameters
192 ------------
193 matrix: (4, 4) float
194 Homogeneous transformation
195 """
196 matrix = np.asanyarray(matrix, order="C", dtype=np.float64)
197 if matrix.shape != (4, 4):
198 raise ValueError("matrix must be `(4, 4)`!")
199 if util.allclose(matrix, _IDENTITY, 1e-8):
200 # identity matrix is a no-op
201 return self
203 prim = self.primitive
204 # copy the current transform
205 current = prim.transform.copy()
206 # see if matrix has scaling from the matrix
207 # use the magnitude so a mirrored scale like `apply_scale(-2)`
208 # keeps the reflection in the rigid transform instead of NaN
209 scale = np.abs(np.linalg.det(matrix[:3, :3])) ** (1.0 / 3.0)
211 # the objects we handle re-scaling for
212 # note that `Extrusion` is NOT supported
213 kinds = (Box, Cylinder, Capsule, Sphere)
214 if isinstance(self, kinds) and abs(scale - 1.0) > 1e-8:
215 # scale the primitive attributes
216 if hasattr(prim, "height"):
217 prim.height *= scale
218 if hasattr(prim, "radius"):
219 prim.radius *= scale
220 if hasattr(prim, "extents"):
221 prim.extents *= scale
222 # scale the translation of the current matrix
223 current[:3, 3] *= scale
224 # apply new matrix, rescale, translate, current
225 updated = util.multi_dot([matrix, tf.scale_matrix(1.0 / scale), current])
226 else:
227 # without scaling just multiply
228 updated = np.dot(matrix, current)
230 # make sure matrix is a rigid transform
231 if not tf.is_rigid(updated):
232 raise ValueError("Couldn't produce rigid transform!")
234 # apply the new matrix
235 self.primitive.transform = updated
237 return self
239 def _create_mesh(self):
240 raise ValueError("Primitive doesn't define mesh creation!")
243class PrimitiveAttributes:
244 """
245 Hold the mutable data which defines a primitive.
246 """
248 def __init__(self, parent, defaults, kwargs, mutable=True):
249 """
250 Hold the attributes for a Primitive.
252 Parameters
253 ------------
254 parent : Primitive
255 Parent object reference.
256 defaults : dict
257 The default values for this primitive type.
258 kwargs : dict
259 User-passed values, i.e. {'radius': 10.0}
260 """
261 # store actual data in parent object
262 self._data = parent._data
263 # default values define the keys
264 self._defaults = defaults
265 # store a reference to the parent ubject
266 self._parent = parent
267 # start with a copy of all default objects
268 self._data.update(defaults)
269 # store whether this data is mutable after creation
270 self._mutable = mutable
271 # assign the keys passed by the user only if
272 # they are a property of this primitive
273 for key, default in defaults.items():
274 value = kwargs.get(key, None)
275 if value is not None:
276 # convert passed data into type of defaults
277 self._data[key] = util.convert_like(value, default)
278 # make sure stored values are immutable after setting
279 if not self._mutable:
280 self._data.mutable = False
282 @property
283 def __doc__(self):
284 # this is generated dynamically as the format
285 # operation can be surprisingly slow and most
286 # people never call it
287 import pprint
289 doc = (
290 "Store the attributes of a {name} object.\n\n"
291 + "When these values are changed, the mesh geometry will \n"
292 + "automatically be updated to reflect the new values.\n\n"
293 + "Available properties and their default values are:\n {defaults}"
294 + "\n\nExample\n---------------\n"
295 + "p = trimesh.primitives.{name}()\n"
296 + "p.primitive.radius = 10\n"
297 + "\n"
298 ).format(
299 name=self._parent.__class__.__name__,
300 defaults=pprint.pformat(self._defaults, width=-1)[1:-1],
301 )
302 return doc
304 def __getattr__(self, key):
305 if key.startswith("_"):
306 return super().__getattr__(key)
307 elif key == "center":
308 # this whole __getattr__ is a little hacky
309 return self._data["transform"][:3, 3]
310 elif key in self._defaults:
311 return util.convert_like(self._data[key], self._defaults[key])
312 raise AttributeError(f"primitive object has no attribute '{key}' ")
314 def __setattr__(self, key, value):
315 if key.startswith("_"):
316 return super().__setattr__(key, value)
317 elif key == "center":
318 value = np.array(value, dtype=np.float64)
319 transform = np.eye(4)
320 transform[:3, 3] = value
321 self._data["transform"] = transform
322 return
323 elif key in self._defaults:
324 if self._mutable:
325 self._data[key] = util.convert_like(value, self._defaults[key])
326 else:
327 raise ValueError(
328 "Primitive is configured as immutable! Cannot set attribute!"
329 )
330 else:
331 keys = list(self._defaults.keys())
332 raise ValueError(f"Only default attributes {keys} can be set!")
334 def __dir__(self):
335 result = sorted(dir(type(self)) + list(self._defaults.keys()))
336 return result
339class Cylinder(Primitive):
340 def __init__(self, radius=1.0, height=1.0, transform=None, sections=32, mutable=True):
341 """
342 Create a Cylinder Primitive, a subclass of Trimesh.
344 Parameters
345 -------------
346 radius : float
347 Radius of cylinder
348 height : float
349 Height of cylinder
350 transform : (4, 4) float
351 Homogeneous transformation matrix
352 sections : int
353 Number of facets in circle.
354 mutable : bool
355 Are extents and transform mutable after creation.
356 """
357 super().__init__()
359 defaults = {"height": 10.0, "radius": 1.0, "transform": np.eye(4), "sections": 32}
360 self.primitive = PrimitiveAttributes(
361 self,
362 defaults=defaults,
363 kwargs={
364 "height": height,
365 "radius": radius,
366 "transform": transform,
367 "sections": sections,
368 },
369 mutable=mutable,
370 )
372 @cache_decorator
373 def volume(self):
374 """
375 The analytic volume of the cylinder primitive.
377 Returns
378 ---------
379 volume : float
380 Volume of the cylinder
381 """
382 return (np.pi * self.primitive.radius**2) * self.primitive.height
384 @cache_decorator
385 def area(self) -> float:
386 """
387 The analytical area of the cylinder primitive
388 """
389 # circumfrence * height + end-cap-area
390 radius, height = self.primitive.radius, self.primitive.height
391 return (np.pi * 2 * radius * height) + (2 * np.pi * radius**2)
393 @cache_decorator
394 def moment_inertia(self):
395 """
396 The analytic inertia tensor of the cylinder primitive.
398 Returns
399 ----------
400 tensor: (3, 3) float
401 3D inertia tensor
402 """
404 tensor = inertia.cylinder_inertia(
405 mass=self.volume,
406 radius=self.primitive.radius,
407 height=self.primitive.height,
408 transform=self.primitive.transform,
409 )
410 return tensor
412 @cache_decorator
413 def direction(self):
414 """
415 The direction of the cylinder's axis.
417 Returns
418 --------
419 axis: (3,) float, vector along the cylinder axis
420 """
421 axis = np.dot(self.primitive.transform, [0, 0, 1, 0])[:3]
422 return axis
424 @property
425 def segment(self):
426 """
427 A line segment which if inflated by cylinder radius
428 would represent the cylinder primitive.
430 Returns
431 -------------
432 segment : (2, 3) float
433 Points representing a single line segment
434 """
435 # half the height
436 half = self.primitive.height / 2.0
437 # apply the transform to the Z- aligned segment
438 points = np.dot(
439 self.primitive.transform, np.transpose([[0, 0, -half, 1], [0, 0, half, 1]])
440 ).T[:, :3]
441 return points
443 def to_dict(self):
444 """
445 Get a copy of the current Cylinder primitive as
446 a JSON-serializable dict that matches the schema
447 in `trimesh/resources/schema/cylinder.schema.json`
449 Returns
450 ----------
451 as_dict : dict
452 Serializable data for this primitive.
453 """
454 return {
455 "kind": "cylinder",
456 "transform": self.primitive.transform.tolist(),
457 "radius": float(self.primitive.radius),
458 "height": float(self.primitive.height),
459 }
461 def buffer(self, distance):
462 """
463 Return a cylinder primitive which covers the source
464 cylinder by distance: radius is inflated by distance
465 height by twice the distance.
467 Parameters
468 ------------
469 distance : float
470 Distance to inflate cylinder radius and height
472 Returns
473 -------------
474 buffered : Cylinder
475 Cylinder primitive inflated by distance
476 """
477 distance = float(distance)
478 buffered = Cylinder(
479 height=self.primitive.height + distance * 2,
480 radius=self.primitive.radius + distance,
481 transform=self.primitive.transform.copy(),
482 )
483 return buffered
485 def _create_mesh(self):
486 log.debug("creating mesh for Cylinder primitive")
487 mesh = creation.cylinder(
488 radius=self.primitive.radius,
489 height=self.primitive.height,
490 sections=self.primitive.sections,
491 transform=self.primitive.transform,
492 )
494 self._cache["vertices"] = mesh.vertices
495 self._cache["faces"] = mesh.faces
496 self._cache["face_normals"] = mesh.face_normals
499class Capsule(Primitive):
500 def __init__(
501 self, radius=1.0, height=10.0, transform=None, sections=32, mutable=True
502 ):
503 """
504 Create a Capsule Primitive, a subclass of Trimesh.
506 Parameters
507 ----------
508 radius : float
509 Radius of cylinder
510 height : float
511 Height of cylinder
512 transform : (4, 4) float
513 Transformation matrix
514 sections : int
515 Number of facets in circle
516 mutable : bool
517 Are extents and transform mutable after creation.
518 """
519 super().__init__()
521 defaults = {"height": 1.0, "radius": 1.0, "transform": np.eye(4), "sections": 32}
522 self.primitive = PrimitiveAttributes(
523 self,
524 defaults=defaults,
525 kwargs={
526 "height": height,
527 "radius": radius,
528 "transform": transform,
529 "sections": sections,
530 },
531 mutable=mutable,
532 )
534 @property
535 def transform(self):
536 return self.primitive.transform
538 @cache_decorator
539 def volume(self) -> float:
540 """
541 The analytic volume of the capsule primitive.
543 Returns
544 ---------
545 volume : float
546 Volume of the capsule
547 """
548 radius, height = self.primitive.radius, self.primitive.height
549 return (np.pi * radius**2) * ((4.0 / 3.0) * radius + height)
551 @cache_decorator
552 def area(self) -> float:
553 """
554 The analytic area of the capsule primitive.
556 Returns
557 ---------
558 area : float
559 Area of the capsule
560 """
561 radius, height = self.primitive.radius, self.primitive.height
562 return (2 * np.pi * radius * height) + (4 * np.pi * radius**2)
564 def to_dict(self):
565 """
566 Get a copy of the current Capsule primitive as
567 a JSON-serializable dict that matches the schema
568 in `trimesh/resources/schema/capsule.schema.json`
570 Returns
571 ----------
572 as_dict : dict
573 Serializable data for this primitive.
574 """
575 return {
576 "kind": "capsule",
577 "transform": self.primitive.transform.tolist(),
578 "height": float(self.primitive.height),
579 "radius": float(self.primitive.radius),
580 }
582 @cache_decorator
583 def direction(self):
584 """
585 The direction of the capsule's axis.
587 Returns
588 --------
589 axis : (3,) float
590 Vector along the cylinder axis
591 """
592 axis = np.dot(self.primitive.transform, [0, 0, 1, 0])[:3]
593 return axis
595 def _create_mesh(self):
596 log.debug("creating mesh for `Capsule` primitive")
598 mesh = creation.capsule(
599 radius=self.primitive.radius,
600 height=self.primitive.height,
601 count=[self.primitive.sections, self.primitive.sections * 2],
602 transform=self.primitive.transform,
603 )
605 self._cache["vertices"] = mesh.vertices
606 self._cache["faces"] = mesh.faces
607 self._cache["face_normals"] = mesh.face_normals
610class Sphere(Primitive):
611 def __init__(
612 self,
613 radius: Number = 1.0,
614 center: ArrayLike | None = None,
615 transform: ArrayLike | None = None,
616 subdivisions: Integer = 3,
617 mutable: bool = True,
618 ):
619 """
620 Create a Sphere Primitive, a subclass of Trimesh.
622 Parameters
623 ----------
624 radius
625 Radius of sphere
626 center : None or (3,) float
627 Center of sphere.
628 transform : None or (4, 4) float
629 Full homogeneous transform. Pass `center` OR `transform.
630 subdivisions
631 Number of subdivisions for icosphere.
632 mutable
633 Are extents and transform mutable after creation.
634 """
636 super().__init__()
638 constructor = {"radius": float(radius), "subdivisions": int(subdivisions)}
639 # center is a helper method for "transform"
640 # since a sphere is rotationally symmetric
641 if center is not None:
642 if transform is not None:
643 raise ValueError("only one of `center` and `transform` may be passed!")
644 translate = np.eye(4)
645 translate[:3, 3] = center
646 constructor["transform"] = translate
647 elif transform is not None:
648 constructor["transform"] = transform
650 # create the attributes object
651 self.primitive = PrimitiveAttributes(
652 self,
653 defaults={"radius": 1.0, "transform": np.eye(4), "subdivisions": 3},
654 kwargs=constructor,
655 mutable=mutable,
656 )
658 @property
659 def center(self):
660 return self.primitive.center
662 @center.setter
663 def center(self, value):
664 self.primitive.center = value
666 def to_dict(self):
667 """
668 Get a copy of the current Sphere primitive as
669 a JSON-serializable dict that matches the schema
670 in `trimesh/resources/schema/sphere.schema.json`
672 Returns
673 ----------
674 as_dict : dict
675 Serializable data for this primitive.
676 """
677 return {
678 "kind": "sphere",
679 "transform": self.primitive.transform.tolist(),
680 "radius": float(self.primitive.radius),
681 }
683 @property
684 def bounds(self):
685 # no docstring so will inherit Trimesh docstring
686 # return exact bounds from primitive center and radius (rather than faces)
687 # self.extents will also use this information
688 bounds = np.array(
689 [
690 self.primitive.center - self.primitive.radius,
691 self.primitive.center + self.primitive.radius,
692 ]
693 )
694 return bounds
696 @property
697 def bounding_box_oriented(self):
698 # for a sphere the oriented bounding box is the same as the axis aligned
699 # bounding box, and a sphere is the absolute slowest case for the OBB calculation
700 # as it is a convex surface with a ton of face normals that all need to
701 # be checked
702 return self.bounding_box
704 @cache_decorator
705 def area(self):
706 """
707 Surface area of the current sphere primitive.
709 Returns
710 --------
711 area: float, surface area of the sphere Primitive
712 """
714 area = 4.0 * np.pi * (self.primitive.radius**2)
715 return area
717 @cache_decorator
718 def volume(self):
719 """
720 Volume of the current sphere primitive.
722 Returns
723 --------
724 volume: float, volume of the sphere Primitive
725 """
727 volume = (4.0 * np.pi * (self.primitive.radius**3)) / 3.0
728 return volume
730 @cache_decorator
731 def moment_inertia(self):
732 """
733 The analytic inertia tensor of the sphere primitive.
735 Returns
736 ----------
737 tensor: (3, 3) float
738 3D inertia tensor.
739 """
740 return inertia.sphere_inertia(mass=self.volume, radius=self.primitive.radius)
742 def _create_mesh(self):
743 log.debug("creating mesh for Sphere primitive")
744 unit = creation.icosphere(
745 subdivisions=self.primitive.subdivisions, radius=self.primitive.radius
746 )
748 # apply the center offset here
749 self._cache["vertices"] = unit.vertices + self.primitive.center
750 self._cache["faces"] = unit.faces
751 self._cache["face_normals"] = unit.face_normals
754class Box(Primitive):
755 def __init__(self, extents=None, transform=None, bounds=None, mutable=True):
756 """
757 Create a Box Primitive as a subclass of Trimesh
759 Parameters
760 ----------
761 extents : ndarray (3,) float or None
762 Length of each side of the 3D box.
763 transform : ndarray (4, 4) float or None
764 Homogeneous transformation matrix for box center.
765 bounds : ndarray (2, 3) float or None
766 Axis aligned bounding box, if passed extents and
767 transform will be derived from this.
768 mutable : bool
769 Are extents and transform mutable after creation.
770 """
771 super().__init__()
772 defaults = {"transform": np.eye(4), "extents": np.ones(3)}
774 if bounds is not None:
775 # validate the multiple forms of input available here
776 if extents is not None or transform is not None:
777 raise ValueError(
778 "if `bounds` is passed `extents` and `transform` must not be!"
779 )
780 bounds = np.array(bounds, dtype=np.float64)
781 if bounds.shape != (2, 3):
782 raise ValueError("`bounds` must be (2, 3) float")
783 # create extents from AABB
784 extents = np.ptp(bounds, axis=0)
785 # translate to the center of the box
786 # use the min corner (not `bounds[0]`) so the result is
787 # independent of the order the two corners are passed in
788 transform = np.eye(4)
789 transform[:3, 3] = np.min(bounds, axis=0) + extents / 2.0
791 self.primitive = PrimitiveAttributes(
792 self,
793 defaults=defaults,
794 kwargs={"extents": extents, "transform": transform},
795 mutable=mutable,
796 )
798 def to_dict(self):
799 """
800 Get a copy of the current Box primitive as
801 a JSON-serializable dict that matches the schema
802 in `trimesh/resources/schema/box.schema.json`
804 Returns
805 ----------
806 as_dict : dict
807 Serializable data for this primitive.
808 """
809 return {
810 "kind": "box",
811 "transform": self.primitive.transform.tolist(),
812 "extents": self.primitive.extents.tolist(),
813 }
815 @property
816 def transform(self):
817 return self.primitive.transform
819 def sample_volume(self, count, seed: Seed = None):
820 """
821 Return random samples from inside the volume of the box.
823 Parameters
824 -------------
825 count : int
826 Number of samples to return
827 seed : None or int
828 Seed for deterministic results, otherwise OS entropy.
830 Returns
831 ----------
832 samples : (count, 3) float
833 Points inside the volume
834 """
835 samples = sample.volume_rectangular(
836 extents=self.primitive.extents,
837 count=count,
838 transform=self.primitive.transform,
839 seed=seed,
840 )
841 return samples
843 def sample_grid(self, count=None, step=None):
844 """
845 Return a 3D grid which is contained by the box.
846 Samples are either 'step' distance apart, or there are
847 'count' samples per box side.
849 Parameters
850 -----------
851 count : int or (3,) int
852 If specified samples are spaced with np.linspace
853 step : float or (3,) float
854 If specified samples are spaced with np.arange
856 Returns
857 -----------
858 grid : (n, 3) float
859 Points inside the box
860 """
862 if count is not None and step is not None:
863 raise ValueError("only step OR count can be specified!")
865 # create pre- transform bounds from extents
866 bounds = np.array([-self.primitive.extents, self.primitive.extents]) * 0.5
868 if step is not None:
869 grid = util.grid_arange(bounds, step=step)
870 elif count is not None:
871 grid = util.grid_linspace(bounds, count=count)
872 else:
873 raise ValueError("either count or step must be specified!")
875 transformed = tf.transform_points(grid, matrix=self.primitive.transform)
876 return transformed
878 @property
879 def is_oriented(self):
880 """
881 Returns whether or not the current box is rotated at all.
882 """
883 if util.is_shape(self.primitive.transform, (4, 4)):
884 return not np.allclose(self.primitive.transform[0:3, 0:3], np.eye(3))
885 else:
886 return False
888 @cache_decorator
889 def volume(self):
890 """
891 Volume of the box Primitive.
893 Returns
894 --------
895 volume : float
896 Volume of box.
897 """
898 volume = float(np.prod(self.primitive.extents))
899 return volume
901 def _create_mesh(self):
902 log.debug("creating mesh for Box primitive")
903 box = creation.box(
904 extents=self.primitive.extents, transform=self.primitive.transform
905 )
907 self._cache.cache.update(box._cache.cache)
908 self._cache["vertices"] = box.vertices
909 self._cache["faces"] = box.faces
910 self._cache["face_normals"] = box.face_normals
912 def as_outline(self):
913 """
914 Return a Path3D containing the outline of the box.
916 Returns
917 -----------
918 outline : trimesh.path.Path3D
919 Outline of box primitive
920 """
921 # do the import in function to keep soft dependency
922 from .path.creation import box_outline
924 # return outline with same size as primitive
925 return box_outline(
926 extents=self.primitive.extents, transform=self.primitive.transform
927 )
930class Extrusion(Primitive):
931 def __init__(
932 self,
933 polygon=None,
934 transform: ArrayLike | None = None,
935 height: Number = 1.0,
936 mutable: bool = True,
937 mid_plane: bool = False,
938 ):
939 """
940 Create an Extrusion primitive, which
941 is a subclass of Trimesh.
943 Parameters
944 ----------
945 polygon : shapely.geometry.Polygon
946 Polygon to extrude
947 transform : (4, 4) float
948 Transform to apply after extrusion
949 height : float
950 Height to extrude polygon by
951 mutable : bool
952 Are extents and transform mutable after creation.
953 """
954 # do the import here, fail early if Shapely isn't installed
955 from shapely.geometry import Point
957 # run the Trimesh init
958 super().__init__()
959 # set default values
960 defaults = {
961 "polygon": Point([0, 0]).buffer(1.0),
962 "transform": np.eye(4),
963 "height": 1.0,
964 "mid_plane": False,
965 }
967 self.primitive = PrimitiveAttributes(
968 self,
969 defaults=defaults,
970 kwargs={
971 "transform": transform,
972 "polygon": polygon,
973 "height": height,
974 "mid_plane": mid_plane,
975 },
976 mutable=mutable,
977 )
979 @cache_decorator
980 def area(self):
981 """
982 The surface area of the primitive extrusion.
984 Calculated from polygon and height to avoid mesh creation.
986 Returns
987 ----------
988 area: float
989 Surface area of 3D extrusion
990 """
991 # area of the sides of the extrusion
992 area = abs(self.primitive.height * self.primitive.polygon.length)
993 # area of the two caps of the extrusion
994 area += self.primitive.polygon.area * 2
995 return area
997 @cache_decorator
998 def volume(self):
999 """
1000 The volume of the Extrusion primitive.
1001 Calculated from polygon and height to avoid mesh creation.
1003 Returns
1004 ----------
1005 volume : float
1006 Volume of 3D extrusion
1007 """
1008 # height may be negative
1009 volume = abs(self.primitive.polygon.area * self.primitive.height)
1010 return volume
1012 @cache_decorator
1013 def direction(self):
1014 """
1015 Based on the extrudes transform what is the
1016 vector along which the polygon will be extruded.
1018 Returns
1019 ---------
1020 direction : (3,) float
1021 Unit direction vector
1022 """
1023 # only consider rotation and signed height
1024 direction = np.dot(
1025 self.primitive.transform[:3, :3], [0.0, 0.0, np.sign(self.primitive.height)]
1026 )
1027 return direction
1029 @property
1030 def origin(self):
1031 """
1032 Based on the extrude transform what is the
1033 origin of the plane it is extruded from.
1035 Returns
1036 -----------
1037 origin : (3,) float
1038 Origin of extrusion plane
1039 """
1040 return self.primitive.transform[:3, 3]
1042 @property
1043 def transform(self):
1044 return self.primitive.transform
1046 @cache_decorator
1047 def bounding_box_oriented(self):
1048 # no docstring for inheritance
1049 # calculate OBB using 2D polygon and known axis
1050 from . import bounds
1052 # find the 2D bounding box using the polygon
1053 to_origin, box = bounds.oriented_bounds_2D(self.primitive.polygon.exterior.coords)
1054 # 3D extents
1055 extents = np.append(box, abs(self.primitive.height))
1056 # calculate to_3D transform from 2D obb
1057 rotation_Z = np.linalg.inv(tf.planar_matrix_to_3D(to_origin))
1058 rotation_Z[2, 3] = self.primitive.height / 2.0
1059 # combine the 2D OBB transformation with the 2D projection transform
1060 to_3D = np.dot(self.primitive.transform, rotation_Z)
1061 return Box(transform=to_3D, extents=extents, mutable=False)
1063 def slide(self, distance):
1064 """
1065 Alter the transform of the current extrusion to slide it
1066 along its extrude_direction vector
1068 Parameters
1069 -----------
1070 distance : float
1071 Distance along self.extrude_direction to move
1072 """
1073 distance = float(distance)
1074 translation = np.eye(4)
1075 translation[2, 3] = distance
1076 new_transform = np.dot(self.primitive.transform.copy(), translation.copy())
1077 self.primitive.transform = new_transform
1079 def buffer(self, distance, distance_height=None, **kwargs):
1080 """
1081 Return a new Extrusion object which is expanded in profile
1082 and in height by a specified distance.
1084 Parameters
1085 --------------
1086 distance : float
1087 Distance to buffer polygon
1088 distance_height : float
1089 Distance to buffer above and below extrusion
1090 kwargs : dict
1091 Passed to Extrusion constructor
1093 Returns
1094 ----------
1095 buffered : primitives.Extrusion
1096 Extrusion object with new values
1097 """
1098 distance = float(distance)
1099 # if not specified use same distance for everything
1100 if distance_height is None:
1101 distance_height = distance
1103 # start with current height
1104 height = self.primitive.height
1105 # if current height is negative offset by negative amount
1106 height += np.sign(height) * 2.0 * distance_height
1108 # create a new extrusion with a buffered polygon
1109 # use type(self) vs Extrusion to handle subclasses
1110 buffered = type(self)(
1111 transform=self.primitive.transform.copy(),
1112 polygon=self.primitive.polygon.buffer(distance),
1113 height=height,
1114 **kwargs,
1115 )
1117 # slide the stock along the axis
1118 buffered.slide(-np.sign(height) * distance_height)
1120 return buffered
1122 def to_dict(self):
1123 """
1124 Get a copy of the current Extrusion primitive as
1125 a JSON-serializable dict that matches the schema
1126 in `trimesh/resources/schema/extrusion.schema.json`
1128 Returns
1129 ----------
1130 as_dict : dict
1131 Serializable data for this primitive.
1132 """
1133 return {
1134 "kind": "extrusion",
1135 "polygon": self.primitive.polygon.wkt,
1136 "transform": self.primitive.transform.tolist(),
1137 "height": float(self.primitive.height),
1138 }
1140 def _create_mesh(self):
1141 log.debug("creating mesh for Extrusion primitive")
1142 # extrude the polygon along Z
1143 mesh = creation.extrude_polygon(
1144 polygon=self.primitive.polygon,
1145 height=self.primitive.height,
1146 transform=self.primitive.transform,
1147 mid_plane=self.primitive.mid_plane,
1148 )
1150 # check volume here in unit tests
1151 if tol.strict and mesh.volume < 0.0:
1152 raise ValueError("matrix inverted mesh!")
1154 # cache mesh geometry in the primitive
1155 self._cache["vertices"] = mesh.vertices
1156 self._cache["faces"] = mesh.faces