trimesh API Reference
Full documentation for trimesh (4.12.2)
trimesh.Geometry
Python Library Documentation: class Geometry in module trimesh.parent
class Geometry(abc.ABC)
| `Geometry` is the parent class for all geometry.
|
| By decorating a method with `abc.abstractmethod` it means
| the objects that inherit from `Geometry` MUST implement
| those methods.
|
| Method resolution order:
| Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_transform(self, matrix: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Any
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| copy(self)
|
| export(self, file_obj, file_type=None)
|
| show(self)
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| bounds
|
| extents
|
| identifier_hash
|
| is_empty
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__add__', 'apply_transform', 'bounds...
|
| __annotations__ = {'metadata': <class 'dict'>}
trimesh.PointCloud
Python Library Documentation: class PointCloud in module trimesh.points
class PointCloud(trimesh.parent.Geometry3D)
| PointCloud(vertices, colors=None, metadata=None, **kwargs)
|
| Hold 3D points in an object which can be visualized
| in a scene.
|
| Method resolution order:
| PointCloud
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
|
| __getitem__(self, *args, **kwargs)
|
| __init__(self, vertices, colors=None, metadata=None, **kwargs)
| Load an array of points into a PointCloud object.
|
| Parameters
| -------------
| vertices : (n, 3) float
| Points in space
| colors : (n, 4) uint8 or None
| RGBA colors for each point
| metadata : dict or None
| Metadata about points
|
| __setitem__(self, *args, **kwargs)
|
| apply_transform(self, transform)
| Apply a homogeneous transformation to the PointCloud
| object in- place.
|
| Parameters
| --------------
| transform : (4, 4) float
| Homogeneous transformation to apply to PointCloud
|
| copy(self)
| Safely get a copy of the current point cloud.
|
| Copied objects will have emptied caches to avoid memory
| issues and so may be slow on initial operations until
| caches are regenerated.
|
| Current object will *not* have its cache cleared.
|
| Returns
| ---------
| copied : trimesh.PointCloud
| Copy of current point cloud
|
| export(self, file_obj=None, file_type=None, **kwargs)
| Export the current pointcloud to a file object.
| If file_obj is a filename, file will be written there.
| Supported formats are xyz
| Parameters
| ------------
| file_obj: open writeable file object
| str, file name where to save the pointcloud
| None, if you would like this function to return the export blob
| file_type: str
| Which file type to export as.
| If file name is passed this is not required
|
| hash(self)
| Get a hash of the current vertices.
|
| Returns
| ----------
| hash : str
| Hash of self.vertices
|
| merge_vertices(self)
| Merge vertices closer than tol.merge (default: 1e-8)
|
| query(self, input_points, **kwargs)
| Find the the closest points and associated attributes from this PointCloud.
| Parameters
| ------------
| input_points : (n, 3) float
| Input query points
| kwargs : dict
| Arguments for proximity.query_from_points
| result : proximity.NearestQueryResult
| Result of the query.
|
| scene(self)
| A scene containing just the PointCloud
|
| Returns
| ----------
| scene : trimesh.Scene
| Scene object containing this PointCloud
|
| show(self, **kwargs)
| Open a viewer window displaying the current PointCloud
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| bounds
| The axis aligned bounds of the PointCloud
|
| Returns
| ------------
| bounds : (2, 3) float
| Minimum, Maximum verteex
|
| centroid
| The mean vertex position
|
| Returns
| ------------
| centroid : (3,) float
| Mean vertex position
|
| convex_hull
| A convex hull of every point.
|
| Returns
| -------------
| convex_hull : trimesh.Trimesh
| A watertight mesh of the hull of the points
|
| extents
| The size of the axis aligned bounds
|
| Returns
| ------------
| extents : (3,) float
| Edge length of axis aligned bounding box
|
| identifier
| Return a simple array representing this PointCloud
| that can be used to identify identical arrays.
|
| Returns
| ----------
| identifier : (9,)
| A flat array of data representing the cloud.
|
| identifier_hash
| A hash of the PointCloud's identifier that can be used
| to detect duplicates.
|
| is_empty
| Are there any vertices defined or not.
|
| Returns
| ----------
| empty : bool
| True if no vertices defined
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| moment_inertia
|
| shape
| Get the shape of the pointcloud
|
| Returns
| ----------
| shape : (2,) int
| Shape of vertex array
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| colors
| Stored per- point color
|
| Returns
| ----------
| colors : (len(self.vertices), 4) np.uint8
| Per- point RGBA color
|
| vertices
| Vertices of the PointCloud
|
| Returns
| ------------
| vertices : (n, 3) float
| Points in the PointCloud
|
| weights
| If each point has a specific weight assigned to it.
|
| Returns
| -----------
| weights : (n,)
| A per-vertex weight.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
trimesh.Scene
Python Library Documentation: class Scene in module trimesh.scene.scene
class Scene(trimesh.parent.Geometry3D)
| Scene(geometry: Union[trimesh.parent.Geometry, collections.abc.Iterable[trimesh.parent.Geometry], dict[str, trimesh.parent.Geometry], collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, base_frame: str = 'world', metadata: Optional[dict] = None, graph: Optional[trimesh.scene.transforms.SceneGraph] = None, camera: Optional[trimesh.scene.cameras.Camera] = None, lights: Optional[collections.abc.Sequence[trimesh.scene.lighting.Light]] = None, camera_transform: Optional[numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]] = None)
|
| A simple scene graph which can be rendered directly via
| pyglet/openGL or through other endpoints such as a
| raytracer. Meshes are added by name, which can then be
| moved by updating transform in the transform tree.
|
| Method resolution order:
| Scene
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
| Concatenate the current scene with another scene or mesh.
|
| Parameters
| ------------
| other : trimesh.Scene, trimesh.Trimesh, trimesh.Path
| Other object to append into the result scene
|
| Returns
| ------------
| appended : trimesh.Scene
| Scene with geometry from both scenes
|
| __hash__(self) -> int
| Return information about scene which is hashable.
|
| Returns
| ---------
| hashed
| String hashing scene.
|
| __init__(self, geometry: Union[trimesh.parent.Geometry, collections.abc.Iterable[trimesh.parent.Geometry], dict[str, trimesh.parent.Geometry], collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, base_frame: str = 'world', metadata: Optional[dict] = None, graph: Optional[trimesh.scene.transforms.SceneGraph] = None, camera: Optional[trimesh.scene.cameras.Camera] = None, lights: Optional[collections.abc.Sequence[trimesh.scene.lighting.Light]] = None, camera_transform: Optional[numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]] = None)
| Create a new Scene object.
|
| Parameters
| -------------
| geometry : Trimesh, Path2D, Path3D PointCloud or list
| Geometry to initially add to the scene
| base_frame
| Name of base frame
| metadata
| Any metadata about the scene
| graph
| A passed transform graph to use
| camera : Camera or None
| A passed camera to use
| lights : [trimesh.scene.lighting.Light] or None
| A passed lights to use
| camera_transform
| Homogeneous (4, 4) camera transform in the base frame
|
| add_geometry(self, geometry: Union[trimesh.parent.Geometry, collections.abc.Iterable[trimesh.parent.Geometry], dict[str, trimesh.parent.Geometry], collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], node_name: Optional[str] = None, geom_name: Optional[str] = None, parent_node_name: Optional[str] = None, transform: Optional[numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]] = None, metadata: Optional[dict] = None)
| Add a geometry to the scene.
|
| If the mesh has multiple transforms defined in its
| metadata, they will all be copied into the
| TransformForest of the current scene automatically.
|
| Parameters
| ----------
| geometry : Trimesh, Path2D, Path3D PointCloud or list
| Geometry to initially add to the scene
| node_name : None or str
| Name of the added node.
| geom_name : None or str
| Name of the added geometry.
| parent_node_name : None or str
| Name of the parent node in the graph.
| transform : None or (4, 4) float
| Transform that applies to the added node.
| metadata : None or dict
| Optional metadata for the node.
|
| Returns
| ----------
| node_name : str
| Name of single node in self.graph (passed in) or None if
| node was not added (eg. geometry was null or a Scene).
|
| apply_transform(self, transform)
| Apply a transform to all children of the base frame
| without modifying any geometry.
|
| Parameters
| --------------
| transform : (4, 4)
| Homogeneous transformation matrix.
|
| camera_rays(self) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.int64]]]
| Calculate the trimesh.scene.Camera origin and ray
| direction vectors. Returns one ray per pixel as set
| in camera.resolution
|
| Returns
| --------------
| origin: (n, 3) float
| Ray origins in space
| vectors: (n, 3) float
| Ray direction unit vectors in world coordinates
| pixels : (n, 2) int
| Which pixel does each ray correspond to in an image
|
| convert_units(self, desired: str, guess: bool = False) -> 'Scene'
| If geometry has units defined convert them to new units.
|
| Returns a new scene with geometries and transforms scaled.
|
| Parameters
| ----------
| desired : str
| Desired final unit system: 'inches', 'mm', etc.
| guess : bool
| Is the converter allowed to guess scale when models
| don't have it specified in their metadata.
|
| Returns
| ----------
| scaled : trimesh.Scene
| Copy of scene with scaling applied and units set
| for every model
|
| copy(self) -> 'Scene'
| Return a deep copy of the current scene
|
| Returns
| ----------
| copied : trimesh.Scene
| Copy of the current scene
|
| delete_geometry(self, names: Union[set, str, collections.abc.Sequence]) -> None
| Delete one more multiple geometries from the scene and also
| remove any node in the transform graph which references it.
|
| Parameters
| --------------
| name : hashable
| Name that references self.geometry
|
| dump(self, concatenate: bool = False) -> list[trimesh.parent.Geometry]
| Get a list of every geometry moved to its instance position,
| i.e. freezing or "baking" transforms.
|
| Parameters
| ------------
| concatenate
| KWARG IS DEPRECATED FOR REMOVAL APRIL 2025
| Concatenate results into single geometry.
| This keyword argument will make the type hint incorrect and
| you should replace `Scene.dump(concatenate=True)` with:
| - `Scene.to_geometry()` for a Trimesh, Path2D or Path3D
| - `Scene.to_mesh()` for only `Trimesh` components.
|
| Returns
| ----------
| dumped
| Copies of `Scene.geometry` transformed to their instance position.
|
| explode(self, vector=None, origin=None) -> None
| Explode the current scene in-place around a point and vector.
|
| Parameters
| -----------
| vector : (3,) float or float
| Explode radially around a direction vector or spherically
| origin : (3,) float
| Point to explode around
|
| export(self, file_obj=None, file_type=None, **kwargs)
| Export a snapshot of the current scene.
|
| Parameters
| ----------
| file_obj : str, file-like, or None
| File object to export to
| file_type : str or None
| What encoding to use for meshes
| IE: dict, dict64, stl
|
| Returns
| ----------
| export : bytes
| Only returned if file_obj is None
|
| moment_inertia_frame(self, transform)
| Return the moment of inertia of the current scene relative
| to a transform from the base frame.
|
| Parameters
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3) float
| Inertia tensor at requested frame.
|
| reconstruct_instances(self, cost_threshold: Union[float, numpy.floating] = 1e-05) -> 'Scene'
| If a scene has been "baked" with meshes it means that
| the duplicate nodes have *corresponding vertices* but are
| rigidly transformed to different places.
|
| This means the problem of finding ab instance transform can
| use the `procrustes` analysis which is *very* fast relative
| to more complicated registration problems that require ICP
| and nearest-point-on-surface calculations.
|
| TODO : construct a parent non-geometry node for containing every group.
|
| Parameters
| ----------
| scene
| The scene to handle.
| cost_threshold
| The maximum value for `procrustes` cost which is "squared mean
| vertex distance between pair". If the fit is above this value
| the instance will be left even if it is a duplicate.
|
| Returns
| ---------
| dedupe
| A copy of the scene de-duplicated as much as possible.
|
| rezero(self) -> None
| Move the current scene so that the AABB of the whole
| scene is centered at the origin.
|
| Does this by changing the base frame to a new, offset
| base frame.
|
| save_image(self, resolution=None, **kwargs) -> bytes
| Get a PNG image of a scene.
|
| Parameters
| -----------
| resolution : (2,) int
| Resolution to render image
| **kwargs
| Passed to SceneViewer constructor
|
| Returns
| -----------
| png : bytes
| Render of scene as a PNG
|
| scaled(self, scale: Union[float, numpy.floating, collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> 'Scene'
| Return a copy of the current scene, with meshes and scene
| transforms scaled to the requested factor.
|
| Parameters
| -----------
| scale : float or (3,) float
| Factor to scale meshes and transforms
|
| Returns
| -----------
| scaled : trimesh.Scene
| A copy of the current scene but scaled
|
| set_camera(self, angles=None, distance=None, center=None, resolution=None, fov=None) -> trimesh.scene.cameras.Camera
| Create a camera object for self.camera, and add
| a transform to self.graph for it.
|
| If arguments are not passed sane defaults will be figured
| out which show the mesh roughly centered.
|
| Parameters
| -----------
| angles : (3,) float
| Initial euler angles in radians
| distance : float
| Distance from centroid
| center : (3,) float
| Point camera should be center on
| camera : Camera object
| Object that stores camera parameters
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs)
| Display the current scene.
|
| Parameters
| -----------
| viewer
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| kwargs
| Passed to viewer, such as `smooth=False` which will turn
| off automatic smooth shading
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Apply in-place `mesh.simplify_quadric_decimation` to any meshes
| in the scene.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| strip_visuals(self) -> None
| Strip visuals from every Trimesh geometry
| and set them to an empty `ColorVisuals`.
|
| subscene(self, node: str) -> 'Scene'
| Get part of a scene that succeeds a specified node.
|
| Parameters
| ------------
| node
| Hashable key in `scene.graph`
|
| Returns
| -----------
| subscene
| Partial scene generated from current.
|
| to_geometry(self) -> trimesh.parent.Geometry
| Concatenate geometry in the scene into a single like-typed geometry,
| applying the transforms and "baking" the result. May drop geometry
| if the scene has mixed geometry.
|
| Returns
| ---------
| concat
| Either a Trimesh, Path2D, or Path3D depending on what is in the scene.
|
| to_mesh(self) -> 'trimesh.Trimesh'
| Concatenate every mesh instances in the scene into a single mesh,
| applying transforms and "baking" the result. Will drop any geometry
| in the scene that is not a `Trimesh` object.
|
| Returns
| ----------
| mesh
| All meshes in the scene concatenated into one.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| What is the summed area of every geometry which
| has area.
|
| Returns
| ------------
| area : float
| Summed area of every instanced geometry
|
| bounds
| Return the overall bounding box of the scene.
|
| Returns
| --------
| bounds : (2, 3) float or None
| Position of [min, max] bounding box
| Returns None if no valid bounds exist
|
| bounds_corners
| Get the post-transform AABB for each node
| which has geometry defined.
|
| Returns
| -----------
| corners
| Bounds for each node with vertices:
| {node_name : (2, 3) float}
|
| center_mass
| Find the center of mass for every instance in the scene.
|
| Returns
| ------------
| center_mass : (3,) float
| The center of mass of the scene
|
| centroid
| Return the center of the bounding box for the scene.
|
| Returns
| --------
| centroid : (3) float
| Point for center of bounding box
|
| convex_hull
| The convex hull of the whole scene.
|
| Returns
| ---------
| hull : trimesh.Trimesh
| Trimesh object which is a convex hull of all meshes in scene
|
| duplicate_nodes
| Return a sequence of node keys of identical meshes.
|
| Will include meshes with different geometry but identical
| spatial hashes as well as meshes repeated by self.nodes.
|
| Returns
| -----------
| duplicates
| Keys of self.graph that represent identical geometry
|
| extents
| Return the axis aligned box size of the current scene
| or None if the scene is empty.
|
| Returns
| ----------
| extents
| Bounding box sides length or None for empty scene.
|
| geometry_identifiers
| Look up geometries by identifier hash.
|
| Returns
| ---------
| identifiers
| {Identifier hash: key in self.geometry}
|
| has_camera
|
| identifier_hash
| Get a unique identifier for the scene.
|
| is_empty
| Does the scene have anything in it.
|
| Returns
| ----------
| is_empty
| True if nothing is in the scene
|
| is_valid
| Is every geometry connected to the root node.
|
| Returns
| -----------
| is_valid : bool
| Does every geometry have a transform
|
| moment_inertia
| Return the moment of inertia of the current scene with
| respect to the center of mass of the current scene.
|
| Returns
| ------------
| inertia : (3, 3) float
| Inertia with respect to cartesian axis at `scene.center_mass`
|
| scale
| The approximate scale of the mesh
|
| Returns
| -----------
| scale : float
| The mean of the bounding box edge lengths
|
| triangles
| Return a correctly transformed polygon soup of the
| current scene.
|
| Returns
| ----------
| triangles : (n, 3, 3) float
| Triangles in space
|
| triangles_node
| Which node of self.graph does each triangle come from.
|
| Returns
| ---------
| triangles_index : (len(self.triangles),)
| Node name for each triangle
|
| volume
| What is the summed volume of every geometry which
| has volume
|
| Returns
| ------------
| volume : float
| Summed area of every instanced geometry
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| camera
| Get the single camera for the scene. If not manually
| set one will abe automatically generated.
|
| Returns
| ----------
| camera : trimesh.scene.Camera
| Camera object defined for the scene
|
| camera_transform
| Get camera transform in the base frame.
|
| Returns
| -------
| camera_transform : (4, 4) float
| Camera transform in the base frame
|
| lights
| Get a list of the lights in the scene. If nothing is
| set it will generate some automatically.
|
| Returns
| -------------
| lights : [trimesh.scene.lighting.Light]
| Lights in the scene.
|
| units
| Get the units for every model in the scene. If the scene has
| mixed units or no units this will return None.
|
| Returns
| -----------
| units
| Units for every model in the scene or None
| if there are no units or mixed units
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
trimesh.Trimesh
Python Library Documentation: class Trimesh in module trimesh.base
class Trimesh(trimesh.parent.Geometry3D)
| Trimesh(vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, vertex_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, metadata: Optional[dict[str, Any]] = None, process: bool = True, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, use_embree: bool = True, initial_cache: Optional[dict[str, numpy.ndarray]] = None, visual: Union[trimesh.visual.color.ColorVisuals, trimesh.visual.texture.TextureVisuals, NoneType] = None, **kwargs) -> None
|
| Method resolution order:
| Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| __copy__(self, *args) -> 'Trimesh'
|
| __deepcopy__(self, *args) -> 'Trimesh'
|
| __init__(self, vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, vertex_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, metadata: Optional[dict[str, Any]] = None, process: bool = True, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, use_embree: bool = True, initial_cache: Optional[dict[str, numpy.ndarray]] = None, visual: Union[trimesh.visual.color.ColorVisuals, trimesh.visual.texture.TextureVisuals, NoneType] = None, **kwargs) -> None
| A Trimesh object contains a triangular 3D mesh.
|
| Parameters
| ------------
| vertices : (n, 3) float
| Array of vertex locations
| faces : (m, 3) or (m, 4) int
| Array of triangular or quad faces (triangulated on load)
| face_normals : (m, 3) float
| Array of normal vectors corresponding to faces
| vertex_normals : (n, 3) float
| Array of normal vectors for vertices
| face_colors : (n, 3|4) uint8
| Array of colors for faces
| vertex_colors : (n, 3|4) uint8
| Array of colors for vertices
| face_attributes : dict
| Attributes corresponding to faces
| vertex_attributes : dict
| Attributes corresponding to vertices
| metadata : dict
| Any metadata about the mesh
| process : bool
| if True, Nan and Inf values will be removed
| immediately and vertices will be merged
| validate : bool
| If True, degenerate and duplicate faces will be
| removed immediately, and some functions will alter
| the mesh to ensure consistent results.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| use_embree : bool
| If True try to use pyembree raytracer.
| If pyembree is not available it will automatically fall
| back to a much slower rtree/numpy implementation
| initial_cache : dict
| A way to pass things to the cache in case expensive
| things were calculated before creating the mesh object.
| visual : ColorVisuals or TextureVisuals
| Assigned to self.visual
|
| apply_transform(self, matrix: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Self
| Transform mesh by a homogeneous transformation matrix.
|
| Does the bookkeeping to avoid recomputing things so this function
| should be used rather than directly modifying self.vertices
| if possible.
|
| Parameters
| ------------
| matrix : (4, 4) float
| Homogeneous transformation matrix
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| copy(self, include_cache: bool = False, include_visual: bool = True) -> 'Trimesh'
| Safely return a copy of the current mesh.
|
| By default, copied meshes will have emptied cache
| to avoid memory issues and so may be slow on initial
| operations until caches are regenerated.
|
| Current object will *never* have its cache cleared.
|
| Parameters
| ------------
| include_cache : bool
| If True, will shallow copy cached data to new mesh
| include_visual : bool
| If True, will copy visual information
|
| Returns
| ---------
| copied : trimesh.Trimesh
| Copy of current mesh
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| to_dict(self) -> dict[str, typing.Union[str, list[list[float]], list[list[int]]]]
| Return a dictionary representation of the current mesh
| with keys that can be used as the kwargs for the
| Trimesh constructor and matches the schema in:
| `trimesh/resources/schema/primitive/trimesh.schema.json`
|
| Returns
| ----------
| result : dict
| Matches schema and Trimesh constructor.
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| Summed area of all triangles in the current mesh.
|
| Returns
| ---------
| area : float
| Surface area of mesh
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| moment_inertia
| Return the moment of inertia matrix of the current mesh.
| If mesh isn't watertight this is garbage. The returned
| moment of inertia is *axis aligned* at the mesh's center
| of mass `mesh.center_mass`. If you want the moment at any
| other frame including the origin call:
| `mesh.moment_inertia_frame`
|
| Returns
| ---------
| inertia : (3, 3) float
| Moment of inertia of the current mesh at the center of
| mass and aligned with the cartesian axis.
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| volume
| Volume of the current mesh calculated using a surface
| integral. If the current mesh isn't watertight this is
| garbage.
|
| Returns
| ---------
| volume : float
| Volume of the current mesh
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
trimesh.available_formats
Python Library Documentation: function available_formats in module trimesh.exchange.load
available_formats() -> set[str]
Get a list of all available loaders
Returns
-----------
loaders
Extensions of all available loaders
i.e. `{'stl', 'ply', 'dxf'}`
trimesh.base
Python Library Documentation: module trimesh.base in trimesh
NAME
trimesh.base - # trimesh
DESCRIPTION
https://github.com/mikedh/trimesh
---------------------------------
Library for importing, exporting and doing simple operations on triangular meshes.
CLASSES
trimesh.parent.Geometry3D(trimesh.parent.Geometry)
Trimesh
class Trimesh(trimesh.parent.Geometry3D)
| Trimesh(vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, vertex_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, metadata: Optional[dict[str, Any]] = None, process: bool = True, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, use_embree: bool = True, initial_cache: Optional[dict[str, numpy.ndarray]] = None, visual: Union[trimesh.visual.color.ColorVisuals, trimesh.visual.texture.TextureVisuals, NoneType] = None, **kwargs) -> None
|
| Method resolution order:
| Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| __copy__(self, *args) -> 'Trimesh'
|
| __deepcopy__(self, *args) -> 'Trimesh'
|
| __init__(self, vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_normals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, face_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, vertex_attributes: Optional[dict[str, Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]]] = None, metadata: Optional[dict[str, Any]] = None, process: bool = True, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, use_embree: bool = True, initial_cache: Optional[dict[str, numpy.ndarray]] = None, visual: Union[trimesh.visual.color.ColorVisuals, trimesh.visual.texture.TextureVisuals, NoneType] = None, **kwargs) -> None
| A Trimesh object contains a triangular 3D mesh.
|
| Parameters
| ------------
| vertices : (n, 3) float
| Array of vertex locations
| faces : (m, 3) or (m, 4) int
| Array of triangular or quad faces (triangulated on load)
| face_normals : (m, 3) float
| Array of normal vectors corresponding to faces
| vertex_normals : (n, 3) float
| Array of normal vectors for vertices
| face_colors : (n, 3|4) uint8
| Array of colors for faces
| vertex_colors : (n, 3|4) uint8
| Array of colors for vertices
| face_attributes : dict
| Attributes corresponding to faces
| vertex_attributes : dict
| Attributes corresponding to vertices
| metadata : dict
| Any metadata about the mesh
| process : bool
| if True, Nan and Inf values will be removed
| immediately and vertices will be merged
| validate : bool
| If True, degenerate and duplicate faces will be
| removed immediately, and some functions will alter
| the mesh to ensure consistent results.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| use_embree : bool
| If True try to use pyembree raytracer.
| If pyembree is not available it will automatically fall
| back to a much slower rtree/numpy implementation
| initial_cache : dict
| A way to pass things to the cache in case expensive
| things were calculated before creating the mesh object.
| visual : ColorVisuals or TextureVisuals
| Assigned to self.visual
|
| apply_transform(self, matrix: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Self
| Transform mesh by a homogeneous transformation matrix.
|
| Does the bookkeeping to avoid recomputing things so this function
| should be used rather than directly modifying self.vertices
| if possible.
|
| Parameters
| ------------
| matrix : (4, 4) float
| Homogeneous transformation matrix
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| copy(self, include_cache: bool = False, include_visual: bool = True) -> 'Trimesh'
| Safely return a copy of the current mesh.
|
| By default, copied meshes will have emptied cache
| to avoid memory issues and so may be slow on initial
| operations until caches are regenerated.
|
| Current object will *never* have its cache cleared.
|
| Parameters
| ------------
| include_cache : bool
| If True, will shallow copy cached data to new mesh
| include_visual : bool
| If True, will copy visual information
|
| Returns
| ---------
| copied : trimesh.Trimesh
| Copy of current mesh
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| to_dict(self) -> dict[str, typing.Union[str, list[list[float]], list[list[int]]]]
| Return a dictionary representation of the current mesh
| with keys that can be used as the kwargs for the
| Trimesh constructor and matches the schema in:
| `trimesh/resources/schema/primitive/trimesh.schema.json`
|
| Returns
| ----------
| result : dict
| Matches schema and Trimesh constructor.
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| Summed area of all triangles in the current mesh.
|
| Returns
| ---------
| area : float
| Surface area of mesh
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| moment_inertia
| Return the moment of inertia matrix of the current mesh.
| If mesh isn't watertight this is garbage. The returned
| moment of inertia is *axis aligned* at the mesh's center
| of mass `mesh.center_mass`. If you want the moment at any
| other frame including the origin call:
| `mesh.moment_inertia_frame`
|
| Returns
| ---------
| inertia : (3, 3) float
| Moment of inertia of the current mesh at the center of
| mass and aligned with the cartesian axis.
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| volume
| Volume of the current mesh calculated using a surface
| integral. If the current mesh isn't watertight this is
| garbage.
|
| Returns
| ---------
| volume : float
| Volume of the current mesh
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
BooleanEngineType = typing.Literal['manifold', 'blender', None]
Floating = typing.Union[float, numpy.floating]
Index = <trimesh.exceptions.ExceptionWrapper object>
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
Loadable = typing.Union[str, pathlib.Path, typing.IO, _io.B...yping.Te...
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Self = typing.Self
Used to spell the type of "self" in classes.
Example::
from typing import Self
class Foo:
def return_self(self) -> Self:
...
return self
This is especially useful for:
- classmethods that are used as alternative constructors
- annotating an `__enter__` method which returns self
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
ViewerType = typing.Union[NoneType, collections.abc.Callable, typing.L...
log = <Logger trimesh.util (WARNING)>
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\base.py
trimesh.boolean
Python Library Documentation: module trimesh.boolean in trimesh
NAME
trimesh.boolean
DESCRIPTION
boolean.py
-------------
Do boolean operations on meshes using either Blender or Manifold.
FUNCTIONS
boolean_manifold(meshes: collections.abc.Sequence, operation: Literal['difference', 'union', 'intersection'], check_volume: bool = True, **kwargs)
Run an operation on a set of meshes using the Manifold engine.
Parameters
----------
meshes : list of trimesh.Trimesh
Meshes to be processed
operation
Which boolean operation to do.
check_volume
Raise an error if not all meshes are watertight
positive volumes. Advanced users may want to ignore
this check as it is expensive.
kwargs
Passed through to the `engine`.
difference(meshes: collections.abc.Sequence, engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs)
Compute the boolean difference between a mesh an n other meshes.
Parameters
----------
meshes : sequence of trimesh.Trimesh
Meshes to be processed.
engine
Which backend to use, i.e. 'blender' or 'manifold'
check_volume
Raise an error if not all meshes are watertight
positive volumes. Advanced users may want to ignore
this check as it is expensive.
kwargs
Passed through to the `engine`.
Returns
----------
difference
A `Trimesh` that contains `meshes[0] - meshes[1:]`
intersection(meshes: collections.abc.Sequence, engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs)
Compute the boolean intersection between a mesh and other meshes.
Parameters
----------
meshes : list of trimesh.Trimesh
Meshes to be processed
engine : str
Which backend to use, i.e. 'blender' or 'manifold'
check_volume
Raise an error if not all meshes are watertight
positive volumes. Advanced users may want to ignore
this check as it is expensive.
kwargs
Passed through to the `engine`.
Returns
----------
intersection
A `Trimesh` that contains the intersection geometry.
union(meshes: collections.abc.Sequence, engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs)
Compute the boolean union between a mesh an n other meshes.
Parameters
----------
meshes : list of trimesh.Trimesh
Meshes to be processed
engine : str
Which backend to use, i.e. 'blender' or 'manifold'
check_volume
Raise an error if not all meshes are watertight
positive volumes. Advanced users may want to ignore
this check as it is expensive.
kwargs
Passed through to the `engine`.
Returns
----------
union
A `Trimesh` that contains the union of all passed meshes.
DATA
BooleanEngineType = typing.Literal['manifold', 'blender', None]
BooleanOperationType = typing.Literal['difference', 'union', 'intersec...
Manifold = <trimesh.exceptions.ExceptionWrapper object>
Mesh = <trimesh.exceptions.ExceptionWrapper object>
__annotations__ = {'_engines': dict[str, collections.abc.Callable]}
engines_available = set()
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\boolean.py
trimesh.bounds
Python Library Documentation: module trimesh.bounds in trimesh
NAME
trimesh.bounds
FUNCTIONS
contains(bounds: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
Do an axis aligned bounding box check on an array of points.
Parameters
-----------
bounds : (2, dimension) float
Axis aligned bounding box
points : (n, dimension) float
Points in space
Returns
-----------
points_inside : (n,) bool
True if points are inside the AABB
corners(bounds)
Given a pair of axis aligned bounds, return all
8 corners of the bounding box.
Parameters
----------
bounds : (2,3) or (2,2) float
Axis aligned bounds
Returns
----------
corners : (8,3) float
Corner vertices of the cube
minimum_cylinder(obj, sample_count=6, angle_tol=0.001)
Find the approximate minimum volume cylinder which contains
a mesh or a a list of points.
Samples a hemisphere then uses scipy.optimize to pick the
final orientation of the cylinder.
A nice discussion about better ways to implement this is here:
https://www.staff.uni-mainz.de/schoemer/publications/ALGO00.pdf
Parameters
----------
obj : trimesh.Trimesh, or (n, 3) float
Mesh object or points in space
sample_count : int
How densely should we sample the hemisphere.
Angular spacing is 180 degrees / this number
Returns
----------
result : dict
With keys:
'radius' : float, radius of cylinder
'height' : float, height of cylinder
'transform' : (4,4) float, transform from the origin
to centered cylinder
now = time(...)
time() -> floating-point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
oriented_bounds(obj, angle_digits=1, ordered=True, normal=None, coplanar_tol=1e-12)
Find the oriented bounding box for a Trimesh
Parameters
----------
obj : trimesh.Trimesh, (n, 2) float, or (n, 3) float
Mesh object or points in 2D or 3D space
angle_digits : int
How much angular precision do we want on our result.
Even with less precision the returned extents will cover
the mesh albeit with larger than minimal volume, and may
experience substantial speedups.
ordered : bool
Return a consistent order for bounds
normal : None or (3,) float
Override search for normal on 3D meshes.
coplanar_tol : float
If a convex hull fails and we are checking to see if the
points are coplanar this is the maximum deviation from
a plane where the points will be considered coplanar.
Returns
----------
to_origin : (4,4) float
Transformation matrix which will move the center of the
bounding box of the input mesh to the origin.
extents: (3,) float
The extents of the mesh once transformed with to_origin
oriented_bounds_2D(points, qhull_options='QbB')
Find an oriented bounding box for an array of 2D points.
Details on qhull options:
http://www.qhull.org/html/qh-quick.htm#options
Parameters
----------
points : (n,2) float
Points in 2D.
Returns
----------
transform : (3,3) float
Homogeneous 2D transformation matrix to move the
input points so that the axis aligned bounding box
is CENTERED AT THE ORIGIN.
rectangle : (2,) float
Size of extents once input points are transformed
by transform
to_extents(bounds)
Convert an axis aligned bounding box to extents and
transform.
Parameters
------------
bounds : (2, 3) float
Axis aligned bounds in space
Returns
------------
extents : (3,) float
Extents of the bounding box
transform : (4, 4) float
Homogeneous transform moving extents to bounds
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
log = <Logger trimesh.util (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\bounds.py
trimesh.caching
Python Library Documentation: module trimesh.caching in trimesh
NAME
trimesh.caching
DESCRIPTION
caching.py
-----------
Functions and classes that help with tracking changes
in `numpy.ndarray` and clearing cached values based
on those changes.
You should really `pip install xxhash`:
```
In [23]: %timeit int(blake2b(d).hexdigest(), 16)
102 us +/- 684 ns per loop
In [24]: %timeit int(sha256(d).hexdigest(), 16)
142 us +/- 3.73 us
In [25]: %timeit xxh3_64_intdigest(d)
3.37 us +/- 116 ns per loop
```
CLASSES
builtins.object
Cache
DiskCache
collections.abc.Mapping(collections.abc.Collection)
DataStore
numpy.ndarray(builtins.object)
TrackedArray
class Cache(builtins.object)
| Cache(id_function, force_immutable=False)
|
| Class to cache values which will be stored until the
| result of an ID function changes.
|
| Methods defined here:
|
| __contains__(self, key)
|
| __enter__(self)
|
| __exit__(self, *args)
|
| __getitem__(self, key)
| Get an item from the cache. If the item
| is not in the cache, it will return None
|
| Parameters
| -------------
| key : hashable
| Key in dict
|
| Returns
| -------------
| cached : object, or None
| Object that was stored
|
| __init__(self, id_function, force_immutable=False)
| Create a cache object.
|
| Parameters
| ------------
| id_function : function
| Returns hashable value
| force_immutable : bool
| If set will make all numpy arrays read-only
|
| __len__(self)
|
| __setitem__(self, key, value)
| Add an item to the cache.
|
| Parameters
| ------------
| key : hashable
| Key to reference value
| value : any
| Value to store in cache
|
| clear(self, exclude=None)
| Remove elements in the cache.
|
| Parameters
| -----------
| exclude : list
| List of keys in cache to not clear.
|
| delete(self, key)
| Remove a key from the cache.
|
| id_set(self)
| Set the current ID to the value of the ID function.
|
| update(self, items)
| Update the cache with a set of key, value pairs without
| checking id_function.
|
| verify(self)
| Verify that the cached values are still for the same
| value of id_function and delete all stored items if
| the value of id_function has changed.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class DataStore(collections.abc.Mapping)
| A class to store multiple numpy arrays and track them all
| for changes.
|
| Operates like a dict that only stores numpy.ndarray
|
| Method resolution order:
| DataStore
| collections.abc.Mapping
| collections.abc.Collection
| collections.abc.Sized
| collections.abc.Iterable
| collections.abc.Container
| builtins.object
|
| Methods defined here:
|
| __contains__(self, key)
|
| __delitem__(self, key)
|
| __getitem__(self, key)
|
| __hash__(self)
| Get a hash reflecting everything in the DataStore.
|
| Returns
| ----------
| hash : str
| hash of data in hexadecimal
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __setitem__(self, key, data)
| Store an item in the DataStore.
|
| Parameters
| -------------
| key
| A hashable key to store under
| data
| Usually a numpy array which will be subclassed
| but anything hashable should be able to be stored.
|
| clear(self)
| Remove all data from the DataStore.
|
| is_empty(self)
| Is the current DataStore empty or not.
|
| Returns
| ----------
| empty : bool
| False if there are items in the DataStore
|
| pop(self, key)
|
| update(self, values)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| mutable
| Is data allowed to be altered or not.
|
| Returns
| -----------
| is_mutable : bool
| Can data be altered in the DataStore
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.Mapping:
|
| __eq__(self, other)
| Return self==value.
|
| get(self, key, default=None)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(self)
| D.items() -> a set-like object providing a view on D's items
|
| keys(self)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(self)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from collections.abc.Mapping:
|
| __reversed__ = None
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Iterable:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
class DiskCache(builtins.object)
| DiskCache(path, expire_days=30)
|
| Store results of expensive operations on disk
| with an option to expire the results. This is used
| to cache the multi-gigabyte test corpuses in
| `tests/corpus.py`
|
| Methods defined here:
|
| __init__(self, path, expire_days=30)
| Create a cache on disk for storing expensive results.
|
| Parameters
| --------------
| path : str
| A writeable location on the current file path.
| expire_days : int or float
| How old should results be considered expired.
|
| get(self, key, fetch)
| Get a key from the cache or run a calculation.
|
| Parameters
| -----------
| key : str
| Key to reference item with
| fetch : function
| If key isn't stored and recent run this
| function and store its result on disk.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class TrackedArray(numpy.ndarray)
| Subclass of numpy.ndarray that provides hash methods
| to track changes.
|
| General method is to aggressively set 'modified' flags
| on operations which might (but don't necessarily) alter
| the array, ideally we sometimes compute hashes when we
| don't need to, but we don't return wrong hashes ever.
|
| We store boolean modified flag for each hash type to
| make checks fast even for queries of different hashes.
|
| Methods
| ----------
| __hash__ : int
| Runs the fastest available hash in this order:
| `xxh3_64, xxh_64, blake2b, sha256`
|
| Method resolution order:
| TrackedArray
| numpy.ndarray
| builtins.object
|
| Methods defined here:
|
| __array_finalize__(self, obj)
| Sets a modified flag on every TrackedArray
| This flag will be set on every change as well as
| during copies and certain types of slicing.
|
| __array_wrap__(self, out_arr, context=None, *args, **kwargs)
| Return a numpy scalar if array is 0d.
| See https://github.com/numpy/numpy/issues/5819
|
| __hash__(self)
| Return a fast hash of the contents of the array.
|
| Returns
| -------------
| hash : long int
| A hash of the array contents.
|
| __iadd__(self, *args, **kwargs)
| In-place addition.
|
| The i* operations are in- place and modify the array,
| so we better catch all of them.
|
| __iand__(self, *args, **kwargs)
| Return self&=value.
|
| __idiv__(self, *args, **kwargs)
|
| __ifloordiv__(self, *args, **kwargs)
| Return self//=value.
|
| __ilshift__(self, *args, **kwargs)
| Return self<<=value.
|
| __imatmul__(self, *args, **kwargs)
| Return self@=value.
|
| __imod__(self, *args, **kwargs)
| Return self%=value.
|
| __imul__(self, *args, **kwargs)
| Return self*=value.
|
| __ior__(self, *args, **kwargs)
| Return self|=value.
|
| __ipow__(self, *args, **kwargs)
| Return self**=value.
|
| __irshift__(self, *args, **kwargs)
| Return self>>=value.
|
| __isub__(self, *args, **kwargs)
| Return self-=value.
|
| __itruediv__(self, *args, **kwargs)
| Return self/=value.
|
| __ixor__(self, *args, **kwargs)
| Return self^=value.
|
| __setitem__(self, *args, **kwargs)
| Set self[key] to value.
|
| __setslice__(self, *args, **kwargs)
|
| byteswap(self, *args, **kwargs)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| fill(self, *args, **kwargs)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| itemset(self, *args, **kwargs)
|
| partition(self, *args, **kwargs)
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array in such a way that the value of
| the element in k-th position is in the position it would be in a sorted
| array. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value will be in its
| final sorted position and all smaller elements will be moved before it
| and all equal or greater elements behind it.
| The order of all elements in the partitions is undefined.
| If provided with a sequence of kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str or list of str, optional
| When `a` is an array with fields defined, this argument specifies
| which fields to compare first, second, etc. A single field can
| be specified as a string, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| put(self, *args, **kwargs)
| a.put(indices, values, mode='raise')
|
| Set ``a.flat[n] = values[n]`` for all `n` in indices.
|
| Refer to `numpy.put` for full documentation.
|
| See Also
| --------
| numpy.put : equivalent function
|
| setflags(self, *args, **kwargs)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| sort(self, *args, **kwargs)
| a.sort(axis=-1, kind=None, order=None)
|
| Sort an array in-place. Refer to `numpy.sort` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| and 'mergesort' use timsort under the covers and, in general, the
| actual implementation will vary with datatype. The 'mergesort' option
| is retained for backwards compatibility.
|
| .. versionchanged:: 1.15.0
| The 'stable' option was added.
|
| order : str or list of str, optional
| When `a` is an array with fields defined, this argument specifies
| which fields to compare first, second, etc. A single field can
| be specified as a string, and not all fields need be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.sort : Return a sorted copy of an array.
| numpy.argsort : Indirect sort.
| numpy.lexsort : Indirect stable sort on multiple keys.
| numpy.searchsorted : Find elements in sorted array.
| numpy.partition: Partial sort.
|
| Notes
| -----
| See `numpy.sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,4], [3,1]])
| >>> a.sort(axis=1)
| >>> a
| array([[1, 4],
| [1, 3]])
| >>> a.sort(axis=0)
| >>> a
| array([[1, 3],
| [1, 4]])
|
| Use the `order` keyword to specify a field to use when sorting a
| structured array:
|
| >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| >>> a.sort(order='y')
| >>> a
| array([(b'c', 1), (b'a', 2)],
| dtype=[('x', 'S1'), ('y', '<i8')])
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| mutable
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __deepcopy__(...)
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| a.__reduce__()
|
| For pickling.
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
| a.__setstate__(state, /)
|
| For unpickling.
|
| The `state` argument must be a sequence that contains the following
| elements:
|
| Parameters
| ----------
| version : int
| optional pickle version. If omitted defaults to 0.
| shape : tuple
| dtype : data-type
| isFortran : bool
| rawdata : string or list
| a binary string with the data (or a list if 'a' is an object array)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| a.all(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if all elements evaluate to True.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.all : equivalent function
|
| any(...)
| a.any(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if any of the elements of `a` evaluate to True.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.any : equivalent function
|
| argmax(...)
| a.argmax(axis=None, out=None, *, keepdims=False)
|
| Return indices of the maximum values along the given axis.
|
| Refer to `numpy.argmax` for full documentation.
|
| See Also
| --------
| numpy.argmax : equivalent function
|
| argmin(...)
| a.argmin(axis=None, out=None, *, keepdims=False)
|
| Return indices of the minimum values along the given axis.
|
| Refer to `numpy.argmin` for detailed documentation.
|
| See Also
| --------
| numpy.argmin : equivalent function
|
| argpartition(...)
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(...)
| a.argsort(axis=-1, kind=None, order=None)
|
| Returns the indices that would sort this array.
|
| Refer to `numpy.argsort` for full documentation.
|
| See Also
| --------
| numpy.argsort : equivalent function
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| 'C' means C order, 'F' means Fortran order, 'A'
| means 'F' order if all the arrays are Fortran contiguous,
| 'C' order otherwise, and 'K' means as close to the
| order the array elements appear in memory as possible.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * 'no' means the data types should not be cast at all.
| * 'equiv' means only byte-order changes are allowed.
| * 'safe' means only casts which can preserve values are allowed.
| * 'same_kind' means only safe casts or casts within a kind,
| like float64 to float32, are allowed.
| * 'unsafe' means any data conversions may be done.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| compress(...)
| a.compress(condition, axis=None, out=None)
|
| Return selected slices of this array along given axis.
|
| Refer to `numpy.compress` for full documentation.
|
| See Also
| --------
| numpy.compress : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| copy(...)
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| cumprod(...)
| a.cumprod(axis=None, dtype=None, out=None)
|
| Return the cumulative product of the elements along the given axis.
|
| Refer to `numpy.cumprod` for full documentation.
|
| See Also
| --------
| numpy.cumprod : equivalent function
|
| cumsum(...)
| a.cumsum(axis=None, dtype=None, out=None)
|
| Return the cumulative sum of the elements along the given axis.
|
| Refer to `numpy.cumsum` for full documentation.
|
| See Also
| --------
| numpy.cumsum : equivalent function
|
| diagonal(...)
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(...)
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| flatten(...)
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| max(...)
| a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the maximum along a given axis.
|
| Refer to `numpy.amax` for full documentation.
|
| See Also
| --------
| numpy.amax : equivalent function
|
| mean(...)
| a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
|
| Returns the average of the array elements along given axis.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.mean : equivalent function
|
| min(...)
| a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the minimum along a given axis.
|
| Refer to `numpy.amin` for full documentation.
|
| See Also
| --------
| numpy.amin : equivalent function
|
| nonzero(...)
| a.nonzero()
|
| Return the indices of the elements that are non-zero.
|
| Refer to `numpy.nonzero` for full documentation.
|
| See Also
| --------
| numpy.nonzero : equivalent function
|
| prod(...)
| a.prod(axis=None, dtype=None, out=None, keepdims=False,
| initial=1, where=True)
|
| Return the product of the array elements over the given axis
|
| Refer to `numpy.prod` for full documentation.
|
| See Also
| --------
| numpy.prod : equivalent function
|
| ravel(...)
| a.ravel([order])
|
| Return a flattened array.
|
| Refer to `numpy.ravel` for full documentation.
|
| See Also
| --------
| numpy.ravel : equivalent function
|
| ndarray.flat : a flat iterator on the array.
|
| repeat(...)
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(...)
| a.reshape(shape, /, *, order='C', copy=None)
|
| Returns an array containing the same data with a new shape.
|
| Refer to `numpy.reshape` for full documentation.
|
| See Also
| --------
| numpy.reshape : equivalent function
|
| Notes
| -----
| Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| the elements of the shape parameter to be passed in as separate arguments.
| For example, ``a.reshape(10, 11)`` is equivalent to
| ``a.reshape((10, 11))``.
|
| resize(...)
| a.resize(new_shape, refcheck=True)
|
| Change shape and size of array in-place.
|
| Parameters
| ----------
| new_shape : tuple of ints, or `n` ints
| Shape of resized array.
| refcheck : bool, optional
| If False, reference count will not be checked. Default is True.
|
| Returns
| -------
| None
|
| Raises
| ------
| ValueError
| If `a` does not own its own data or references or views to it exist,
| and the data memory must be changed.
| PyPy only: will always raise if the data memory must be changed, since
| there is no reliable way to determine if references or views to it
| exist.
|
| SystemError
| If the `order` keyword argument is specified. This behaviour is a
| bug in NumPy.
|
| See Also
| --------
| resize : Return a new array with the specified shape.
|
| Notes
| -----
| This reallocates space for the data area if necessary.
|
| Only contiguous arrays (data elements consecutive in memory) can be
| resized.
|
| The purpose of the reference count check is to make sure you
| do not use this array as a buffer for another Python object and then
| reallocate the memory. However, reference counts can increase in
| other ways so if you are sure that you have not shared the memory
| for this array with another Python object, then you may safely set
| `refcheck` to False.
|
| Examples
| --------
| Shrinking an array: array is flattened (in the order that the data are
| stored in memory), resized, and reshaped:
|
| >>> import numpy as np
|
| >>> a = np.array([[0, 1], [2, 3]], order='C')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [1]])
|
| >>> a = np.array([[0, 1], [2, 3]], order='F')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [2]])
|
| Enlarging an array: as above, but missing entries are filled with zeros:
|
| >>> b = np.array([[0, 1], [2, 3]])
| >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| >>> b
| array([[0, 1, 2],
| [3, 0, 0]])
|
| Referencing an array prevents resizing...
|
| >>> c = a
| >>> a.resize((1, 1))
| Traceback (most recent call last):
| ...
| ValueError: cannot resize an array that references or is referenced ...
|
| Unless `refcheck` is False:
|
| >>> a.resize((1, 1), refcheck=False)
| >>> a
| array([[0]])
| >>> c
| array([[0]])
|
| round(...)
| a.round(decimals=0, out=None)
|
| Return `a` with each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.around : equivalent function
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| squeeze(...)
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(...)
| a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the standard deviation of the array elements along given axis.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.std : equivalent function
|
| sum(...)
| a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
|
| Return the sum of the array elements over the given axis.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.sum : equivalent function
|
| swapaxes(...)
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(...)
| a.take(indices, axis=None, out=None, mode='raise')
|
| Return an array formed from the elements of `a` at the given indices.
|
| Refer to `numpy.take` for full documentation.
|
| See Also
| --------
| numpy.take : equivalent function
|
| to_device(...)
|
| tobytes(...)
| a.tobytes(order='C')
|
| Construct Python bytes containing the raw data bytes in the array.
|
| Constructs Python bytes showing a copy of the raw contents of
| data memory. The bytes object is produced in C-order by default.
| This behavior is controlled by the ``order`` parameter.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| order : {'C', 'F', 'A'}, optional
| Controls the memory layout of the bytes object. 'C' means C-order,
| 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| Fortran contiguous, 'C' otherwise. Default is 'C'.
|
| Returns
| -------
| s : bytes
| Python bytes exhibiting a copy of `a`'s raw data.
|
| See also
| --------
| frombuffer
| Inverse of this operation, construct a 1-dimensional array from Python
| bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| >>> x.tobytes()
| b'\x00\x00\x01\x00\x02\x00\x03\x00'
| >>> x.tobytes('C') == x.tobytes()
| True
| >>> x.tobytes('F')
| b'\x00\x00\x02\x00\x01\x00\x03\x00'
|
| tofile(...)
| a.tofile(fid, sep="", format="%s")
|
| Write array to a file as text or binary (default).
|
| Data is always written in 'C' order, independent of the order of `a`.
| The data produced by this method can be recovered using the function
| fromfile().
|
| Parameters
| ----------
| fid : file or str or Path
| An open file object, or a string containing a filename.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| sep : str
| Separator between array items for text output.
| If "" (empty), a binary file is written, equivalent to
| ``file.write(a.tobytes())``.
| format : str
| Format string for text file output.
| Each entry in the array is formatted to text by first converting
| it to the closest Python type, and then using "format" % item.
|
| Notes
| -----
| This is a convenience function for quick storage of array data.
| Information on endianness and precision is lost, so this method is not a
| good choice for files intended to archive data or transport data between
| machines with different endianness. Some of these problems can be overcome
| by outputting the data as text files, at the expense of speed and file
| size.
|
| When fid is a file object, array contents are directly written to the
| file, bypassing the file object's ``write`` method. As a result, tofile
| cannot be used with files objects supporting compression (e.g., GzipFile)
| or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
|
| tolist(...)
| a.tolist()
|
| Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
|
| Return a copy of the array data as a (nested) Python list.
| Data items are converted to the nearest compatible builtin Python type, via
| the `~numpy.ndarray.item` function.
|
| If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
| not be a list at all, but a simple Python scalar.
|
| Parameters
| ----------
| none
|
| Returns
| -------
| y : object, or list of object, or list of list of object, or ...
| The possibly nested list of array elements.
|
| Notes
| -----
| The array may be recreated via ``a = np.array(a.tolist())``, although this
| may sometimes lose precision.
|
| Examples
| --------
| For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
| except that ``tolist`` changes numpy scalars to Python scalars:
|
| >>> import numpy as np
| >>> a = np.uint32([1, 2])
| >>> a_list = list(a)
| >>> a_list
| [1, 2]
| >>> type(a_list[0])
| <class 'numpy.uint32'>
| >>> a_tolist = a.tolist()
| >>> a_tolist
| [1, 2]
| >>> type(a_tolist[0])
| <class 'int'>
|
| Additionally, for a 2D array, ``tolist`` applies recursively:
|
| >>> a = np.array([[1, 2], [3, 4]])
| >>> list(a)
| [array([1, 2]), array([3, 4])]
| >>> a.tolist()
| [[1, 2], [3, 4]]
|
| The base case for this recursion is a 0D array:
|
| >>> a = np.array(1)
| >>> list(a)
| Traceback (most recent call last):
| ...
| TypeError: iteration over a 0-d array
| >>> a.tolist()
| 1
|
| tostring(...)
| a.tostring(order='C')
|
| A compatibility alias for `~ndarray.tobytes`, with exactly the same
| behavior.
|
| Despite its name, it returns :class:`bytes` not :class:`str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(...)
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(...)
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| var(...)
| a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the variance of the array elements, along given axis.
|
| Refer to `numpy.var` for full documentation.
|
| See Also
| --------
| numpy.var : equivalent function
|
| view(...)
| a.view([dtype][, type])
|
| New view of array with the same data.
|
| .. note::
| Passing None for ``dtype`` is different from omitting the parameter,
| since the former invokes ``dtype(None)`` which is an alias for
| ``dtype('float64')``.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| Omitting it results in the view having the same data-type as `a`.
| This argument can also be specified as an ndarray sub-class, which
| then specifies the type of the returned object (this is equivalent to
| setting the ``type`` parameter).
| type : Python type, optional
| Type of the returned view, e.g., ndarray or matrix. Again, omission
| of the parameter results in type preservation.
|
| Notes
| -----
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a regular
| array to a structured array), then the last axis of ``a`` must be
| contiguous. This axis will be resized in the result.
|
| .. versionchanged:: 1.23.0
| Only the last axis needs to be contiguous. Previously, the entire array
| had to be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
|
| Viewing array data using a different type and dtype:
|
| >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| >>> y = x.view(dtype=nonneg, type=np.recarray)
| >>> x["a"]
| array([-1], dtype=int8)
| >>> y.a
| array([255], dtype=uint8)
|
| Creating a view on a structured array so it can be used in calculations
|
| >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| >>> xv
| array([[1, 2],
| [3, 4]], dtype=int8)
| >>> xv.mean(0)
| array([2., 3.])
|
| Making changes to the view changes the underlying array
|
| >>> xv[0,1] = 20
| >>> x
| array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
|
| Using a view to convert an array to a recarray:
|
| >>> z = x.view(np.recarray)
| >>> z.a
| array([1, 3], dtype=int8)
|
| Views share data:
|
| >>> x[0] = (9, 10)
| >>> z[0]
| np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
|
| Views that change the dtype size (bytes per entry) should normally be
| avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
|
| >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| >>> y = x[:, ::2]
| >>> y
| array([[1, 3],
| [4, 6]], dtype=int16)
| >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| Traceback (most recent call last):
| ...
| ValueError: To change to a dtype of a different size, the last axis must be contiguous
| >>> z = y.copy()
| >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| array([[(1, 3)],
| [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
|
| However, views that change dtype are totally fine for arrays with a
| contiguous last axis, even if the rest of the axes are not C-contiguous:
|
| >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| >>> x.transpose(1, 0, 2).view(np.int16)
| array([[[ 256, 770],
| [3340, 3854]],
| <BLANKLINE>
| [[1284, 1798],
| [4368, 4882]],
| <BLANKLINE>
| [[2312, 2826],
| [5396, 5910]]], dtype=int16)
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Static methods inherited from numpy.ndarray:
|
| __new__(*args, **kwargs) class method of numpy.ndarray
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ndarray:
|
| T
| View of the transposed array.
|
| Same as ``self.transpose()``.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.T
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.T
| array([1, 2, 3, 4])
|
| See Also
| --------
| transpose
|
| __array_interface__
| Array protocol: Python side.
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| data
| Python buffer object pointing to the start of the array's data.
|
| device
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| flat
| A 1-D iterator over the array.
|
| This is a `numpy.flatiter` instance, which acts similarly to, but is not
| a subclass of, Python's built-in iterator object.
|
| See Also
| --------
| flatten : Return a copy of the array collapsed into one dimension.
|
| flatiter
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(1, 7).reshape(2, 3)
| >>> x
| array([[1, 2, 3],
| [4, 5, 6]])
| >>> x.flat[3]
| 4
| >>> x.T
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> x.T.flat[3]
| 5
| >>> type(x.flat)
| <class 'numpy.flatiter'>
|
| An assignment example:
|
| >>> x.flat = 3; x
| array([[3, 3, 3],
| [3, 3, 3]])
| >>> x.flat[[1,4]] = 1; x
| array([[3, 1, 3],
| [3, 1, 3]])
|
| imag
| The imaginary part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.imag
| array([ 0. , 0.70710678])
| >>> x.imag.dtype
| dtype('float64')
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| mT
| View of the matrix transposed array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.mT
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.arange(8).reshape((2, 2, 2))
| >>> a
| array([[[0, 1],
| [2, 3]],
| <BLANKLINE>
| [[4, 5],
| [6, 7]]])
| >>> a.mT
| array([[[0, 2],
| [1, 3]],
| <BLANKLINE>
| [[4, 6],
| [5, 7]]])
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| ptp
|
| real
| The real part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.real
| array([ 1. , 0.70710678])
| >>> x.real.dtype
| dtype('float64')
|
| See Also
| --------
| numpy.real : equivalent function
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
FUNCTIONS
cache_decorator(function)
A decorator for class methods, replaces @property
but will store and retrieve function return values
in object cache.
Parameters
------------
function : method
This is used as a decorator:
```
@cache_decorator
def foo(self, things):
return 'happy days'
```
hash_fallback(item)
hash_fast = xxh3_64_intdigest(...)
xxh3_64_intdigest
sha256(item) -> int
tracked_array(array, dtype=None)
Properly subclass a numpy ndarray to track changes.
Avoids some pitfalls of subclassing by forcing contiguous
arrays and does a view into a TrackedArray.
Parameters
------------
array : array- like object
To be turned into a TrackedArray
dtype : np.dtype
Which dtype to use for the array
Returns
------------
tracked : TrackedArray
Contains input array data.
DATA
log = <Logger trimesh.util (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\caching.py
trimesh.collision
Python Library Documentation: module trimesh.collision in trimesh
NAME
trimesh.collision
CLASSES
builtins.object
CollisionManager
ContactData
DistanceData
class CollisionManager(builtins.object)
| A mesh-mesh collision manager.
|
| Methods defined here:
|
| __init__(self)
| Initialize a mesh-mesh collision manager.
|
| add_object(self, name, mesh, transform=None)
| Add an object to the collision manager.
|
| If an object with the given name is already in the manager,
| replace it.
|
| Parameters
| ----------
| name : str
| An identifier for the object
| mesh : Trimesh object
| The geometry of the collision object
| transform : (4,4) float
| Homogeneous transform matrix for the object
|
| in_collision_internal(self, return_names=False, return_data=False)
| Check if any pair of objects in the manager collide with one another.
|
| Parameters
| ----------
| return_names : bool
| If true, a set is returned containing the names
| of all pairs of objects in collision.
| return_data : bool
| If true, a list of ContactData is returned as well
|
| Returns
| -------
| is_collision : bool
| True if a collision occurred between any pair of objects
| and False otherwise
| names : set of 2-tup
| The set of pairwise collisions. Each tuple
| contains two names in alphabetical order indicating
| that the two corresponding objects are in collision.
| contacts : list of ContactData
| All contacts detected
|
| in_collision_other(self, other_manager, return_names=False, return_data=False)
| Check if any object from this manager collides with any object
| from another manager.
|
| Parameters
| -------------------
| other_manager : CollisionManager
| Another collision manager object
| return_names : bool
| If true, a set is returned containing the names
| of all pairs of objects in collision.
| return_data : bool
| If true, a list of ContactData is returned as well
|
| Returns
| -------------
| is_collision : bool
| True if a collision occurred between any pair of objects
| and False otherwise
| names : set of 2-tup
| The set of pairwise collisions. Each tuple
| contains two names (first from this manager,
| second from the other_manager) indicating
| that the two corresponding objects are in collision.
| contacts : list of ContactData
| All contacts detected
|
| in_collision_single(self, mesh, transform=None, return_names=False, return_data=False)
| Check a single object for collisions against all objects in the
| manager.
|
| Parameters
| ----------
| mesh : Trimesh object
| The geometry of the collision object
| transform : (4,4) float
| Homogeneous transform matrix
| return_names : bool
| If true, a set is returned containing the names
| of all objects in collision with the object
| return_data : bool
| If true, a list of ContactData is returned as well
|
| Returns
| ------------
| is_collision : bool
| True if a collision occurs and False otherwise
| names : set of str
| [OPTIONAL] The set of names of objects that collided with the
| provided one
| contacts : list of ContactData
| [OPTIONAL] All contacts detected
|
| min_distance_internal(self, name=None, return_names=False, return_data=False)
| Get the minimum distance between objects in the manager.
|
| If name is provided, computes the minimum distance between the
| specified object and any other object in the manager.
| If name is None, computes the minimum distance between any pair
| of objects in the manager.
|
| Parameters
| -------------
| name : str or None
| If provided, the identifier for the object already in the manager
| to compute distances from. If None, computes distances between
| all pairs of objects.
| return_names : bool
| If true, a 2-tuple is returned containing the names
| of the closest objects.
| return_data : bool
| If true, a DistanceData object is returned as well
|
| Returns
| -----------
| distance : float
| Min distance between objects
| names : (2,) str
| The names of the closest objects
| data : DistanceData
| Extra data about the distance query
|
| min_distance_other(self, other_manager, return_names=False, return_data=False)
| Get the minimum distance between any pair of objects,
| one in each manager.
|
| Parameters
| ----------
| other_manager : CollisionManager
| Another collision manager object
| return_names : bool
| If true, a 2-tuple is returned containing
| the names of the closest objects.
| return_data : bool
| If true, a DistanceData object is returned as well
|
| Returns
| -----------
| distance : float
| The min distance between a pair of objects,
| one from each manager.
| names : 2-tup of str
| A 2-tuple containing two names (first from this manager,
| second from the other_manager) indicating
| the two closest objects.
| data : DistanceData
| Extra data about the distance query
|
| min_distance_single(self, mesh, transform=None, return_name=False, return_data=False)
| Get the minimum distance between a single object and any
| object in the manager.
|
| Parameters
| ---------------
| mesh : Trimesh object
| The geometry of the collision object
| transform : (4,4) float
| Homogeneous transform matrix for the object
| return_names : bool
| If true, return name of the closest object
| return_data : bool
| If true, a DistanceData object is returned as well
|
| Returns
| -------------
| distance : float
| Min distance between mesh and any object in the manager
| name : str
| The name of the object in the manager that was closest
| data : DistanceData
| Extra data about the distance query
|
| remove_object(self, name)
| Delete an object from the collision manager.
|
| Parameters
| ----------
| name : str
| The identifier for the object
|
| set_transform(self, name, transform)
| Set the transform for one of the manager's objects.
| This replaces the prior transform.
|
| Parameters
| ----------
| name : str
| An identifier for the object already in the manager
| transform : (4,4) float
| A new homogeneous transform matrix for the object
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ContactData(builtins.object)
| ContactData(names, contact)
|
| Data structure for holding information about a collision contact.
|
| Methods defined here:
|
| __init__(self, names, contact)
| Initialize a ContactData.
|
| Parameters
| ----------
| names : list of str
| The names of the two objects in order.
| contact : fcl.Contact
| The contact in question.
|
| index(self, name)
| Returns the index of the face in contact for the mesh with
| the given name.
|
| Parameters
| ----------
| name : str
| The name of the target object.
|
| Returns
| -------
| index : int
| The index of the face in collision
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| depth
| The penetration depth of the 3D point of intersection for this contact.
|
| Returns
| -------
| depth : float
| The penetration depth.
|
| normal
| The 3D intersection normal for this contact.
|
| Returns
| -------
| normal : (3,) float
| The intersection normal.
|
| point
| The 3D point of intersection for this contact.
|
| Returns
| -------
| point : (3,) float
| The intersection point.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class DistanceData(builtins.object)
| DistanceData(names, result)
|
| Data structure for holding information about a distance query.
|
| Methods defined here:
|
| __init__(self, names, result)
| Initialize a DistanceData.
|
| Parameters
| ----------
| names : list of str
| The names of the two objects in order.
| contact : fcl.DistanceResult
| The distance query result.
|
| index(self, name)
| Returns the index of the closest face for the mesh with
| the given name.
|
| Parameters
| ----------
| name : str
| The name of the target object.
|
| Returns
| -------
| index : int
| The index of the face in collisoin.
|
| point(self, name)
| The 3D point of closest distance on the mesh with the given name.
|
| Parameters
| ----------
| name : str
| The name of the target object.
|
| Returns
| -------
| point : (3,) float
| The closest point.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| distance
| Returns the distance between the two objects.
|
| Returns
| -------
| distance : float
| The euclidean distance between the objects.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
mesh_to_BVH(mesh)
Create a BVHModel object from a Trimesh object
Parameters
-----------
mesh : Trimesh
Input geometry
Returns
------------
bvh : fcl.BVHModel
BVH of input geometry
mesh_to_convex(mesh)
Create a Convex object from a Trimesh object
Parameters
-----------
mesh : Trimesh
Input geometry
Returns
------------
convex : fcl.Convex
Convex of input geometry
scene_to_collision(scene)
Create collision objects from a trimesh.Scene object.
Parameters
------------
scene : trimesh.Scene
Scene to create collision objects for
Returns
------------
manager : CollisionManager
CollisionManager for objects in scene
objects: {node name: CollisionObject}
Collision objects for nodes in scene
DATA
fcl = None
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\collision.py
trimesh.comparison
Python Library Documentation: module trimesh.comparison in trimesh
NAME
trimesh.comparison
DESCRIPTION
comparison.py
----------------
Provide methods for quickly hashing and comparing meshes.
FUNCTIONS
identifier_hash(identifier)
Hash an identifier array in a way that is hand-tuned to be
somewhat robust to likely changes.
Parameters
------------
identifier : (n,) float
Vector of properties
Returns
----------
hash : (64,) str
A SHA256 of the identifier vector at hand-tuned precision.
identifier_simple(mesh)
Return a basic identifier for a mesh consisting of
properties that have been hand tuned to be somewhat
robust to rigid transformations and different
tessellations.
Parameters
------------
mesh : trimesh.Trimesh
Source geometry
Returns
----------
identifier : (7,) float
Identifying values of the mesh
sha256 = openssl_sha256(string=b'', *, usedforsecurity=True)
Returns a sha256 hash object; optionally initialized with a string
DATA
id_sigfig = array([ 5, 10, 5, 2, 2, 3, 1])
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\comparison.py
trimesh.constants
Python Library Documentation: module trimesh.constants in trimesh
NAME
trimesh.constants
CLASSES
builtins.object
ResolutionPath
ToleranceMesh
TolerancePath
class ResolutionPath(builtins.object)
| ResolutionPath(seg_frac: float = 0.05, seg_angle: float = 0.08, max_sections: float = 500.0, min_sections: float = 20.0, export: str = '0.10f') -> None
|
| res.seg_frac : float
| When discretizing curves, what percentage of the drawing
| scale should we aim to make a single segment
| res.seg_angle : float
| When discretizing curves, what angle should a section span
| res.max_sections : int
| When discretizing splines, what is the maximum number
| of segments per control point
| res.min_sections : int
| When discretizing splines, what is the minimum number
| of segments per control point
| res.export : str
| Format string to use when exporting floating point vertices
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, seg_frac: float = 0.05, seg_angle: float = 0.08, max_sections: float = 500.0, min_sections: float = 20.0, export: str = '0.10f') -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'export': <class 'str'>, 'max_sections': <class 'fl...
|
| __dataclass_fields__ = {'export': Field(name='export',type=<class 'str...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('seg_frac', 'seg_angle', 'max_sections', 'min_sectio...
|
| export = '0.10f'
|
| max_sections = 500.0
|
| min_sections = 20.0
|
| seg_angle = 0.08
|
| seg_frac = 0.05
class ToleranceMesh(builtins.object)
| ToleranceMesh(zero: float = np.float64(1e-13), merge: float = 1e-08, planar: float = 1e-05, facet_threshold: int = 5000, strict: bool = False) -> None
|
| ToleranceMesh objects hold tolerance information about meshes.
|
| Parameters
| ----------------
| tol.zero : float
| Floating point numbers smaller than this are considered zero
| tol.merge : float
| When merging vertices, consider vertices closer than this
| to be the same vertex. Here we use the same value (1e-8)
| as SolidWorks uses, according to their documentation.
| tol.planar : float
| The maximum distance from a plane a point can be and
| still be considered to be on the plane
| tol.facet_threshold : float
| Threshold for two facets to be considered coplanar
| tol.strict : bool
| If True, run additional in- process checks (slower)
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, zero: float = np.float64(1e-13), merge: float = 1e-08, planar: float = 1e-05, facet_threshold: int = 5000, strict: bool = False) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'facet_threshold': <class 'int'>, 'merge': <class '...
|
| __dataclass_fields__ = {'facet_threshold': Field(name='facet_threshold...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('zero', 'merge', 'planar', 'facet_threshold', 'stric...
|
| facet_threshold = 5000
|
| merge = 1e-08
|
| planar = 1e-05
|
| strict = False
|
| zero = np.float64(1e-13)
class TolerancePath(builtins.object)
| TolerancePath(zero: float = 1e-12, merge: float = 1e-05, planar: float = 1e-05, seg_frac: float = 0.125, seg_angle: float = 0.8726646259971648, seg_angle_min: float = 0.017453292519943295, seg_angle_frac: float = 0.5, aspect_frac: float = 0.1, radius_frac: float = 0.02, radius_min: float = 0.0001, radius_max: float = 50.0, tangent: float = 0.3490658503988659, strict: bool = False) -> None
|
| TolerancePath objects contain tolerance information used in
| Path objects.
|
| Parameters
| ---------------
| tol.zero : float
| Floating point numbers smaller than this are considered zero
| tol.merge : float
| When merging vertices, consider vertices closer than this
| to be the same vertex. Here we use the same value (1e-8)
| as SolidWorks uses, according to their documentation.
| tol.planar : float
| The maximum distance from a plane a point can be and
| still be considered to be on the plane
| tol.seg_frac : float
| When simplifying line segments what percentage of the drawing
| scale can a segment be and have a curve fitted
| tol.seg_angle : float
| When simplifying line segments to arcs, what angle
| can a segment span to be acceptable.
| tol.aspect_frac : float
| When simplifying line segments to closed arcs (circles)
| what percentage can the aspect ratio differfrom 1:1
| before escaping the fit early
| tol.radius_frac : float
| When simplifying line segments to arcs, what percentage
| of the fit radius can vertices deviate to be acceptable
| tol.radius_min :
| When simplifying line segments to arcs, what is the minimum
| radius multiplied by document scale for an acceptable fit
| tol.radius_max :
| When simplifying line segments to arcs, what is the maximum
| radius multiplied by document scale for an acceptable fit
| tol.tangent :
| When simplifying line segments to curves, what is the maximum
| angle the end sections can deviate from tangent that is
| acceptable.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, zero: float = 1e-12, merge: float = 1e-05, planar: float = 1e-05, seg_frac: float = 0.125, seg_angle: float = 0.8726646259971648, seg_angle_min: float = 0.017453292519943295, seg_angle_frac: float = 0.5, aspect_frac: float = 0.1, radius_frac: float = 0.02, radius_min: float = 0.0001, radius_max: float = 50.0, tangent: float = 0.3490658503988659, strict: bool = False) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| merge_digits
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'aspect_frac': <class 'float'>, 'merge': <class 'fl...
|
| __dataclass_fields__ = {'aspect_frac': Field(name='aspect_frac',type=<...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('zero', 'merge', 'planar', 'seg_frac', 'seg_angle', ...
|
| aspect_frac = 0.1
|
| merge = 1e-05
|
| planar = 1e-05
|
| radius_frac = 0.02
|
| radius_max = 50.0
|
| radius_min = 0.0001
|
| seg_angle = 0.8726646259971648
|
| seg_angle_frac = 0.5
|
| seg_angle_min = 0.017453292519943295
|
| seg_frac = 0.125
|
| strict = False
|
| tangent = 0.3490658503988659
|
| zero = 1e-12
FUNCTIONS
log_time(method)
A decorator for methods which will time the method
and then emit a log.debug message with the method name
and how long it took to execute.
now = time(...)
time() -> floating-point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
DATA
log = <Logger trimesh.util (WARNING)>
res_path = ResolutionPath(seg_frac=0.05, seg_angle=0.08, max_sections=...
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
tol_path = TolerancePath(zero=1e-12, merge=1e-05, planar=1e...x=50.0, ...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\constants.py
trimesh.convex
Python Library Documentation: module trimesh.convex in trimesh
NAME
trimesh.convex - convex.py
DESCRIPTION
Deal with creating and checking convex objects in 2, 3 and N dimensions.
Convex is defined as:
1) "Convex, meaning "curving out" or "extending outward" (compare to concave)
2) having an outline or surface curved like the exterior of a circle or sphere.
3) (of a polygon) having only interior angles measuring less than 180
CLASSES
builtins.object
QhullOptions
class QhullOptions(builtins.object)
| QhullOptions(Qa: bool = False, Qc: bool = False, Qi: bool = False, QJ: bool = False, Qt: bool = False, Qu: bool = False, Qw: bool = False, Qbb: bool = False, Qs: bool = False, Qv: bool = False, Qx: bool = False, Qz: bool = False, QbB: bool = False, QR0: bool = False, Qg: bool = False, Pp: bool = False) -> None
|
| A helper class for constructing correct Qhull option strings.
| More details available at: http://www.qhull.org/html/qh-quick.htm#options
|
| Currently only includes the boolean flag options, which is most of them.
|
| Parameters
| -----------
| Qa
| Allow input with fewer or more points than coordinates
| Qc
| Keep coplanar points with nearest facet
| Qi
| Keep interior points with nearest facet.
| QJ
| Joggled input to avoid precision problems
| Qt
| Triangulated output.
| Qu
| Compute upper hull for furthest-site Delaunay triangulation
| Qw
| Allow warnings about Qhull options
| Qbb
| Scale last coordinate to [0,m] for Delaunay
| Qs
| Search all points for the initial simplex
| Qv
| Test vertex neighbors for convexity
| Qx
| Exact pre-merges (allows coplanar facets)
| Qz
| Add a point-at-infinity for Delaunay triangulations
| QbB
| Scale input to fit the unit cube
| QR0
| Random rotation (n=seed, n=0 time, n=-1 time/no rotate)
| Qg
| only build good facets (needs 'QGn', 'QVn', or 'Pdk')
| Pp
| Do not print statistics about precision problems and remove
| some of the warnings including the narrow hull warning.
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, Qa: bool = False, Qc: bool = False, Qi: bool = False, QJ: bool = False, Qt: bool = False, Qu: bool = False, Qw: bool = False, Qbb: bool = False, Qs: bool = False, Qv: bool = False, Qx: bool = False, Qz: bool = False, QbB: bool = False, QR0: bool = False, Qg: bool = False, Pp: bool = False) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __str__(self) -> str
| Construct the `qhull_options` string used by `scipy.spatial`
| objects and functions.
|
| Returns
| ----------
| qhull_options
| Can be passed to `scipy.spatial.[ConvexHull,Delaunay,Voronoi]`
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| Pp = False
|
| QJ = False
|
| QR0 = False
|
| Qa = False
|
| QbB = False
|
| Qbb = False
|
| Qc = False
|
| Qg = False
|
| Qi = False
|
| Qs = False
|
| Qt = False
|
| Qu = False
|
| Qv = False
|
| Qw = False
|
| Qx = False
|
| Qz = False
|
| __annotations__ = {'Pp': <class 'bool'>, 'QJ': <class 'bool'>, 'QR0': ...
|
| __dataclass_fields__ = {'Pp': Field(name='Pp',type=<class 'bool'>,defa...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('Qa', 'Qc', 'Qi', 'QJ', 'Qt', 'Qu', 'Qw', 'Qbb', 'Qs...
FUNCTIONS
adjacency_projections(mesh)
Test if a mesh is convex by projecting the vertices of
a triangle onto the normal of its adjacent face.
Parameters
----------
mesh : Trimesh
Input geometry
Returns
----------
projection : (len(mesh.face_adjacency),) float
Distance of projection of adjacent vertex onto plane
convex_hull(obj: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], qhull_options: Union[trimesh.convex.QhullOptions, str, NoneType] = QhullOptions(Qa=False, Qc=False, Qi=False, QJ=False, Qt=True, Qu=False, Qw=False, Qbb=False, Qs=False, Qv=False, Qx=False, Qz=False, QbB=True, QR0=False, Qg=False, Pp=True), repair: bool = True) -> 'trimesh.Trimesh'
Get a new Trimesh object representing the convex hull of the
current mesh attempting to return a watertight mesh with correct
normals.
Arguments
--------
obj
Mesh or `(n, 3)` points.
qhull_options
Options to pass to qhull.
Returns
--------
convex
Mesh of convex hull.
hull_points(obj, qhull_options='QbB Pp')
Try to extract a convex set of points from multiple input formats.
Details on qhull options:
http://www.qhull.org/html/qh-quick.htm#options
Parameters
---------
obj: Trimesh object
(n,d) points
(m,) Trimesh objects
Returns
--------
points: (o,d) convex set of points
is_convex(mesh)
Check if a mesh is convex.
Parameters
-----------
mesh : Trimesh
Input geometry
Returns
-----------
convex : bool
Was passed mesh convex or not
DATA
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
QHULL_DEFAULT = QhullOptions(Qa=False, Qc=False, Qi=False, QJ=Fa...Qz=...
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\convex.py
trimesh.creation
Python Library Documentation: module trimesh.creation in trimesh
NAME
trimesh.creation
DESCRIPTION
creation.py
--------------
Create meshes from primitives, or with operations.
FUNCTIONS
annulus(r_min: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], r_max: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None, sections: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, segment: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs)
Create a mesh of an annular cylinder along Z centered at the origin.
Parameters
----------
r_min : float
The inner radius of the annular cylinder
r_max : float
The outer radius of the annular cylinder
height : float
The height of the annular cylinder
sections : int or None
How many pie wedges should the annular cylinder have
transform : (4, 4) float or None
Transform to apply to move result from the origin
segment : None or (2, 3) float
Override transform and height with a line segment
**kwargs:
passed to Trimesh to create annulus
Returns
----------
annulus : trimesh.Trimesh
Mesh of annular cylinder
axis(origin_size: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 0.04, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, origin_color: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, axis_radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None, axis_length: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
Parameters
----------
origin_size : float
Radius of sphere that represents the origin
transform : (4, 4) float
Transformation matrix
origin_color : (3,) float or int, uint8 or float
Color of the origin
axis_radius : float
Radius of cylinder that represents x, y, z axis
axis_length: float
Length of cylinder that represents x, y, z axis
Returns
-------
marker : trimesh.Trimesh
Mesh geometry of axis indicators
box(extents: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, bounds: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs)
Return a cuboid.
Parameters
------------
extents : (3,) float
Edge lengths
transform: (4, 4) float
Transformation matrix
bounds : None or (2, 3) float
Corners of AABB, overrides extents and transform.
**kwargs:
passed to Trimesh to create box
Returns
------------
geometry : trimesh.Trimesh
Mesh of a cuboid
camera_marker(camera, marker_height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 0.4, origin_size: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Create a visual marker for a camera object, including an axis and FOV.
Parameters
---------------
camera : trimesh.scene.Camera
Camera object with FOV and transform defined
marker_height : float
How far along the camera Z should FOV indicators be
origin_size : float
Sphere radius of the origin (default: marker_height / 10.0)
Returns
------------
meshes : list
Contains Trimesh and Path3D objects which can be visualized
capsule(height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, count: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> trimesh.base.Trimesh
Create a mesh of a capsule, or a cylinder with hemispheric ends.
Parameters
----------
height : float
Center to center distance of two spheres
radius : float
Radius of the cylinder and hemispheres
count : (2,) int
Number of sections on latitude and longitude
transform : None or (4, 4) float
Transform to apply to mesh after construction
Returns
----------
capsule : trimesh.Trimesh
Capsule geometry with:
- cylinder axis is along Z
- one hemisphere is centered at the origin
- other hemisphere is centered along the Z axis at height
cone(radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], sections: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> trimesh.base.Trimesh
Create a mesh of a cone along Z centered at the origin.
Parameters
----------
radius : float
The radius of the cone at the widest part.
height : float
The height of the cone.
sections : int or None
How many pie wedges per revolution
transform : (4, 4) float or None
Transform to apply after creation
**kwargs : dict
Passed to Trimesh constructor
Returns
----------
cone: trimesh.Trimesh
Resulting mesh of a cone
cylinder(radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None, sections: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, segment: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs)
Create a mesh of a cylinder along Z centered at the origin.
Parameters
----------
radius : float
The radius of the cylinder
height : float or None
The height of the cylinder, or None if `segment` has been passed.
sections : int or None
How many pie wedges should the cylinder have
segment : (2, 3) float
Endpoints of axis, overrides transform and height
transform : None or (4, 4) float
Transform to apply to mesh after construction
**kwargs:
passed to Trimesh to create cylinder
Returns
----------
cylinder: trimesh.Trimesh
Resulting mesh of a cylinder
extrude_polygon(polygon: 'Polygon', height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, mid_plane: bool = False, **kwargs) -> trimesh.base.Trimesh
Extrude a 2D shapely polygon into a 3D mesh
Parameters
----------
polygon : shapely.geometry.Polygon
2D geometry to extrude
height : float
Distance to extrude polygon along Z
transform : None or (4, 4) float
Transform to apply to mesh after construction
triangle_args : str or None
Passed to triangle
**kwargs : dict
Passed to `triangulate_polygon`
Returns
----------
mesh : trimesh.Trimesh
Resulting extrusion as watertight body
extrude_triangulation(vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> trimesh.base.Trimesh
Extrude a 2D triangulation into a watertight mesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to extrude triangulation
transform : None or (4, 4) float
Transform to apply to mesh after construction
**kwargs : dict
Passed to Trimesh constructor
Returns
---------
mesh : trimesh.Trimesh
Mesh created from extrusion
icosahedron(**kwargs) -> trimesh.base.Trimesh
Create an icosahedron, one of the platonic solids which is has 20 faces.
Parameters
------------
kwargs : dict
Passed through to `Trimesh` constructor.
Returns
-------------
ico : trimesh.Trimesh
Icosahederon centered at the origin.
icosphere(subdivisions: Union[int, numpy.integer, numpy.unsignedinteger] = 3, radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, **kwargs)
Create an icosphere centered at the origin.
Parameters
----------
subdivisions : int
How many times to subdivide the mesh.
Note that the number of faces will grow as function of
4 ** subdivisions, so you probably want to keep this under ~5
radius : float
Desired radius of sphere
kwargs : dict
Passed through to `Trimesh` constructor.
Returns
---------
ico : trimesh.Trimesh
Meshed sphere
random_soup(face_count: Union[int, numpy.integer, numpy.unsignedinteger] = 100)
Return random triangles as a Trimesh
Parameters
-----------
face_count : int
Number of faces desired in mesh
Returns
-----------
soup : trimesh.Trimesh
Geometry with face_count random faces
revolve(linestring: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], angle: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None, cap: bool = False, sections: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> trimesh.base.Trimesh
Revolve a 2D line string around the 2D Y axis, with a result with
the 2D Y axis pointing along the 3D Z axis.
This function is intended to handle the complexity of indexing
and is intended to be used to create all radially symmetric primitives,
eventually including cylinders, annular cylinders, capsules, cones,
and UV spheres.
Note that if your linestring is closed, it needs to be counterclockwise
if you would like face winding and normals facing outwards.
Parameters
-------------
linestring : (n, 2) float
Lines in 2D which will be revolved
angle
Angle in radians to revolve curve by or if not
passed will be a full revolution (`angle = 2*pi`)
cap
If not a full revolution (`0.0 < angle < 2 * pi`)
and cap is True attempt to add a tessellated cap.
sections
Number of sections result should have
If not specified default is 32 per revolution
transform : None or (4, 4) float
Transform to apply to mesh after construction
**kwargs : dict
Passed to Trimesh constructor
Returns
--------------
revolved : Trimesh
Mesh representing revolved result
sweep_polygon(polygon: 'Polygon', path: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], angles: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, cap: bool = True, connect: bool = True, kwargs: Optional[dict] = None, **triangulation) -> trimesh.base.Trimesh
Extrude a 2D polygon into a 3D mesh along a 3D path. Note that this
does *not* handle the case where there is very sharp curvature leading
the polygon to intersect the plane of a previous slice, and does *not*
scale the polygon along the induced normal to result in a constant cross section.
You may want to resample your path with a B-spline, i.e:
`trimesh.path.simplify.resample_spline(path, smooth=0.2, count=100)`
Parameters
----------
polygon : shapely.geometry.Polygon
Profile to sweep along path
path : (n, 3) float
A path in 3D
angles : (n,) float
Optional rotation angle relative to prior vertex
at each vertex.
cap
If an open path is passed apply a cap to both ends.
connect
If a closed path is passed connect the sweep into
a single watertight mesh.
kwargs : dict
Passed to the mesh constructor.
**triangulation
Passed to `triangulate_polygon`, i.e. `engine='triangle'`
Returns
-------
mesh : trimesh.Trimesh
Geometry of result
torus(major_radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], minor_radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], major_sections: Union[int, numpy.integer, numpy.unsignedinteger] = 32, minor_sections: Union[int, numpy.integer, numpy.unsignedinteger] = 32, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs)
Create a mesh of a torus around Z centered at the origin.
Parameters
------------
major_radius: (float)
Radius from the center of the torus to the center of the tube.
minor_radius: (float)
Radius of the tube.
major_sections: int
Number of sections around major radius result should have
If not specified default is 32 per revolution
minor_sections: int
Number of sections around minor radius result should have
If not specified default is 32 per revolution
transform : (4, 4) float
Transformation matrix
**kwargs:
passed to Trimesh to create torus
Returns
------------
geometry : trimesh.Trimesh
Mesh of a torus
triangulate_polygon(polygon, triangle_args: Optional[str] = None, engine: Optional[str] = None, force_vertices: bool = False, **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.int64]]]
Given a shapely polygon create a triangulation using a
python interface to the permissively licensed `mapbox-earcut`
or the more robust `triangle.c`.
> pip install manifold3d
> pip install triangle
> pip install mapbox_earcut
Parameters
---------
polygon : Shapely.geometry.Polygon
Polygon object to be triangulated.
triangle_args
Passed to triangle.triangulate i.e: 'p', 'pq30', 'pY'="don't insert vert"
engine
None or 'earcut' will use earcut, 'triangle' will use triangle
force_vertices
Many operations can't handle new vertices being inserted, so this will
attempt to generate a triangulation without new vertices and raise a
ValueError if it is unable to do so.
Returns
--------------
vertices : (n, 2) float
Points in space
faces : (n, 3) int
Index of vertices that make up triangles
truncated_prisms(tris: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None)
Return a mesh consisting of multiple watertight prisms below
a list of triangles, truncated by a specified plane.
Parameters
-------------
triangles : (n, 3, 3) float
Triangles in space
origin : None or (3,) float
Origin of truncation plane
normal : None or (3,) float
Unit normal vector of truncation plane
Returns
-----------
mesh : trimesh.Trimesh
Triangular mesh
uv_sphere(radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, count: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> trimesh.base.Trimesh
Create a UV sphere (latitude + longitude) centered at the
origin. Roughly one order of magnitude faster than an
icosphere but slightly uglier.
Parameters
----------
radius : float
Radius of sphere
count : (2,) int
Number of latitude and longitude lines
transform : None or (4, 4) float
Transform to apply to mesh after construction
kwargs : dict
Passed thgrough
Returns
----------
mesh : trimesh.Trimesh
Mesh of UV sphere with specified parameters
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
log = <Logger trimesh.util (WARNING)>
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\creation.py
trimesh.curvature
Python Library Documentation: module trimesh.curvature in trimesh
NAME
trimesh.curvature
DESCRIPTION
curvature.py
---------------
Query mesh curvature.
FUNCTIONS
discrete_gaussian_curvature_measure(mesh, points, radius)
Return the discrete gaussian curvature measure of a sphere
centered at a point as detailed in 'Restricted Delaunay
triangulations and normal cycle'- Cohen-Steiner and Morvan.
This is the sum of the vertex defects at all vertices
within the radius for each point.
Parameters
----------
points : (n, 3) float
Points in space
radius : float ,
The sphere radius, which can be zero if vertices
passed are points.
Returns
--------
gaussian_curvature: (n,) float
Discrete gaussian curvature measure.
discrete_mean_curvature_measure(mesh, points, radius)
Return the discrete mean curvature measure of a sphere
centered at a point as detailed in 'Restricted Delaunay
triangulations and normal cycle'- Cohen-Steiner and Morvan.
This is the sum of the angle at all edges contained in the
sphere for each point.
Parameters
----------
points : (n, 3) float
Points in space
radius : float
Sphere radius which should typically be greater than zero
Returns
--------
mean_curvature : (n,) float
Discrete mean curvature measure.
face_angles_sparse(mesh)
A sparse matrix representation of the face angles.
Returns
----------
sparse : scipy.sparse.coo_matrix
matrix is float shaped (len(vertices), len(faces))
line_ball_intersection(start_points, end_points, center, radius)
Compute the length of the intersection of a line segment with a ball.
Parameters
----------
start_points : (n,3) float, list of points in space
end_points : (n,3) float, list of points in space
center : (3,) float, the sphere center
radius : float, the sphere radius
Returns
--------
lengths: (n,) float, the lengths.
sphere_ball_intersection(R, r)
Compute the surface area of the intersection of sphere of radius R centered
at (0, 0, 0) with a ball of radius r centered at (R, 0, 0).
Parameters
----------
R : float, sphere radius
r : float, ball radius
Returns
--------
area: float, the surface are.
vertex_defects(mesh)
Return the vertex defects, or (2*pi) minus the sum of the
angles of every face that includes that vertex.
If a vertex is only included by coplanar triangles, this
will be zero. For convex regions this is positive, and
concave negative.
Returns
--------
vertex_defect : (len(self.vertices), ) float
Vertex defect at the every vertex
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\curvature.py
trimesh.decomposition
Python Library Documentation: module trimesh.decomposition in trimesh
NAME
trimesh.decomposition
FUNCTIONS
convex_decomposition(mesh, **kwargs) -> list[dict]
Compute an approximate convex decomposition of a mesh.
VHACD Parameters which can be passed as kwargs:
Name Default
-----------------------------------------
maxConvexHulls 64
resolution 400000
minimumVolumePercentErrorAllowed 1.0
maxRecursionDepth 10
shrinkWrap True
fillMode "flood"
maxNumVerticesPerCH 64
asyncACD True
minEdgeLength 2
findBestPlane False
Parameters
----------
mesh : trimesh.Trimesh
Mesh to be decomposed into convex parts
**kwargs : VHACD keyword arguments
Returns
-------
mesh_args : list
List of **kwargs for Trimeshes that are nearly
convex and approximate the original.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\decomposition.py
trimesh.exceptions
Python Library Documentation: module trimesh.exceptions in trimesh
NAME
trimesh.exceptions
DESCRIPTION
exceptions.py
----------------
Wrap exceptions.
CLASSES
builtins.object
ExceptionWrapper
class ExceptionWrapper(builtins.object)
| ExceptionWrapper(exception: BaseException)
|
| Create a dummy object which will raise an exception when attributes
| are accessed (i.e. when used as a module) or when called (i.e.
| when used like a function)
|
| For soft dependencies we want to survive failing to import but
| we would like to raise an appropriate error when the functionality is
| actually requested so the user gets an easily debuggable message.
|
| Methods defined here:
|
| __call__(self, *args, **kwargs)
| Call self as a function.
|
| __getattribute__(self, *args, **kwargs)
| Return getattr(self, name).
|
| __init__(self, exception: BaseException)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\exceptions.py
trimesh.exchange
Python Library Documentation: package trimesh.exchange in trimesh
NAME
trimesh.exchange
DESCRIPTION
trimesh/exchange
----------------
Contains the importers and exporters for various mesh formats.
Note that *you should probably not be using these directly*, if
you call `trimesh.load` it will then call and wrap the result
of the various loaders:
```
mesh = trimesh.load(file_name)
```
PACKAGE CONTENTS
binvox
cascade
dae
export
gltf (package)
load
misc
obj
off
ply
stl
threedxml
threemf
urdf
xaml
xyz
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\exchange\__init__.py
trimesh.geometry
Python Library Documentation: module trimesh.geometry in trimesh
NAME
trimesh.geometry
FUNCTIONS
align_vectors(a, b, return_angle=False)
Find the rotation matrix that transforms one 3D vector
to another.
Parameters
------------
a : (3,) float
Unit vector
b : (3,) float
Unit vector
return_angle : bool
Return the angle between vectors or not
Returns
-------------
matrix : (4, 4) float
Homogeneous transform to rotate from `a` to `b`
angle : float
If `return_angle` angle in radians between `a` and `b`
faces_to_edges(faces, return_index=False)
Given a list of faces (n,3), return a list of edges (n*3,2)
Parameters
-----------
faces : (n, 3) int
Vertex indices representing faces
Returns
-----------
edges : (n*3, 2) int
Vertex indices representing edges
index_sparse(columns, indices, data=None, dtype=None)
Return a sparse matrix for which vertices are contained in which faces.
A data vector can be passed which is then used instead of booleans
Parameters
------------
columns : int
Number of columns, usually number of vertices
indices : (m, d) int
Usually mesh.faces
Returns
---------
sparse: scipy.sparse.coo_matrix of shape (columns, len(faces))
dtype is boolean
Examples
----------
In [1]: sparse = faces_sparse(len(mesh.vertices), mesh.faces)
In [2]: sparse.shape
Out[2]: (12, 20)
In [3]: mesh.faces.shape
Out[3]: (20, 3)
In [4]: mesh.vertices.shape
Out[4]: (12, 3)
In [5]: dense = sparse.toarray().astype(int)
In [6]: dense
Out[6]:
array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1]])
In [7]: dense.sum(axis=0)
Out[7]: array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3])
mean_vertex_normals(vertex_count, faces, face_normals, sparse=None, **kwargs)
Find vertex normals from the mean of the faces that contain
that vertex.
Parameters
-----------
vertex_count : int
The number of vertices faces refer to
faces : (n, 3) int
List of vertex indices
face_normals : (n, 3) float
Normal vector for each face
Returns
-----------
vertex_normals : (vertex_count, 3) float
Normals for every vertex
Vertices unreferenced by faces will be zero.
plane_transform(origin, normal)
Given the origin and normal of a plane find the transform
that will move that plane to be coplanar with the XY plane.
Parameters
----------
origin : (3,) float
Point that lies on the plane
normal : (3,) float
Vector that points along normal of plane
Returns
---------
transform: (4,4) float
Transformation matrix to move points onto XY plane
triangulate_quads(quads, dtype=<class 'numpy.int64'>, use_fan: bool = True) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Given an array of quad faces return them as triangle faces,
also handles pure triangles and mixed triangles and quads.
Parameters
-----------
quads: (n, 4) int
Vertex indices of quad faces.
dtype
Data type requested for the return
use_fan
Triangulate holes larger than quads with fans,
which may be wrong if the holes are non-convex
Returns
-----------
faces : (m, 3) int
Vertex indices of triangular faces.
vector_angle(pairs)
Find the angles between pairs of unit vectors.
Parameters
----------
pairs : (n, 2, 3) float
Unit vector pairs
Returns
----------
angles : (n,) float
Angles between vectors in radians
vertex_face_indices(vertex_count, faces, faces_sparse)
Find vertex face indices from the faces array of vertices
Parameters
-----------
vertex_count : int
The number of vertices faces refer to
faces : (n, 3) int
List of vertex indices
faces_sparse : scipy.sparse.COO
Sparse matrix
Returns
-----------
vertex_faces : (vertex_count, ) int
Face indices for every vertex
Array padded with -1 in each row for all vertices with fewer
face indices than the max number of face indices.
weighted_vertex_normals(vertex_count, faces, face_normals, face_angles, use_loop=False)
Compute vertex normals from the faces that contain that vertex.
The contribution of a face's normal to a vertex normal is the
ratio of the corner-angle in which the vertex is, with respect
to the sum of all corner-angles surrounding the vertex.
Grit Thuerrner & Charles A. Wuethrich (1998)
Computing Vertex Normals from Polygonal Facets,
Journal of Graphics Tools, 3:1, 43-46
Parameters
-----------
vertex_count : int
The number of vertices faces refer to
faces : (n, 3) int
List of vertex indices
face_normals : (n, 3) float
Normal vector for each face
face_angles : (n, 3) float
Angles at each vertex in the face
Returns
-----------
vertex_normals : (vertex_count, 3) float
Normals for every vertex
Vertices unreferenced by faces will be zero.
DATA
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
log = <Logger trimesh.util (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\geometry.py
trimesh.graph
Python Library Documentation: module trimesh.graph in trimesh
NAME
trimesh.graph
DESCRIPTION
graph.py
-------------
Deal with graph operations. Primarily deal with graphs in (n, 2)
edge list form, and abstract the backend graph library being used.
Currently uses networkx or scipy.sparse.csgraph backend.
FUNCTIONS
connected_component_labels(edges, node_count=None)
Label graph nodes from an edge list, using scipy.sparse.csgraph
Parameters
-----------
edges : (n, 2) int
Edges of a graph
node_count : int, or None
The largest node in the graph.
Returns
----------
labels : (node_count,) int
Component labels for each node
connected_components(edges, min_len: Union[int, numpy.integer, numpy.unsignedinteger] = 1, nodes=None, engine: Literal['networkx', 'scipy', None] = None)
Find groups of connected nodes from an edge list.
Parameters
-----------
edges : (n, 2) int
Edges between nodes
nodes : (m, ) int or None
List of nodes that exist
min_len : int
Minimum length of a component group to return
engine : str or None
Which graph engine to use (None for automatic):
(None, 'networkx', 'scipy')
Returns
-----------
components : (n,) sequence of (*,) int
Nodes which are connected
edges_to_coo(edges, count=None, data=None)
Given an edge list, return a boolean scipy.sparse.coo_matrix
representing the edges in matrix form.
Parameters
------------
edges : (n, 2) int
Edges of a graph
count : int
The total number of nodes in the graph
if None: count = edges.max() + 1
data : (n,) any
Assign data to each edge, if None will
be bool True for each specified edge
Returns
------------
matrix: (count, count) scipy.sparse.coo_matrix
Sparse COO
face_adjacency(faces=None, mesh=None, return_edges=False)
Returns an (n, 2) list of face indices.
Each pair of faces in the list shares an edge, making them adjacent.
Parameters
-----------
faces : (n, 3) int, or None
Vertex indices representing triangles
mesh : Trimesh object
If passed will used cached edges
instead of generating from faces
return_edges : bool
Return the edges shared by adjacent faces
Returns
----------
adjacency : (m, 2) int
Indexes of faces that are adjacent
edges: (m, 2) int
Only returned if return_edges is True
Indexes of vertices which make up the
edges shared by the adjacent faces
Examples
----------
This is useful for lots of things such as finding
face- connected components:
```python
>>> graph = nx.Graph()
>>> graph.add_edges_from(mesh.face_adjacency)
>>> groups = nx.connected_components(graph_connected)
```
face_adjacency_radius(mesh)
Compute an approximate radius between adjacent faces.
Parameters
--------------
mesh : trimesh.Trimesh
Returns
-------------
radii : (len(self.face_adjacency),) float
Approximate radius between faces
Parallel faces will have a value of np.inf
span : (len(self.face_adjacency),) float
Perpendicular projection distance of two
unshared vertices onto the shared edge
face_adjacency_unshared(mesh)
Return the vertex index of the two vertices not in the shared
edge between two adjacent faces
Parameters
----------
mesh : Trimesh object
Input mesh
Returns
-----------
vid_unshared : (len(mesh.face_adjacency), 2) int
Indexes of mesh.vertices
for degenerate faces without exactly
one unshared vertex per face it will be -1
face_neighborhood(mesh) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.int64]]
Find faces that share a vertex i.e. 'neighbors' faces.
Relies on the fact that an adjacency matrix at a power p
contains the number of paths of length p connecting two nodes.
Here we take the bipartite graph from mesh.faces_sparse to the power 2.
The non-zeros are the faces connected by one vertex.
Returns
----------
neighborhood : (n, 2) int
Pairs of faces which share a vertex
facets(mesh, engine: Literal['networkx', 'scipy', None] = None, facet_threshold: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Find the list of parallel adjacent faces.
Parameters
-----------
mesh : trimesh.Trimesh
engine
Which graph engine to use
facet_threshold : float
Threshold for two facets to be considered coplanar
Returns
---------
facets : sequence of (n,) int
Groups of face indexes of
parallel adjacent faces.
fill_traversals(traversals: collections.abc.Sequence, edges: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Union[collections.abc.Sequence, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]]
Convert a traversal of a list of edges into a sequence of
traversals where every pair of consecutive node indexes
is an edge in a passed edge list
Parameters
-------------
traversals : sequence of (m,) int
Node indexes of traversals of a graph
edges : (n, 2) int
Pairs of connected node indexes
Returns
--------------
splits : sequence of (p,) int
Node indexes of connected traversals
graph_to_svg(graph)
Turn a networkx graph into an SVG string
using graphviz `dot`.
Parameters
----------
graph: networkx graph
Returns
---------
svg: string, pictoral layout in SVG format
is_watertight(edges: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], edges_sorted: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> tuple[bool, bool]
Parameters
-----------
edges : (n, 2) int
List of vertex indices
edges_sorted : (n, 2) int
Pass vertex indices sorted on axis 1 as a speedup
Returns
---------
watertight : boolean
Whether every edge is shared by an even
number of faces
winding : boolean
Whether every shared edge is reversed
multigraph_collect(G, traversal, attrib=None)
Given a MultiDiGraph traversal, collect attributes along it.
Parameters
-------------
G: networkx.MultiDiGraph
traversal: (n) list of (node, instance) tuples
attrib: dict key, name to collect. If None, will return all
Returns
-------------
collected: (len(traversal) - 1) list of attributes
multigraph_paths(G, source, cutoff=None)
For a networkx MultiDiGraph, find all paths from a source node
to leaf nodes. This function returns edge instance numbers
in addition to nodes, unlike networkx.all_simple_paths.
Parameters
---------------
G : networkx.MultiDiGraph
Graph to evaluate
source : hashable
Node to start traversal at
cutoff : int
Number of nodes to visit
If None will visit all nodes
Returns
----------
traversals : (n,) list of [(node, edge instance index), ] paths
Traversals of the multigraph
neighbors(edges, max_index=None, directed=False)
Find the neighbors for each node in an edgelist graph.
TODO : re-write this with sparse matrix operations
Parameters
------------
edges : (n, 2) int
Connected nodes
directed : bool
If True, only connect edges in one direction
Returns
---------
neighbors : sequence
Vertex index corresponds to set of other vertex indices
shared_edges(faces_a, faces_b)
Given two sets of faces, find the edges which are in both sets.
Parameters
---------
faces_a : (n, 3) int
Array of faces
faces_b : (m, 3) int
Array of faces
Returns
---------
shared : (p, 2) int
Edges shared between faces
smooth_shade(mesh, angle: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None, facet_minarea: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = 10.0)
Return a non-watertight version of the mesh which
will render nicely with smooth shading by
disconnecting faces at sharp angles to each other.
Parameters
-----------
mesh : trimesh.Trimesh
Source geometry
angle : float or None
Angle in radians face pairs with angles
smaller than this will appear smoothed
facet_minarea : float or None
Minimum area fraction to consider
IE for `facets_minarea=25` only facets larger
than `mesh.area / 25` will be considered.
Returns
---------
smooth : trimesh.Trimesh
Geometry with disconnected face patches
split(mesh, only_watertight: bool = True, repair: bool = True, adjacency: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, engine: Literal['networkx', 'scipy', None] = None, **kwargs) -> list
Split a mesh into multiple meshes from face
connectivity.
If only_watertight is true it will only return
watertight meshes and will attempt to repair
single triangle or quad holes.
Parameters
----------
mesh : trimesh.Trimesh
The source multibody mesh to split
only_watertight
Only return watertight components and discard
any connected component that isn't fully watertight.
repair
If set try to fill small holes in a mesh, before the
discard step in `only_watertight.
adjacency : (n, 2) int
If passed will be used instead of `mesh.face_adjacency`
engine
Which graph engine to use for the connected components.
Returns
----------
meshes : (m,) trimesh.Trimesh
Results of splitting based on parameters.
traversals(edges, mode='bfs')
Given an edge list generate a sequence of ordered depth
first search traversals using scipy.csgraph routines.
Parameters
------------
edges : (n, 2) int
Undirected edges of a graph
mode : str
Traversal type, 'bfs' or 'dfs'
Returns
-----------
traversals : (m,) sequence of (p,) int
Ordered DFS or BFS traversals of the graph.
vertex_adjacency_graph(mesh)
Returns a networkx graph representing the vertices and
their connections in the mesh.
Parameters
----------
mesh : Trimesh object
Returns
---------
graph : networkx.Graph
Graph representing vertices and edges between
them where vertices are nodes and edges are edges
Examples
----------
This is useful for getting nearby vertices for a given vertex,
potentially for some simple smoothing techniques.
>>> graph = mesh.vertex_adjacency_graph
>>> graph.neighbors(0)
> [1, 3, 4]
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
GraphEngineType = typing.Literal['networkx', 'scipy', None]
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
log = <Logger trimesh.util (WARNING)>
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\graph.py
trimesh.grouping
Python Library Documentation: module trimesh.grouping in trimesh
NAME
trimesh.grouping
DESCRIPTION
grouping.py
-------------
Functions for grouping values and rows.
FUNCTIONS
blocks(data, min_len=2, max_len=inf, wrap=False, digits=None, only_nonzero=False)
Find the indices in an array of contiguous blocks
of equal values.
Parameters
------------
data : (n,) array
Data to find blocks on
min_len : int
The minimum length group to be returned
max_len : int
The maximum length group to be retuurned
wrap : bool
Combine blocks on both ends of 1D array
digits : None or int
If dealing with floats how many digits to consider
only_nonzero : bool
Only return blocks of non- zero values
Returns
---------
blocks : (m) sequence of (*,) int
Indices referencing data
boolean_rows(a: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], b: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], operation=<function intersect1d at 0x000002D3F9DB04F0>) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.int64]]
Find the rows in two arrays which occur in both rows.
Parameters
---------
a: (n, d) int
Array with row vectors
b: (m, d) int
Array with row vectors
operation : function
Numpy boolean set operation function:
-np.intersect1d
-np.setdiff1d
Returns
--------
shared : (p, d) int64
Array containing requested rows in both a and b
clusters(points, radius)
Find clusters of points which have neighbours closer than radius
Parameters
---------
points : (n, d) float
Points of dimension d
radius : float
Max distance between points in a cluster
Returns
----------
groups : (m,) sequence of int
Indices of points in a cluster
float_to_int(data, digits: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.int64]]
Given a numpy array of float/bool/int, return as integers.
Parameters
-------------
data : (n, d) float, int, or bool
Input data
digits : float or int
Precision for float conversion
Returns
-------------
as_int : (n, d) int
Data as integers
group(values, min_len: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, max_len: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Return the indices of values that are identical
Parameters
----------
values : (n,) int
Values to group
min_len : int
The shortest group allowed
All groups will have len >= min_length
max_len : int
The longest group allowed
All groups will have len <= max_length
Returns
----------
groups : sequence
Contains indices to form groups
IE [0,1,0,1] returns [[0,2], [1,3]]
group_distance(values: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], distance: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger]) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], collections.abc.Sequence]
Find non-overlapping groups of points where no two points in a
group are farther than 2*distance apart.
Parameters
---------
values : (n, d) float
Points of dimension d
distance : float
Max distance between points in a cluster
Returns
----------
unique : (m, d) float
Median value of each group
groups : (m) sequence of int
Indexes of points that make up a group
group_min(groups, data)
Given a list of groups find the minimum element of data
within each group
Parameters
-----------
groups : (n,) sequence of (q,) int
Indexes of each group corresponding to each element in data
data : (m,)
The data that groups indexes reference
Returns
-----------
minimums : (n,)
Minimum value of data per group
group_rows(data, require_count=None, digits=None)
Returns index groups of duplicate rows, for example:
[[1,2], [3,4], [1,2]] will return [[0,2], [1]]
Note that using require_count allows numpy advanced
indexing to be used in place of looping and
checking hashes and is ~10x faster.
Parameters
----------
data : (n, m) array
Data to group
require_count : None or int
Only return groups of a specified length, eg:
require_count = 2
[[1,2], [3,4], [1,2]] will return [[0,2]]
digits : None or int
If data is floating point how many decimals
to consider, or calculated from tol.merge
Returns
----------
groups : sequence (*,) int
Indices from in indicating identical rows.
group_vectors(vectors, angle=0.0001, include_negative=False)
Group vectors based on an angle tolerance, with the option to
include negative vectors.
Parameters
-----------
vectors : (n,3) float
Direction vector
angle : float
Group vectors closer than this angle in radians
include_negative : bool
If True consider the same:
[0,0,1] and [0,0,-1]
Returns
------------
new_vectors : (m,3) float
Direction vector
groups : (m,) sequence of int
Indices of source vectors
hashable_rows(data: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], digits: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, allow_int: bool = True) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
We turn our array into integers based on the precision
given by digits and then put them in a hashable format.
Parameters
---------
data : (n, m) array
Input data
digits : int or None
How many digits to add to hash if data is floating point
If None, tol.merge will be used
Returns
---------
hashable : (n,)
May return as a `np.void` or a `np.uint64`
merge_runs(data: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], digits: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Merge duplicate sequential values. This differs from unique_ordered
in that values can occur in multiple places in the sequence, but
only consecutive repeats are removed
Parameters
-----------
data: (n,) float or int
Returns
--------
merged: (m,) float or int
Examples
---------
In [1]: a
Out[1]:
array([-1, -1, -1, 0, 0, 1, 1, 2, 0,
3, 3, 4, 4, 5, 5, 6, 6, 7,
7, 8, 8, 9, 9, 9])
In [2]: trimesh.grouping.merge_runs(a)
Out[2]: array([-1, 0, 1, 2, 0, 3, 4, 5, 6, 7, 8, 9])
merge_vertices(mesh, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Removes duplicate vertices, grouped by position and
optionally texture coordinate and normal.
Parameters
-------------
mesh : Trimesh object
Mesh to merge vertices on
merge_tex : bool
If True textured meshes with UV coordinates will
have vertices merged regardless of UV coordinates
merge_norm : bool
If True, meshes with vertex normals will have
vertices merged ignoring different normals
digits_vertex : None or int
Number of digits to consider for vertex position
digits_norm : int
Number of digits to consider for unit normals
digits_uv : int
Number of digits to consider for UV coordinates
unique_bincount(values: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], minlength: Union[int, numpy.integer, numpy.unsignedinteger] = 0, return_inverse: bool = False, return_counts: bool = False)
For arrays of integers find unique values using bin counting.
Roughly 10x faster for correct input than np.unique
Parameters
--------------
values : (n,) int
Values to find unique members of
minlength : int
Maximum value that will occur in values (values.max())
return_inverse : bool
If True, return an inverse such that unique[inverse] == values
return_counts : bool
If True, also return the number of times each
unique item appears in values
Returns
------------
unique : (m,) int
Unique values in original array
inverse : (n,) int, optional
An array such that unique[inverse] == values
Only returned if return_inverse is True
counts : (m,) int, optional
An array holding the counts of each unique item in values
Only returned if return_counts is True
unique_float(data, return_index: bool = False, return_inverse: bool = False, digits: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Identical to the numpy.unique command, except evaluates floating point
numbers, using a specified number of digits.
If digits isn't specified, the library default TOL_MERGE will be used.
unique_ordered(data: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], return_index: bool = False, return_inverse: bool = False)
Returns the same as np.unique, but ordered as per the
first occurrence of the unique value in data.
Examples
---------
In [1]: a = [0, 3, 3, 4, 1, 3, 0, 3, 2, 1]
In [2]: np.unique(a)
Out[2]: array([0, 1, 2, 3, 4])
In [3]: trimesh.grouping.unique_ordered(a)
Out[3]: array([0, 3, 4, 1, 2])
unique_rows(data, digits=None, keep_order=False)
Returns indices of unique rows. It will return the
first occurrence of a row that is duplicated:
[[1,2], [3,4], [1,2]] will return [0,1]
Parameters
---------
data : (n, m) array
Floating point data
digits : int or None
How many digits to consider
Returns
--------
unique : (j,) int
Index in data which is a unique row
inverse : (n,) int
Array to reconstruct original
Example: data[unique][inverse] == data
unique_value_in_row(data, unique=None)
For a 2D array of integers find the position of a
value in each row which only occurs once.
If there are more than one value per row which
occur once, the last one is returned.
Parameters
----------
data : (n, d) int
Data to check values
unique : (m,) int
List of unique values contained in data.
Generated from np.unique if not passed
Returns
---------
result : (n, d) bool
With one or zero True values per row.
Examples
-------------------------------------
In [0]: r = np.array([[-1, 1, 1],
[-1, 1, -1],
[-1, 1, 1],
[-1, 1, -1],
[-1, 1, -1]], dtype=np.int8)
In [1]: unique_value_in_row(r)
Out[1]:
array([[ True, False, False],
[False, True, False],
[ True, False, False],
[False, True, False],
[False, True, False]], dtype=bool)
In [2]: unique_value_in_row(r).sum(axis=1)
Out[2]: array([1, 1, 1, 1, 1])
In [3]: r[unique_value_in_row(r)]
Out[3]: array([-1, 1, -1, 1, 1], dtype=int8)
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
log = <Logger trimesh.util (WARNING)>
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\grouping.py
trimesh.inertia
Python Library Documentation: module trimesh.inertia in trimesh
NAME
trimesh.inertia
DESCRIPTION
inertia.py
-------------
Functions for dealing with inertia tensors.
Results validated against known geometries and checked for
internal consistency.
FUNCTIONS
cylinder_inertia(mass: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Return the inertia tensor of a cylinder.
Parameters
------------
mass : float
Mass of cylinder
radius : float
Radius of cylinder
height : float
Height of cylinder
transform : (4, 4) float
Transformation of cylinder
Returns
------------
inertia : (3, 3) float
Inertia tensor
points_inertia(points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], weights: Union[NoneType, collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], numpy.floating, numpy.integer, numpy.unsignedinteger] = None, at_center_mass: bool = True) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Calculate an inertia tensor for an array of point masses
at the center of mass.
Parameters
----------
points : (n, 3)
Points in space.
weights : (n,) or number
Per-point weight to use.
at_center_mass
Calculate at the center of mass of the points, or if False
at the original origin.
Returns
-----------
tensor : (3, 3)
Inertia tensor for point masses.
principal_axis(inertia: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
Find the principal components and principal axis
of inertia from the inertia tensor.
Parameters
------------
inertia : (3, 3) float
Inertia tensor
Returns
------------
components : (3,) float
Principal components of inertia
vectors : (3, 3) float
Row vectors pointing along the
principal axes of inertia
radial_symmetry(mesh)
Check whether a mesh has radial symmetry.
Returns
-----------
symmetry : None or str
None No rotational symmetry
'radial' Symmetric around an axis
'spherical' Symmetric around a point
axis : None or (3,) float
Rotation axis or point
section : None or (3, 2) float
If radial symmetry provide vectors
to get cross section
scene_inertia(scene, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Calculate the inertia of a scene about a specific frame.
Parameters
------------
scene : trimesh.Scene
Scene with geometry.
transform : None or (4, 4) float
Homogeneous transform to compute inertia at.
Returns
----------
moment : (3, 3)
Inertia tensor about requested frame
sphere_inertia(mass: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Return the inertia tensor of a sphere.
Parameters
------------
mass : float
Mass of sphere
radius : float
Radius of sphere
Returns
------------
inertia : (3, 3) float
Inertia tensor
transform_inertia(transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inertia_tensor: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], parallel_axis: bool = False, mass: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Transform an inertia tensor to a new frame.
Note that in trimesh `mesh.moment_inertia` is *axis aligned*
and at `mesh.center_mass`.
So to transform to a new frame and get the moment of inertia at
the center of mass the translation should be ignored and only
rotation applied.
If parallel axis is enabled it will compute the inertia
about a new location.
More details in the MIT OpenCourseWare PDF:
` MIT16_07F09_Lec26.pdf`
Parameters
------------
transform : (3, 3) or (4, 4) float
Transformation matrix
inertia_tensor : (3, 3) float
Inertia tensor.
parallel_axis : bool
Apply the parallel axis theorum or not.
If the passed inertia tensor is at the center of mass
and you want the new post-transform tensor also at the
center of mass you DON'T want this enabled as you *only*
want to apply the rotation. Use this to get moment of
inertia at an arbitrary frame that isn't the center of mass.
Returns
------------
transformed : (3, 3) float
Inertia tensor in new frame.
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\inertia.py
trimesh.interfaces
Python Library Documentation: package trimesh.interfaces in trimesh
NAME
trimesh.interfaces
PACKAGE CONTENTS
blender
generic
DATA
__all__ = ['blender']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\interfaces\__init__.py
trimesh.intersections
Python Library Documentation: module trimesh.intersections in trimesh
NAME
trimesh.intersections
DESCRIPTION
intersections.py
------------------
Primarily mesh-plane intersections (slicing).
FUNCTIONS
mesh_multiplane(mesh, plane_origin, plane_normal, heights)
A utility function for slicing a mesh by multiple
parallel planes which caches the dot product operation.
Parameters
-------------
mesh : trimesh.Trimesh
Geometry to be sliced by planes
plane_origin : (3,) float
Point on a plane
plane_normal : (3,) float
Normal vector of plane
heights : (m,) float
Offset distances from plane to slice at:
at `height=0` it will be exactly on the passed plane.
Returns
--------------
lines : (m,) sequence of (n, 2, 2) float
Lines in space for m planes
to_3D : (m, 4, 4) float
Transform to move each section back to 3D
face_index : (m,) sequence of (n,) int
Indexes of mesh.faces for each segment
mesh_plane(mesh, plane_normal, plane_origin, return_faces=False, local_faces=None, cached_dots=None)
Find a the intersections between a mesh and a plane,
returning a set of line segments on that plane.
Parameters
---------
mesh : Trimesh object
Source mesh to slice
plane_normal : (3,) float
Normal vector of plane to intersect with mesh
plane_origin : (3,) float
Point on plane to intersect with mesh
return_faces : bool
If True return face index each line is from
local_faces : None or (m,) int
Limit section to just these faces.
cached_dots : (n, 3) float
If an external function has stored dot
products pass them here to avoid recomputing.
Returns
----------
lines : (m, 2, 3) float
List of 3D line segments in space.
face_index : (m,) int
Index of mesh.faces for each line
Only returned if return_faces was True
plane_lines(plane_origin, plane_normal, endpoints, line_segments=True)
Calculate plane-line intersections
Parameters
---------
plane_origin : (3,) float
Point on plane
plane_normal : (3,) float
Plane normal vector
endpoints : (2, n, 3) float
Points defining lines to be tested
line_segments : bool
If True, only returns intersections as valid if
vertices from endpoints are on different sides
of the plane.
Returns
---------
intersections : (m, 3) float
Cartesian intersection points
valid : (n, 3) bool
Indicate whether a valid intersection exists
for each input line segment
planes_lines(plane_origins, plane_normals, line_origins, line_directions, return_distance=False, return_denom=False)
Given one line per plane find the intersection points.
Parameters
-----------
plane_origins : (n,3) float
Point on each plane
plane_normals : (n,3) float
Normal vector of each plane
line_origins : (n,3) float
Point at origin of each line
line_directions : (n,3) float
Direction vector of each line
return_distance : bool
Return distance from origin to point also
return_denom : bool
Return denominator, so you can check for small values
Returns
----------
on_plane : (n,3) float
Points on specified planes
valid : (n,) bool
Did plane intersect line or not
distance : (n,) float
[OPTIONAL] Distance from point
denom : (n,) float
[OPTIONAL] Denominator
slice_faces_plane(vertices, faces, plane_normal, plane_origin, uv=None, face_index=None, cached_dots=None)
Slice a mesh (given as a set of faces and vertices) with a plane, returning a
new mesh (again as a set of faces and vertices) that is the
portion of the original mesh to the positive normal side of the plane.
Parameters
---------
vertices : (n, 3) float
Vertices of source mesh to slice
faces : (n, 3) int
Faces of source mesh to slice
plane_normal : (3,) float
Normal vector of plane to intersect with mesh
plane_origin : (3,) float
Point on plane to intersect with mesh
uv : (n, 2) float, optional
UV coordinates of source mesh to slice
face_index : ((m,) int)
Indexes of faces to slice. When no mask is provided, the
default is to slice all faces.
cached_dots : (n, 3) float
If an external function has stored dot
products pass them here to avoid recomputing
Returns
----------
new_vertices : (n, 3) float
Vertices of sliced mesh
new_faces : (n, 3) int
Faces of sliced mesh
new_uv : (n, 2) int or None
UV coordinates of sliced mesh
slice_mesh_plane(mesh, plane_normal, plane_origin, face_index=None, cap=False, engine=None, **kwargs)
Slice a mesh with a plane returning a new mesh that is the
portion of the original mesh to the positive normal side
of the plane.
Parameters
---------
mesh : Trimesh object
Source mesh to slice
plane_normal : (3,) float
Normal vector of plane to intersect with mesh
plane_origin : (3,) float
Point on plane to intersect with mesh
cap : bool
If True, cap the result with a triangulated polygon
face_index : ((m,) int)
Indexes of mesh.faces to slice. When no mask is provided, the
default is to slice all faces.
cached_dots : (n, 3) float
If an external function has stored dot
products pass them here to avoid recomputing
engine : None or str
Triangulation engine passed to `triangulate_polygon`
kwargs : dict
Passed to the newly created sliced mesh
Returns
----------
new_mesh : Trimesh object
Sliced mesh
DATA
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\intersections.py
trimesh.interval
Python Library Documentation: module trimesh.interval in trimesh
NAME
trimesh.interval
DESCRIPTION
interval.py
--------------
Deal with 1D intervals which are defined by:
[start position, end position]
FUNCTIONS
intersection(a: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], b: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Given pairs of ranges merge them in to
one range if they overlap.
Parameters
--------------
a : (2, ) or (n, 2)
Start and end of a 1D interval
b : (2, ) float
Start and end of a 1D interval
Returns
--------------
inter : (2, ) or (2, 2) float
The unioned range from the two inputs,
if not np.ptp(`inter, axis=1)` will be zero.
union(intervals: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], sort: bool = True) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
For array of multiple intervals union them all into
the subset of intervals.
For example:
`intervals = [[1,2], [2,3]] -> [[1, 3]]`
`intervals = [[1,2], [2.5,3]] -> [[1, 2], [2.5, 3]]`
Parameters
------------
intervals : (n, 2)
Pairs of `(min, max)` values.
sort
If the array is already ordered into (min, max) pairs
and then pairs sorted by minimum value you can skip the
sorting in this function.
Returns
----------
unioned : (m, 2)
New intervals where `m <= n`
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\interval.py
trimesh.iteration
Python Library Documentation: module trimesh.iteration in trimesh
NAME
trimesh.iteration
FUNCTIONS
chain(*args: Union[collections.abc.Iterable[Any], Any, NoneType]) -> list[typing.Any]
A less principled version of `list(itertools.chain(*args))` that
accepts non-iterable values, filters `None`, and returns a list
rather than yielding values.
If all passed values are iterables this will return identical
results to `list(itertools.chain(*args))`.
Examples
----------
In [1]: list(itertools.chain([1,2], [3]))
Out[1]: [1, 2, 3]
In [2]: trimesh.util.chain([1,2], [3])
Out[2]: [1, 2, 3]
In [3]: trimesh.util.chain([1,2], [3], 4)
Out[3]: [1, 2, 3, 4]
In [4]: list(itertools.chain([1,2], [3], 4))
----> 1 list(itertools.chain([1,2], [3], 4))
TypeError: 'int' object is not iterable
In [5]: trimesh.util.chain([1,2], None, 3, None, [4], [], [], 5, [])
Out[5]: [1, 2, 3, 4, 5]
Parameters
-----------
args
Will be individually checked to see if they're iterable
before either being appended or extended to a flat list.
Returns
----------
chained
The values in a flat list.
log2(x, /)
Return the base 2 logarithm of x.
reduce_cascade(operation: collections.abc.Callable, items: Union[collections.abc.Sequence, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]])
Call an operation function in a cascaded pairwise way against a
flat list of items.
This should produce the same result as `functools.reduce`
if `operation` is commutable like addition or multiplication.
This may be faster for an `operation` that runs with a speed
proportional to its largest input, which mesh booleans appear to.
The union of a large number of small meshes appears to be
"much faster" using this method.
This only differs from `functools.reduce` for commutative `operation`
in that it returns `None` on empty inputs rather than `functools.reduce`
which raises a `TypeError`.
For example on `a b c d e f g` this function would run and return:
a b
c d
e f
ab cd
ef g
abcd efg
-> abcdefg
Where `functools.reduce` would run and return:
a b
ab c
abc d
abcd e
abcde f
abcdef g
-> abcdefg
Parameters
----------
operation
The function to call on pairs of items.
items
The flat list of items to apply operation against.
DATA
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\iteration.py
trimesh.load
Python Library Documentation: function load in module trimesh.exchange.load
load(file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType], file_type: Optional[str] = None, resolver: Union[trimesh.resolvers.Resolver, collections.abc.Mapping, NoneType] = None, force: Optional[str] = None, allow_remote: bool = False, **kwargs) -> trimesh.parent.Geometry
THIS FUNCTION IS DEPRECATED but there are no current plans for it to be removed.
For new code the typed load functions `trimesh.load_scene` or `trimesh.load_mesh`
are recommended over `trimesh.load` which is a backwards-compatibility wrapper
that mimics the behavior of the old function and can return any geometry type.
Parameters
-----------
file_obj : str, or file- like object
The source of the data to be loadeded
file_type: str
What kind of file type do we have (eg: 'stl')
resolver : trimesh.visual.Resolver
Object to load referenced assets like materials and textures
force : None or str
For 'mesh': try to coerce scenes into a single mesh
For 'scene': try to coerce everything into a scene
allow_remote
If True allow this load call to work on a remote URL.
kwargs : dict
Passed to geometry __init__
Returns
---------
geometry : Trimesh, Path2D, Path3D, Scene
Loaded geometry as trimesh classes
trimesh.load_mesh
Python Library Documentation: function load_mesh in module trimesh.exchange.load
load_mesh(*args, **kwargs) -> trimesh.base.Trimesh
Load a file into a Trimesh object.
Parameters
-----------
file_obj : str or file object
File name or file with mesh data
file_type : str or None
Which file type, e.g. 'stl'
kwargs : dict
Passed to Trimesh constructor
Returns
----------
mesh
Loaded geometry data.
trimesh.load_path
Python Library Documentation: function load_path in module trimesh.path.exchange.load
load_path(file_obj, file_type: Optional[str] = None, **kwargs)
Load a file to a Path file_object.
Parameters
-----------
file_obj
Accepts many types:
- Path, Path2D, or Path3D file_objects
- open file file_object (dxf or svg)
- file name (dxf or svg)
- shapely.geometry.Polygon
- shapely.geometry.MultiLineString
- dict with kwargs for Path constructor
- `(n, 2, (2|3)) float` line segments
file_type
Type of file is required if file
object is passed.
Returns
---------
path : Path, Path2D, Path3D file_object
Data as a native trimesh Path file_object
trimesh.load_remote
Python Library Documentation: function load_remote in module trimesh.exchange.load
load_remote(url: str, **kwargs) -> trimesh.scene.scene.Scene
Load a mesh at a remote URL into a local trimesh object.
This is a thin wrapper around:
`trimesh.load_scene(file_obj=url, allow_remote=True, **kwargs)`
Parameters
------------
url
URL containing mesh file
**kwargs
Passed to `load_scene`
Returns
------------
loaded : Trimesh, Path, Scene
Loaded result
trimesh.load_scene
Python Library Documentation: function load_scene in module trimesh.exchange.load
load_scene(file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType], file_type: Optional[str] = None, resolver: Union[trimesh.resolvers.Resolver, collections.abc.Mapping, NoneType] = None, allow_remote: bool = False, metadata: Optional[dict] = None, **kwargs) -> trimesh.scene.scene.Scene
Load geometry into the `trimesh.Scene` container. This may contain
any `parent.Geometry` object, including `Trimesh`, `Path2D`, `Path3D`,
or a `PointCloud`.
Parameters
-----------
file_obj : str, or file- like object
The source of the data to be loadeded
file_type: str
What kind of file type do we have (eg: 'stl')
resolver : trimesh.visual.Resolver
Object to load referenced assets like materials and textures
force : None or str
For 'mesh': try to coerce scenes into a single mesh
For 'scene': try to coerce everything into a scene
allow_remote
If True allow this load call to work on a remote URL.
kwargs : dict
Passed to geometry __init__
Returns
---------
geometry : Trimesh, Path2D, Path3D, Scene
Loaded geometry as trimesh classes
trimesh.nsphere
Python Library Documentation: module trimesh.nsphere in trimesh
NAME
trimesh.nsphere
DESCRIPTION
nsphere.py
--------------
Functions for fitting and minimizing nspheres:
circles, spheres, hyperspheres, etc.
FUNCTIONS
fit_nsphere(points, prior=None)
Fit an n-sphere to a set of points using least squares.
Parameters
------------
points : (n, d) float
Points in space
prior : (d,) float
Best guess for center of nsphere
Returns
---------
center : (d,) float
Location of center
radius : float
Mean radius across circle
error : float
Peak to peak value of deviation from mean radius
is_nsphere(points)
Check if a list of points is an nsphere.
Parameters
-----------
points : (n, dimension) float
Points in space
Returns
-----------
check : bool
True if input points are on an nsphere
minimum_nsphere(obj)
Compute the minimum n- sphere for a mesh or a set of points.
Uses the fact that the minimum n- sphere will be centered at one of
the vertices of the furthest site voronoi diagram, which is n*log(n)
but should be pretty fast due to using the scipy/qhull implementations
of convex hulls and voronoi diagrams.
Parameters
----------
obj : (n, d) float or trimesh.Trimesh
Points or mesh to find minimum bounding nsphere
Returns
----------
center : (d,) float
Center of fitted n- sphere
radius : float
Radius of fitted n-sphere
DATA
log = <Logger trimesh.util (WARNING)>
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\nsphere.py
trimesh.parent
Python Library Documentation: module trimesh.parent in trimesh
NAME
trimesh.parent
DESCRIPTION
parent.py
-------------
The base class for Trimesh, PointCloud, and Scene objects
CLASSES
abc.ABC(builtins.object)
Geometry
Geometry3D
builtins.object
LoadSource
class Geometry(abc.ABC)
| `Geometry` is the parent class for all geometry.
|
| By decorating a method with `abc.abstractmethod` it means
| the objects that inherit from `Geometry` MUST implement
| those methods.
|
| Method resolution order:
| Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_transform(self, matrix: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Any
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| copy(self)
|
| export(self, file_obj, file_type=None)
|
| show(self)
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| bounds
|
| extents
|
| identifier_hash
|
| is_empty
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__add__', 'apply_transform', 'bounds...
|
| __annotations__ = {'metadata': <class 'dict'>}
class Geometry3D(Geometry)
| The `Geometry3D` object is the parent object of geometry objects
| which are three dimensional, including Trimesh, PointCloud,
| and Scene objects.
|
| Method resolution order:
| Geometry3D
| Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__add__', 'apply_transform', 'bounds...
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Geometry:
|
| __add__(self, other)
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_transform(self, matrix: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Any
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| copy(self)
|
| export(self, file_obj, file_type=None)
|
| show(self)
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Geometry:
|
| bounds
|
| extents
|
| identifier_hash
|
| is_empty
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
class LoadSource(builtins.object)
| LoadSource(file_obj: Optional[Any] = None, file_type: Optional[str] = None, file_path: Optional[str] = None, was_opened: bool = False, resolver: Union[trimesh.resolvers.Resolver, collections.abc.Mapping, NoneType] = None) -> None
|
| Save information about where a particular object was loaded from.
|
| Methods defined here:
|
| __deepcopy__(self, *args)
|
| __eq__(self, other)
| Return self==value.
|
| __getstate__(self) -> dict
| Helper for pickle.
|
| __init__(self, file_obj: Optional[Any] = None, file_type: Optional[str] = None, file_path: Optional[str] = None, was_opened: bool = False, resolver: Union[trimesh.resolvers.Resolver, collections.abc.Mapping, NoneType] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| file_name
| Get just the file name from the path if available.
|
| Returns
| ---------
| file_name
| Just the file name, i.e. for file_path="/a/b/c.stl" -> "c.stl"
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'file_obj': typing.Optional[typing.Any], 'file_path...
|
| __dataclass_fields__ = {'file_obj': Field(name='file_obj',type=typing....
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('file_obj', 'file_type', 'file_path', 'was_opened', ...
|
| file_obj = None
|
| file_path = None
|
| file_type = None
|
| resolver = None
|
| was_opened = False
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
ResolverLike = typing.Union[trimesh.resolvers.Resolver, collections.ab...
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\parent.py
trimesh.path
Python Library Documentation: package trimesh.path in trimesh
NAME
trimesh.path
DESCRIPTION
trimesh.path
-------------
Handle 2D and 3D vector paths such as those contained in an
SVG or DXF file.
PACKAGE CONTENTS
arc
creation
curve
entities
exchange (package)
intersections
packing
path
polygons
raster
repair
segments
simplify
traversal
util
CLASSES
trimesh.path.path.Path(trimesh.parent.Geometry)
trimesh.path.path.Path2D
trimesh.path.path.Path3D
class Path2D(Path)
| Path2D(entities: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], collections.abc.Iterable[trimesh.path.entities.Entity], NoneType] = None, vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, metadata: Optional[collections.abc.Mapping] = None, process: bool = True, colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_attributes: Optional[collections.abc.Mapping] = None, **kwargs)
|
| Hold multiple vector curves (lines, arcs, splines, etc) in 3D.
|
| Method resolution order:
| Path2D
| Path
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| apply_obb(self)
| Transform the current path so that its OBB is axis aligned
| and OBB center is at the origin.
|
| Returns
| -----------
| obb : (3, 3) float
| Homogeneous transformation matrix
|
| apply_scale(self, scale)
| Apply a 2D scale to the current Path2D.
|
| Parameters
| -------------
| scale : float or (2,) float
| Scale to apply in-place.
|
| connected_paths(self, path_id, include_self=False)
| Given an index of self.paths find other paths which
| overlap with that path.
|
| Parameters
| -----------
| path_id : int
| Index of self.paths
| include_self : bool
| Should the result include path_id or not
|
| Returns
| -----------
| path_ids : (n, ) int
| Indexes of self.paths that overlap input path_id
|
| extrude(self, height, **kwargs)
| Extrude the current 2D path into a 3D mesh.
|
| Parameters
| ----------
| height: float, how far to extrude the profile
| kwargs: passed directly to meshpy.triangle.build:
| triangle.build(mesh_info,
| verbose=False,
| refinement_func=None,
| attributes=False,
| volume_constraints=True,
| max_volume=None,
| allow_boundary_steiner=True,
| allow_volume_steiner=True,
| quality_meshing=True,
| generate_edges=None,
| generate_faces=False,
| min_angle=None)
| Returns
| --------
| mesh: trimesh object representing extruded polygon
|
| medial_axis(self, resolution=None, clip=None)
| Find the approximate medial axis based
| on a voronoi diagram of evenly spaced points on the
| boundary of the polygon.
|
| Parameters
| ----------
| resolution : None or float
| Distance between each sample on the polygon boundary
| clip : None, or (2,) float
| Min, max number of samples
|
| Returns
| ----------
| medial : Path2D object
| Contains only medial axis of Path
|
| plot_discrete(self, show=False, annotations=True)
| Plot the closed curves of the path.
|
| plot_entities(self, show=False, annotations=True, color=None)
| Plot the entities of the path with no notion of topology.
|
| Parameters
| ------------
| show : bool
| Open a window immediately or not
| annotations : bool
| Call an entities custom plot function.
| color : str
| Override entity colors and make them all this color.
|
| rasterize(self, pitch=None, origin=None, resolution=None, fill=True, width=None, **kwargs)
| Rasterize a Path2D object into a boolean image ("mode 1").
|
| Parameters
| ------------
| pitch : float or (2,) float
| Length(s) in model space of pixel edges
| origin : (2,) float
| Origin position in model space
| resolution : (2,) int
| Resolution in pixel space
| fill : bool
| If True will return closed regions as filled
| width : int
| If not None will draw outline this wide (pixels)
|
| Returns
| ------------
| raster : PIL.Image object, mode 1
| Rasterized version of closed regions.
|
| sample(self, count, **kwargs)
| Use rejection sampling to generate random points inside a
| polygon.
|
| Parameters
| -----------
| count : int
| Number of points to return
| If there are multiple bodies, there will
| be up to count * bodies points returned
| factor : float
| How many points to test per loop
| IE, count * factor
| max_iter : int,
| Maximum number of intersection loops
| to run, total points sampled is
| count * factor * max_iter
|
| Returns
| -----------
| hit : (n, 2) float
| Random points inside polygon
|
| show(self, annotations=True)
| Plot the current Path2D object using matplotlib.
|
| simplify(self, **kwargs)
| Return a version of the current path with colinear segments
| merged, and circles entities replacing segmented circular paths.
|
| Returns
| ---------
| simplified : Path2D object
|
| simplify_spline(self, smooth=0.0002, verbose=False)
| Convert paths into b-splines.
|
| Parameters
| -----------
| smooth : float
| How much the spline should smooth the curve
| verbose : bool
| Print detailed log messages
|
| Returns
| ------------
| simplified : Path2D
| Discrete curves replaced with splines
|
| split(self, **kwargs)
| If the current Path2D consists of n 'root' curves,
| split them into a list of n Path2D objects
|
| Returns
| ----------
| split: (n,) list of Path2D objects
| Each connected region and interiors
|
| to_3D(self, transform=None)
| Convert 2D path to 3D path on the XY plane.
|
| Parameters
| -------------
| transform : (4, 4) float
| If passed, will transform vertices.
| If not passed and 'to_3D' is in self.metadata
| that transform will be used.
|
| Returns
| -----------
| path_3D : Path3D
| 3D version of current path
|
| triangulate(self, **kwargs)
| Create a region- aware triangulation of the 2D path.
|
| Parameters
| -------------
| **kwargs : dict
| Passed to `trimesh.creation.triangulate_polygon`
|
| Returns
| -------------
| vertices : (n, 2) float
| 2D vertices of triangulation
| faces : (n, 3) int
| Indexes of vertices for triangles
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| Return the area of the polygons interior.
|
| Returns
| ---------
| area : float
| Total area of polygons minus interiors
|
| body_count
| Returns a count of the number of unconnected polygons that
| may contain other curves but aren't contained themselves.
|
| Returns
| ---------
| body_count : int
| Number of unconnected independent polygons.
|
| convex_hull
| Return a convex hull of the 2D path.
|
| Returns
| --------
| hull
| A convex hull of included vertices from this path.
|
| enclosure
| Undirected graph object of polygon enclosure.
|
| Returns
| -----------
| enclosure : networkx.Graph
| Enclosure graph of self.polygons by index.
|
| enclosure_directed
| Directed graph of polygon enclosure.
|
| Returns
| ----------
| enclosure_directed : networkx.DiGraph
| Directed graph: child nodes are fully
| contained by their parent node.
|
| enclosure_shell
| A dictionary of path indexes which are 'shell' paths, and values
| of 'hole' paths.
|
| Returns
| ----------
| corresponding : dict
| {index of self.paths of shell : [indexes of holes]}
|
| identifier
| A unique identifier for the path.
|
| Returns
| ---------
| identifier : (5,) float
| Unique identifier
|
| obb
| Get a transform that centers and aligns the OBB of the
| referenced vertices with the XY axis.
|
| Returns
| -----------
| obb : (3, 3) float
| Homogeneous transformation matrix
|
| path_valid
| Returns
| ----------
| path_valid : (n,) bool
| Indexes of self.paths self.polygons_closed
| which are valid polygons.
|
| polygons_closed
| Cycles in the vertex graph, as shapely.geometry.Polygons.
| These are polygon objects for every closed circuit, with no notion
| of whether a polygon is a hole or an area. Every polygon in this
| list will have an exterior, but NO interiors.
|
| Returns
| ---------
| polygons_closed : (n,) list of shapely.geometry.Polygon objects
|
| polygons_full
| A list of shapely.geometry.Polygon objects with interiors created
| by checking which closed polygons enclose which other polygons.
|
| Returns
| ---------
| full : (len(self.root),) shapely.geometry.Polygon
| Polygons containing interiors
|
| root
| Which indexes of self.paths/self.polygons_closed
| are root curves, also known as 'shell' or 'exterior.
|
| Returns
| ---------
| root : (n,) int
| List of indexes
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Path:
|
| __add__(self, other)
| Concatenate two Path objects by appending vertices and
| reindexing point references.
|
| Parameters
| -----------
| other: Path object
|
| Returns
| -----------
| concat: Path object, appended from self and other
|
| __hash__(self)
| A hash of the current vertices and entities.
|
| Returns
| ------------
| hash : long int
| Appended hashes
|
| __init__(self, entities: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], collections.abc.Iterable[trimesh.path.entities.Entity], NoneType] = None, vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, metadata: Optional[collections.abc.Mapping] = None, process: bool = True, colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_attributes: Optional[collections.abc.Mapping] = None, **kwargs)
| Instantiate a path object.
|
| Parameters
| -----------
| entities : (m,) trimesh.path.entities.Entity
| Contains geometric entities
| vertices : (n, dimension) float
| The vertices referenced by entities
| metadata : dict
| Any metadata about the path
| process : bool
| Run simple cleanup or not
| colors
| Set any per-entity colors.
| vertex_attributes
| Set any per-vertex array data.
|
| __repr__(self)
| Print a quick summary of the number of vertices and entities.
|
| apply_layer(self, name: str) -> None
| Apply a layer name to every entity in the path.
|
| Parameters
| ------------
| name : str
| Apply layer name to every entity
|
| apply_transform(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Self
| Apply a transformation matrix to the current path in- place
|
| Parameters
| -----------
| transform : (d+1, d+1) float
| Homogeneous transformations for vertices
|
| convert_units(self, desired: str, guess: bool = False)
| Convert the units of the current drawing in place.
|
| Parameters
| -----------
| desired : str
| Unit system to convert to
| guess : bool
| If True will attempt to guess units
|
| copy(self, layers: Union[str, NoneType, collections.abc.Iterable[Optional[str]]] = None)
| Get a copy of the current mesh
|
| Parameters
| ------------
| layers
| If passed an iterable of layer names which will
| only include those layers in the copy of the path.
|
| Returns
| ---------
| copied : Path object
| Copy of self
|
| explode(self)
| Turn every multi- segment entity into single segment
| entities in- place.
|
| export(self, file_obj=None, file_type=None, **kwargs)
| Export the path to a file object or return data.
|
| Parameters
| ---------------
| file_obj : None, str, or file object
| File object or string to export to
| file_type : None or str
| Type of file: dxf, dict, svg
|
| Returns
| ---------------
| exported : bytes or str
| Exported as specified type
|
| fill_gaps(self, distance=0.025)
| Find vertices without degree 2 and try to connect to
| other vertices. Operations are done in-place.
|
| Parameters
| ----------
| distance : float
| Connect vertices up to this distance
|
| merge_vertices(self, digits=None)
| Merges vertices which are identical and replace references
| by altering `self.entities` and `self.vertices`
|
| Parameters
| --------------
| digits : None, or int
| How many digits to consider when merging vertices
|
| process(self) -> Self
| Apply basic cleaning functions to the Path object in-place.
|
| remove_duplicate_entities(self)
| Remove entities that are duplicated
|
| Notes
| -------
| self.entities: length same or shorter
|
| remove_entities(self, entity_ids)
| Remove entities by index.
|
| Parameters
| -----------
| entity_ids : (n,) int
| Indexes of self.entities to remove
|
| remove_invalid(self)
| Remove entities which declare themselves invalid
|
| Notes
| ----------
| self.entities: shortened
|
| remove_unreferenced_vertices(self)
| Removes all vertices which aren't used by an entity.
|
| Notes
| ---------
| self.vertices : reordered and shortened
| self.entities : entity.points references updated
|
| replace_vertex_references(self, mask)
| Replace the vertex index references in every entity.
|
| Parameters
| ------------
| mask : (len(self.vertices), ) int
| Contains new vertex indexes
|
| Notes
| ------------
| entity.points in self.entities
| Replaced by mask[entity.points]
|
| rezero(self)
| Translate so that every vertex is positive in the current
| mesh is positive.
|
| Returns
| -----------
| matrix : (dimension + 1, dimension + 1) float
| Homogeneous transformations that was applied
| to the current Path object.
|
| scene(self)
| Get a scene object containing the current Path3D object.
|
| Returns
| --------
| scene: trimesh.scene.Scene object containing current path
|
| to_dict(self) -> dict
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Path:
|
| bounds
| Return the axis aligned bounding box of the current path.
|
| Returns
| ----------
| bounds : (2, dimension) float
| AABB with (min, max) coordinates
|
| centroid
| Return the centroid of axis aligned bounding box enclosing
| all entities of the path object.
|
| Returns
| -----------
| centroid : (d,) float
| Approximate centroid of the path
|
| dangling
| List of entities that aren't included in a closed path
|
| Returns
| ----------
| dangling : (n,) int
| Index of self.entities
|
| discrete
| A sequence of connected vertices in space, corresponding to
| self.paths.
|
| Returns
| ---------
| discrete : (len(self.paths),)
| A sequence of (m*, dimension) float
|
| extents
| The size of the axis aligned bounding box.
|
| Returns
| ---------
| extents : (dimension,) float
| Edge length of AABB
|
| identifier_hash
| Return a hash of the identifier.
|
| Returns
| ----------
| hashed : (64,) str
| SHA256 hash of the identifier vector.
|
| is_closed
| Are all entities connected to other entities.
|
| Returns
| -----------
| closed : bool
| Every entity is connected at its ends
|
| is_empty
| Are any entities defined for the current path.
|
| Returns
| ----------
| empty : bool
| True if no entities are defined
|
| kdtree
| A KDTree object holding the vertices of the path.
|
| Returns
| ----------
| kdtree : scipy.spatial.cKDTree
| Object holding self.vertices
|
| layers
| Get a list of the layer for every entity.
|
| Returns
| ---------
| layers : (len(entities), ) any
| Whatever is stored in each `entity.layer`
|
| length
| The total discretized length of every entity.
|
| Returns
| --------
| length : float
| Summed length of every entity
|
| paths
| Sequence of closed paths, encoded by entity index.
|
| Returns
| ---------
| paths : (n,) sequence of (*,) int
| Referencing self.entities
|
| referenced_vertices
| Which vertices are referenced by an entity.
|
| Returns
| -----------
| referenced_vertices: (n,) int, indexes of self.vertices
|
| vertex_graph
| Return a networkx.Graph object for the entity connectivity
|
| graph : networkx.Graph
| Holds vertex indexes
|
| vertex_nodes
| Get a list of which vertex indices are nodes,
| which are either endpoints or points where the
| entity makes a direction change.
|
| Returns
| --------------
| nodes : (n, 2) int
| Indexes of self.vertices which are nodes
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Path:
|
| colors
| Colors are stored per-entity.
|
| Returns
| ------------
| colors : (len(entities), 4) uint8
| RGBA colors for each entity
|
| entities
| The actual entities making up the path.
|
| Returns
| -----------
| entities : (n,) trimesh.path.entities.Entity
| Entities such as Line, Arc, or BSpline curves
|
| vertices
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
class Path3D(Path)
| Path3D(entities: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], collections.abc.Iterable[trimesh.path.entities.Entity], NoneType] = None, vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, metadata: Optional[collections.abc.Mapping] = None, process: bool = True, colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_attributes: Optional[collections.abc.Mapping] = None, **kwargs)
|
| Hold multiple vector curves (lines, arcs, splines, etc) in 3D.
|
| Method resolution order:
| Path3D
| Path
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| show(self, **kwargs)
| Show the current Path3D object.
|
| to_2D(self, to_2D: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, check: bool = True) -> tuple['Path2D', numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Check to see if current vectors are all coplanar.
|
| If they are, return a Path2D and a transform which will
| transform the 2D representation back into 3 dimensions
|
| Parameters
| -----------
| to_2D : (4, 4) float
| Homogeneous transformation matrix to apply,
| if not passed a plane will be fitted to vertices.
| normal : (3,) float or None
| Normal of direction of plane to use.
| check
| Raise a ValueError if points aren't coplanar.
|
| Returns
| -----------
| planar
| Current path transformed onto plane
| to_3D : (4, 4) float
| Homeogenous transformations to move planar
| back into the original 3D frame.
|
| to_planar(self, *args, **kwargs)
| DEPRECATED: replace `path.to_planar`->`path.to_2D), removal 1/1/2026
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| convex_hull
| Return a convex hull of the 3D path.
|
| Returns
| --------
| hull : trimesh.Trimesh
| A mesh of the convex hull of the 3D path.
|
| identifier
| Return a simple identifier for the 3D path.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Path:
|
| __add__(self, other)
| Concatenate two Path objects by appending vertices and
| reindexing point references.
|
| Parameters
| -----------
| other: Path object
|
| Returns
| -----------
| concat: Path object, appended from self and other
|
| __hash__(self)
| A hash of the current vertices and entities.
|
| Returns
| ------------
| hash : long int
| Appended hashes
|
| __init__(self, entities: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], collections.abc.Iterable[trimesh.path.entities.Entity], NoneType] = None, vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, metadata: Optional[collections.abc.Mapping] = None, process: bool = True, colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_attributes: Optional[collections.abc.Mapping] = None, **kwargs)
| Instantiate a path object.
|
| Parameters
| -----------
| entities : (m,) trimesh.path.entities.Entity
| Contains geometric entities
| vertices : (n, dimension) float
| The vertices referenced by entities
| metadata : dict
| Any metadata about the path
| process : bool
| Run simple cleanup or not
| colors
| Set any per-entity colors.
| vertex_attributes
| Set any per-vertex array data.
|
| __repr__(self)
| Print a quick summary of the number of vertices and entities.
|
| apply_layer(self, name: str) -> None
| Apply a layer name to every entity in the path.
|
| Parameters
| ------------
| name : str
| Apply layer name to every entity
|
| apply_transform(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> Self
| Apply a transformation matrix to the current path in- place
|
| Parameters
| -----------
| transform : (d+1, d+1) float
| Homogeneous transformations for vertices
|
| convert_units(self, desired: str, guess: bool = False)
| Convert the units of the current drawing in place.
|
| Parameters
| -----------
| desired : str
| Unit system to convert to
| guess : bool
| If True will attempt to guess units
|
| copy(self, layers: Union[str, NoneType, collections.abc.Iterable[Optional[str]]] = None)
| Get a copy of the current mesh
|
| Parameters
| ------------
| layers
| If passed an iterable of layer names which will
| only include those layers in the copy of the path.
|
| Returns
| ---------
| copied : Path object
| Copy of self
|
| explode(self)
| Turn every multi- segment entity into single segment
| entities in- place.
|
| export(self, file_obj=None, file_type=None, **kwargs)
| Export the path to a file object or return data.
|
| Parameters
| ---------------
| file_obj : None, str, or file object
| File object or string to export to
| file_type : None or str
| Type of file: dxf, dict, svg
|
| Returns
| ---------------
| exported : bytes or str
| Exported as specified type
|
| fill_gaps(self, distance=0.025)
| Find vertices without degree 2 and try to connect to
| other vertices. Operations are done in-place.
|
| Parameters
| ----------
| distance : float
| Connect vertices up to this distance
|
| merge_vertices(self, digits=None)
| Merges vertices which are identical and replace references
| by altering `self.entities` and `self.vertices`
|
| Parameters
| --------------
| digits : None, or int
| How many digits to consider when merging vertices
|
| process(self) -> Self
| Apply basic cleaning functions to the Path object in-place.
|
| remove_duplicate_entities(self)
| Remove entities that are duplicated
|
| Notes
| -------
| self.entities: length same or shorter
|
| remove_entities(self, entity_ids)
| Remove entities by index.
|
| Parameters
| -----------
| entity_ids : (n,) int
| Indexes of self.entities to remove
|
| remove_invalid(self)
| Remove entities which declare themselves invalid
|
| Notes
| ----------
| self.entities: shortened
|
| remove_unreferenced_vertices(self)
| Removes all vertices which aren't used by an entity.
|
| Notes
| ---------
| self.vertices : reordered and shortened
| self.entities : entity.points references updated
|
| replace_vertex_references(self, mask)
| Replace the vertex index references in every entity.
|
| Parameters
| ------------
| mask : (len(self.vertices), ) int
| Contains new vertex indexes
|
| Notes
| ------------
| entity.points in self.entities
| Replaced by mask[entity.points]
|
| rezero(self)
| Translate so that every vertex is positive in the current
| mesh is positive.
|
| Returns
| -----------
| matrix : (dimension + 1, dimension + 1) float
| Homogeneous transformations that was applied
| to the current Path object.
|
| scene(self)
| Get a scene object containing the current Path3D object.
|
| Returns
| --------
| scene: trimesh.scene.Scene object containing current path
|
| to_dict(self) -> dict
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Path:
|
| bounds
| Return the axis aligned bounding box of the current path.
|
| Returns
| ----------
| bounds : (2, dimension) float
| AABB with (min, max) coordinates
|
| centroid
| Return the centroid of axis aligned bounding box enclosing
| all entities of the path object.
|
| Returns
| -----------
| centroid : (d,) float
| Approximate centroid of the path
|
| dangling
| List of entities that aren't included in a closed path
|
| Returns
| ----------
| dangling : (n,) int
| Index of self.entities
|
| discrete
| A sequence of connected vertices in space, corresponding to
| self.paths.
|
| Returns
| ---------
| discrete : (len(self.paths),)
| A sequence of (m*, dimension) float
|
| extents
| The size of the axis aligned bounding box.
|
| Returns
| ---------
| extents : (dimension,) float
| Edge length of AABB
|
| identifier_hash
| Return a hash of the identifier.
|
| Returns
| ----------
| hashed : (64,) str
| SHA256 hash of the identifier vector.
|
| is_closed
| Are all entities connected to other entities.
|
| Returns
| -----------
| closed : bool
| Every entity is connected at its ends
|
| is_empty
| Are any entities defined for the current path.
|
| Returns
| ----------
| empty : bool
| True if no entities are defined
|
| kdtree
| A KDTree object holding the vertices of the path.
|
| Returns
| ----------
| kdtree : scipy.spatial.cKDTree
| Object holding self.vertices
|
| layers
| Get a list of the layer for every entity.
|
| Returns
| ---------
| layers : (len(entities), ) any
| Whatever is stored in each `entity.layer`
|
| length
| The total discretized length of every entity.
|
| Returns
| --------
| length : float
| Summed length of every entity
|
| paths
| Sequence of closed paths, encoded by entity index.
|
| Returns
| ---------
| paths : (n,) sequence of (*,) int
| Referencing self.entities
|
| referenced_vertices
| Which vertices are referenced by an entity.
|
| Returns
| -----------
| referenced_vertices: (n,) int, indexes of self.vertices
|
| vertex_graph
| Return a networkx.Graph object for the entity connectivity
|
| graph : networkx.Graph
| Holds vertex indexes
|
| vertex_nodes
| Get a list of which vertex indices are nodes,
| which are either endpoints or points where the
| entity makes a direction change.
|
| Returns
| --------------
| nodes : (n, 2) int
| Indexes of self.vertices which are nodes
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Path:
|
| colors
| Colors are stored per-entity.
|
| Returns
| ------------
| colors : (len(entities), 4) uint8
| RGBA colors for each entity
|
| entities
| The actual entities making up the path.
|
| Returns
| -----------
| entities : (n,) trimesh.path.entities.Entity
| Entities such as Line, Arc, or BSpline curves
|
| vertices
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
DATA
__all__ = ['Path2D', 'Path3D']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\path\__init__.py
trimesh.permutate
Python Library Documentation: module trimesh.permutate in trimesh
NAME
trimesh.permutate
DESCRIPTION
permutate.py
-------------
Randomly deform meshes in different ways.
CLASSES
builtins.object
Permutator
class Permutator(builtins.object)
| Permutator(mesh)
|
| Methods defined here:
|
| __init__(self, mesh)
| A convenience object to get permutated versions of a mesh.
|
| noise(self, magnitude=None)
| Add gaussian noise to every vertex of a mesh, making
| no effort to maintain topology or sanity.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| Input geometry, will not be altered
| magnitude : float
| What is the maximum distance per axis we can displace a vertex.
| If None, value defaults to (mesh.scale / 100.0)
|
| Returns
| ----------
| permutated : trimesh.Trimesh
| Input mesh with noise applied
|
| tessellation(self)
| Subdivide each face of a mesh into three faces with the new vertex
| randomly placed inside the old face.
|
| This produces a mesh with exactly the same surface area and volume
| but with different tessellation.
|
| Parameters
| ------------
| mesh : trimesh.Trimesh
| Input geometry
|
| Returns
| ----------
| permutated : trimesh.Trimesh
| Mesh with remeshed facets
|
| transform(self, translation_scale=1000)
| Return a permutated variant of a mesh by randomly reordering faces
| and rotatating + translating a mesh by a random matrix.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| Mesh, will not be altered by this function
|
| Returns
| ----------
| permutated : trimesh.Trimesh
| Mesh with same faces as input mesh but reordered
| and rigidly transformed in space.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
noise(mesh, magnitude=None)
Add gaussian noise to every vertex of a mesh, making
no effort to maintain topology or sanity.
Parameters
----------
mesh : trimesh.Trimesh
Input geometry, will not be altered
magnitude : float
What is the maximum distance per axis we can displace a vertex.
If None, value defaults to (mesh.scale / 100.0)
Returns
----------
permutated : trimesh.Trimesh
Input mesh with noise applied
tessellation(mesh)
Subdivide each face of a mesh into three faces with the new vertex
randomly placed inside the old face.
This produces a mesh with exactly the same surface area and volume
but with different tessellation.
Parameters
------------
mesh : trimesh.Trimesh
Input geometry
Returns
----------
permutated : trimesh.Trimesh
Mesh with remeshed facets
transform(mesh, translation_scale: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1000.0)
Return a permutated variant of a mesh by randomly reordering faces
and rotatating + translating a mesh by a random matrix.
Parameters
----------
mesh : trimesh.Trimesh
Mesh, will not be altered by this function
Returns
----------
permutated : trimesh.Trimesh
Mesh with same faces as input mesh but reordered
and rigidly transformed in space.
DATA
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\permutate.py
trimesh.points
Python Library Documentation: module trimesh.points in trimesh
NAME
trimesh.points
DESCRIPTION
points.py
-------------
Functions dealing with (n, d) points.
CLASSES
trimesh.parent.Geometry3D(trimesh.parent.Geometry)
PointCloud
class PointCloud(trimesh.parent.Geometry3D)
| PointCloud(vertices, colors=None, metadata=None, **kwargs)
|
| Hold 3D points in an object which can be visualized
| in a scene.
|
| Method resolution order:
| PointCloud
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
|
| __getitem__(self, *args, **kwargs)
|
| __init__(self, vertices, colors=None, metadata=None, **kwargs)
| Load an array of points into a PointCloud object.
|
| Parameters
| -------------
| vertices : (n, 3) float
| Points in space
| colors : (n, 4) uint8 or None
| RGBA colors for each point
| metadata : dict or None
| Metadata about points
|
| __setitem__(self, *args, **kwargs)
|
| apply_transform(self, transform)
| Apply a homogeneous transformation to the PointCloud
| object in- place.
|
| Parameters
| --------------
| transform : (4, 4) float
| Homogeneous transformation to apply to PointCloud
|
| copy(self)
| Safely get a copy of the current point cloud.
|
| Copied objects will have emptied caches to avoid memory
| issues and so may be slow on initial operations until
| caches are regenerated.
|
| Current object will *not* have its cache cleared.
|
| Returns
| ---------
| copied : trimesh.PointCloud
| Copy of current point cloud
|
| export(self, file_obj=None, file_type=None, **kwargs)
| Export the current pointcloud to a file object.
| If file_obj is a filename, file will be written there.
| Supported formats are xyz
| Parameters
| ------------
| file_obj: open writeable file object
| str, file name where to save the pointcloud
| None, if you would like this function to return the export blob
| file_type: str
| Which file type to export as.
| If file name is passed this is not required
|
| hash(self)
| Get a hash of the current vertices.
|
| Returns
| ----------
| hash : str
| Hash of self.vertices
|
| merge_vertices(self)
| Merge vertices closer than tol.merge (default: 1e-8)
|
| query(self, input_points, **kwargs)
| Find the the closest points and associated attributes from this PointCloud.
| Parameters
| ------------
| input_points : (n, 3) float
| Input query points
| kwargs : dict
| Arguments for proximity.query_from_points
| result : proximity.NearestQueryResult
| Result of the query.
|
| scene(self)
| A scene containing just the PointCloud
|
| Returns
| ----------
| scene : trimesh.Scene
| Scene object containing this PointCloud
|
| show(self, **kwargs)
| Open a viewer window displaying the current PointCloud
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| bounds
| The axis aligned bounds of the PointCloud
|
| Returns
| ------------
| bounds : (2, 3) float
| Minimum, Maximum verteex
|
| centroid
| The mean vertex position
|
| Returns
| ------------
| centroid : (3,) float
| Mean vertex position
|
| convex_hull
| A convex hull of every point.
|
| Returns
| -------------
| convex_hull : trimesh.Trimesh
| A watertight mesh of the hull of the points
|
| extents
| The size of the axis aligned bounds
|
| Returns
| ------------
| extents : (3,) float
| Edge length of axis aligned bounding box
|
| identifier
| Return a simple array representing this PointCloud
| that can be used to identify identical arrays.
|
| Returns
| ----------
| identifier : (9,)
| A flat array of data representing the cloud.
|
| identifier_hash
| A hash of the PointCloud's identifier that can be used
| to detect duplicates.
|
| is_empty
| Are there any vertices defined or not.
|
| Returns
| ----------
| empty : bool
| True if no vertices defined
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| moment_inertia
|
| shape
| Get the shape of the pointcloud
|
| Returns
| ----------
| shape : (2,) int
| Shape of vertex array
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| colors
| Stored per- point color
|
| Returns
| ----------
| colors : (len(self.vertices), 4) np.uint8
| Per- point RGBA color
|
| vertices
| Vertices of the PointCloud
|
| Returns
| ------------
| vertices : (n, 3) float
| Points in the PointCloud
|
| weights
| If each point has a specific weight assigned to it.
|
| Returns
| -----------
| weights : (n,)
| A per-vertex weight.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
FUNCTIONS
k_means(points, k, **kwargs)
Find k centroids that attempt to minimize the k- means problem:
https://en.wikipedia.org/wiki/Metric_k-center
Parameters
----------
points: (n, d) float
Points in space
k : int
Number of centroids to compute
**kwargs : dict
Passed directly to scipy.cluster.vq.kmeans
Returns
----------
centroids : (k, d) float
Points in some space
labels: (n) int
Indexes for which points belong to which centroid
major_axis(points)
Returns an approximate vector representing the major
axis of the passed points.
Parameters
-------------
points : (n, dimension) float
Points in space
Returns
-------------
axis : (dimension,) float
Vector along approximate major axis
plane_fit(points)
Fit a plane to points using SVD.
Parameters
---------
points : (n, 3) float or (p, n, 3,) float
3D points in space
Second option allows to simultaneously compute
p centroids and normals
Returns
---------
C : (3,) float or (p, 3,) float
Point on the plane
N : (3,) float or (p, 3,) float
Unit normal vector of plane
plot_points(points, show=True)
Plot an (n, 3) list of points using matplotlib
Parameters
-------------
points : (n, 3) float
Points in space
show : bool
If False, will not show until plt.show() is called
point_plane_distance(points, plane_normal, plane_origin=None)
The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points : (n, 3) float
Points in space
plane_normal : (3,) float
Unit normal vector
plane_origin : (3,) float
Plane origin in space
Returns
------------
distances : (n,) float
Distance from point to plane
project_to_plane(points, plane_normal, plane_origin, transform=None, return_transform=False, return_planar=True)
Project (n, 3) points onto a plane.
Parameters
-----------
points : (n, 3) float
Points in space.
plane_normal : (3,) float
Unit normal vector of plane
plane_origin : (3,)
Origin point of plane
transform : None or (4, 4) float
Homogeneous transform, if specified, normal+origin are overridden
return_transform : bool
Returns the (4, 4) matrix used or not
return_planar : bool
Return (n, 2) points rather than (n, 3) points
radial_sort(points, origin, normal, start=None)
Sorts a set of points radially (by angle) around an
axis specified by origin and normal vector.
Parameters
--------------
points : (n, 3) float
Points in space
origin : (3,) float
Origin to sort around
normal : (3,) float
Vector to sort around
start : (3,) float
Vector to specify start position in counter-clockwise
order viewing in direction of normal, MUST not be
parallel with normal
Returns
--------------
ordered : (n, 3) float
Same as input points but reordered
remove_close(points, radius)
Given an (n, m) array of points return a subset of
points where no point is closer than radius.
Parameters
------------
points : (n, dimension) float
Points in space
radius : float
Minimum radius between result points
Returns
------------
culled : (m, dimension) float
Points in space
mask : (n,) bool
Which points from the original points were returned
sha256 = openssl_sha256(string=b'', *, usedforsecurity=True)
Returns a sha256 hash object; optionally initialized with a string
tsp(points, start=0)
Find an ordering of points where each is visited and
the next point is the closest in euclidean distance,
and if there are multiple points with equal distance
go to an arbitrary one.
Assumes every point is visitable from every other point,
i.e. the travelling salesman problem on a fully connected
graph. It is not a MINIMUM traversal; rather it is a
"not totally goofy traversal, quickly." On random points
this traversal is often ~20x shorter than random ordering,
and executes on 1000 points in around 29ms on a 2014 i7.
Parameters
---------------
points : (n, dimension) float
ND points in space
start : int
The index of points we should start at
Returns
---------------
traversal : (n,) int
Ordered traversal visiting every point
distances : (n - 1,) float
The euclidean distance between points in traversal
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\points.py
trimesh.poses
Python Library Documentation: module trimesh.poses in trimesh
NAME
trimesh.poses
DESCRIPTION
poses.py
-----------
Find stable orientations of meshes.
FUNCTIONS
compute_stable_poses(mesh, center_mass=None, sigma=0.0, n_samples=1, threshold=0.0)
Computes stable orientations of a mesh and their quasi-static probabilities.
This method samples the location of the center of mass from a multivariate
gaussian with the mean at the center of mass, and a covariance
equal to and identity matrix times sigma, over n_samples.
For each sample, it computes the stable resting poses of the mesh on a
a planar workspace and evaluates the probabilities of landing in
each pose if the object is dropped onto the table randomly.
This method returns the 4x4 homogeneous transform matrices that place
the shape against the planar surface with the z-axis pointing upwards
and a list of the probabilities for each pose.
The transforms and probabilities that are returned are sorted, with the
most probable pose first.
Parameters
----------
mesh : trimesh.Trimesh
The target mesh
com : (3,) float
Rhe object center of mass. If None, this method
assumes uniform density and watertightness and
computes a center of mass explicitly
sigma : float
Rhe covariance for the multivariate gaussian used
to sample center of mass locations
n_samples : int
The number of samples of the center of mass location
threshold : float
The probability value at which to threshold
returned stable poses
Returns
-------
transforms : (n, 4, 4) float
The homogeneous matrices that transform the
object to rest in a stable pose, with the
new z-axis pointing upwards from the table
and the object just touching the table.
probs : (n,) float
Probability in (0, 1) for each pose
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\poses.py
trimesh.primitives
Python Library Documentation: module trimesh.primitives in trimesh
NAME
trimesh.primitives
DESCRIPTION
primitives.py
----------------
Subclasses of Trimesh objects that are parameterized as primitives.
Useful because you can move boxes and spheres around
and then use trimesh operations on them at any point.
CLASSES
builtins.object
PrimitiveAttributes
trimesh.base.Trimesh(trimesh.parent.Geometry3D)
Primitive
Box
Capsule
Cylinder
Extrusion
Sphere
class Box(Primitive)
| Box(extents=None, transform=None, bounds=None, mutable=True)
|
| Method resolution order:
| Box
| Primitive
| trimesh.base.Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, extents=None, transform=None, bounds=None, mutable=True)
| Create a Box Primitive as a subclass of Trimesh
|
| Parameters
| ----------
| extents : Optional[ndarray] (3,) float
| Length of each side of the 3D box.
| transform : Optional[ndarray] (4, 4) float
| Homogeneous transformation matrix for box center.
| bounds : Optional[ndarray] (2, 3) float
| Axis aligned bounding box, if passed extents and
| transform will be derived from this.
| mutable : bool
| Are extents and transform mutable after creation.
|
| as_outline(self)
| Return a Path3D containing the outline of the box.
|
| Returns
| -----------
| outline : trimesh.path.Path3D
| Outline of box primitive
|
| sample_grid(self, count=None, step=None)
| Return a 3D grid which is contained by the box.
| Samples are either 'step' distance apart, or there are
| 'count' samples per box side.
|
| Parameters
| -----------
| count : int or (3,) int
| If specified samples are spaced with np.linspace
| step : float or (3,) float
| If specified samples are spaced with np.arange
|
| Returns
| -----------
| grid : (n, 3) float
| Points inside the box
|
| sample_volume(self, count)
| Return random samples from inside the volume of the box.
|
| Parameters
| -------------
| count : int
| Number of samples to return
|
| Returns
| ----------
| samples : (count, 3) float
| Points inside the volume
|
| to_dict(self)
| Get a copy of the current Box primitive as
| a JSON-serializable dict that matches the schema
| in `trimesh/resources/schema/box.schema.json`
|
| Returns
| ----------
| as_dict : dict
| Serializable data for this primitive.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| is_oriented
| Returns whether or not the current box is rotated at all.
|
| transform
| The transform of the Primitive object.
|
| Returns
| -------------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| volume
| Volume of the box Primitive.
|
| Returns
| --------
| volume : float
| Volume of box.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Primitive:
|
| __repr__(self)
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_transform(self, matrix)
| Apply a transform to the current primitive by
| applying a new transform on top of existing
| `self.primitive.transform`. If the matrix
| contains scaling it will change parameters
| like `radius` or `height` automatically.
|
| Parameters
| ------------
| matrix: (4, 4) float
| Homogeneous transformation
|
| copy(self, include_visual=True, **kwargs)
| Return a copy of the Primitive object.
|
| Returns
| -------------
| copied : object
| Copy of current primitive
|
| to_mesh(self, **kwargs)
| Return a copy of the Primitive object as a Trimesh.
|
| Parameters
| -----------
| kwargs : dict
| Passed to the Trimesh object constructor.
|
| Returns
| ------------
| mesh : trimesh.Trimesh
| Tessellated version of the primitive.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Primitive:
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Primitive:
|
| __copy__ = None
|
| __deepcopy__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.base.Trimesh:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.base.Trimesh:
|
| area
| Summed area of all triangles in the current mesh.
|
| Returns
| ---------
| area : float
| Surface area of mesh
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| moment_inertia
| Return the moment of inertia matrix of the current mesh.
| If mesh isn't watertight this is garbage. The returned
| moment of inertia is *axis aligned* at the mesh's center
| of mass `mesh.center_mass`. If you want the moment at any
| other frame including the origin call:
| `mesh.moment_inertia_frame`
|
| Returns
| ---------
| inertia : (3, 3) float
| Moment of inertia of the current mesh at the center of
| mass and aligned with the cartesian axis.
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.base.Trimesh:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
class Capsule(Primitive)
| Capsule(radius=1.0, height=10.0, transform=None, sections=32, mutable=True)
|
| Method resolution order:
| Capsule
| Primitive
| trimesh.base.Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, radius=1.0, height=10.0, transform=None, sections=32, mutable=True)
| Create a Capsule Primitive, a subclass of Trimesh.
|
| Parameters
| ----------
| radius : float
| Radius of cylinder
| height : float
| Height of cylinder
| transform : (4, 4) float
| Transformation matrix
| sections : int
| Number of facets in circle
| mutable : bool
| Are extents and transform mutable after creation.
|
| to_dict(self)
| Get a copy of the current Capsule primitive as
| a JSON-serializable dict that matches the schema
| in `trimesh/resources/schema/capsule.schema.json`
|
| Returns
| ----------
| as_dict : dict
| Serializable data for this primitive.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| The analytic area of the capsule primitive.
|
| Returns
| ---------
| area : float
| Area of the capsule
|
| direction
| The direction of the capsule's axis.
|
| Returns
| --------
| axis : (3,) float
| Vector along the cylinder axis
|
| transform
| The transform of the Primitive object.
|
| Returns
| -------------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| volume
| The analytic volume of the capsule primitive.
|
| Returns
| ---------
| volume : float
| Volume of the capsule
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Primitive:
|
| __repr__(self)
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_transform(self, matrix)
| Apply a transform to the current primitive by
| applying a new transform on top of existing
| `self.primitive.transform`. If the matrix
| contains scaling it will change parameters
| like `radius` or `height` automatically.
|
| Parameters
| ------------
| matrix: (4, 4) float
| Homogeneous transformation
|
| copy(self, include_visual=True, **kwargs)
| Return a copy of the Primitive object.
|
| Returns
| -------------
| copied : object
| Copy of current primitive
|
| to_mesh(self, **kwargs)
| Return a copy of the Primitive object as a Trimesh.
|
| Parameters
| -----------
| kwargs : dict
| Passed to the Trimesh object constructor.
|
| Returns
| ------------
| mesh : trimesh.Trimesh
| Tessellated version of the primitive.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Primitive:
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Primitive:
|
| __copy__ = None
|
| __deepcopy__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.base.Trimesh:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.base.Trimesh:
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| moment_inertia
| Return the moment of inertia matrix of the current mesh.
| If mesh isn't watertight this is garbage. The returned
| moment of inertia is *axis aligned* at the mesh's center
| of mass `mesh.center_mass`. If you want the moment at any
| other frame including the origin call:
| `mesh.moment_inertia_frame`
|
| Returns
| ---------
| inertia : (3, 3) float
| Moment of inertia of the current mesh at the center of
| mass and aligned with the cartesian axis.
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.base.Trimesh:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
class Cylinder(Primitive)
| Cylinder(radius=1.0, height=1.0, transform=None, sections=32, mutable=True)
|
| Method resolution order:
| Cylinder
| Primitive
| trimesh.base.Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, radius=1.0, height=1.0, transform=None, sections=32, mutable=True)
| Create a Cylinder Primitive, a subclass of Trimesh.
|
| Parameters
| -------------
| radius : float
| Radius of cylinder
| height : float
| Height of cylinder
| transform : (4, 4) float
| Homogeneous transformation matrix
| sections : int
| Number of facets in circle.
| mutable : bool
| Are extents and transform mutable after creation.
|
| buffer(self, distance)
| Return a cylinder primitive which covers the source
| cylinder by distance: radius is inflated by distance
| height by twice the distance.
|
| Parameters
| ------------
| distance : float
| Distance to inflate cylinder radius and height
|
| Returns
| -------------
| buffered : Cylinder
| Cylinder primitive inflated by distance
|
| to_dict(self)
| Get a copy of the current Cylinder primitive as
| a JSON-serializable dict that matches the schema
| in `trimesh/resources/schema/cylinder.schema.json`
|
| Returns
| ----------
| as_dict : dict
| Serializable data for this primitive.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| The analytical area of the cylinder primitive
|
| direction
| The direction of the cylinder's axis.
|
| Returns
| --------
| axis: (3,) float, vector along the cylinder axis
|
| moment_inertia
| The analytic inertia tensor of the cylinder primitive.
|
| Returns
| ----------
| tensor: (3, 3) float
| 3D inertia tensor
|
| segment
| A line segment which if inflated by cylinder radius
| would represent the cylinder primitive.
|
| Returns
| -------------
| segment : (2, 3) float
| Points representing a single line segment
|
| volume
| The analytic volume of the cylinder primitive.
|
| Returns
| ---------
| volume : float
| Volume of the cylinder
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Primitive:
|
| __repr__(self)
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_transform(self, matrix)
| Apply a transform to the current primitive by
| applying a new transform on top of existing
| `self.primitive.transform`. If the matrix
| contains scaling it will change parameters
| like `radius` or `height` automatically.
|
| Parameters
| ------------
| matrix: (4, 4) float
| Homogeneous transformation
|
| copy(self, include_visual=True, **kwargs)
| Return a copy of the Primitive object.
|
| Returns
| -------------
| copied : object
| Copy of current primitive
|
| to_mesh(self, **kwargs)
| Return a copy of the Primitive object as a Trimesh.
|
| Parameters
| -----------
| kwargs : dict
| Passed to the Trimesh object constructor.
|
| Returns
| ------------
| mesh : trimesh.Trimesh
| Tessellated version of the primitive.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Primitive:
|
| transform
| The transform of the Primitive object.
|
| Returns
| -------------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Primitive:
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Primitive:
|
| __copy__ = None
|
| __deepcopy__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.base.Trimesh:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.base.Trimesh:
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.base.Trimesh:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
class Extrusion(Primitive)
| Extrusion(polygon=None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, mutable: bool = True, mid_plane: bool = False)
|
| Method resolution order:
| Extrusion
| Primitive
| trimesh.base.Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, polygon=None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, height: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, mutable: bool = True, mid_plane: bool = False)
| Create an Extrusion primitive, which
| is a subclass of Trimesh.
|
| Parameters
| ----------
| polygon : shapely.geometry.Polygon
| Polygon to extrude
| transform : (4, 4) float
| Transform to apply after extrusion
| height : float
| Height to extrude polygon by
| mutable : bool
| Are extents and transform mutable after creation.
|
| buffer(self, distance, distance_height=None, **kwargs)
| Return a new Extrusion object which is expanded in profile
| and in height by a specified distance.
|
| Parameters
| --------------
| distance : float
| Distance to buffer polygon
| distance_height : float
| Distance to buffer above and below extrusion
| kwargs : dict
| Passed to Extrusion constructor
|
| Returns
| ----------
| buffered : primitives.Extrusion
| Extrusion object with new values
|
| slide(self, distance)
| Alter the transform of the current extrusion to slide it
| along its extrude_direction vector
|
| Parameters
| -----------
| distance : float
| Distance along self.extrude_direction to move
|
| to_dict(self)
| Get a copy of the current Extrusion primitive as
| a JSON-serializable dict that matches the schema
| in `trimesh/resources/schema/extrusion.schema.json`
|
| Returns
| ----------
| as_dict : dict
| Serializable data for this primitive.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| The surface area of the primitive extrusion.
|
| Calculated from polygon and height to avoid mesh creation.
|
| Returns
| ----------
| area: float
| Surface area of 3D extrusion
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| direction
| Based on the extrudes transform what is the
| vector along which the polygon will be extruded.
|
| Returns
| ---------
| direction : (3,) float
| Unit direction vector
|
| origin
| Based on the extrude transform what is the
| origin of the plane it is extruded from.
|
| Returns
| -----------
| origin : (3,) float
| Origin of extrusion plane
|
| transform
| The transform of the Primitive object.
|
| Returns
| -------------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| volume
| The volume of the Extrusion primitive.
| Calculated from polygon and height to avoid mesh creation.
|
| Returns
| ----------
| volume : float
| Volume of 3D extrusion
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Primitive:
|
| __repr__(self)
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_transform(self, matrix)
| Apply a transform to the current primitive by
| applying a new transform on top of existing
| `self.primitive.transform`. If the matrix
| contains scaling it will change parameters
| like `radius` or `height` automatically.
|
| Parameters
| ------------
| matrix: (4, 4) float
| Homogeneous transformation
|
| copy(self, include_visual=True, **kwargs)
| Return a copy of the Primitive object.
|
| Returns
| -------------
| copied : object
| Copy of current primitive
|
| to_mesh(self, **kwargs)
| Return a copy of the Primitive object as a Trimesh.
|
| Parameters
| -----------
| kwargs : dict
| Passed to the Trimesh object constructor.
|
| Returns
| ------------
| mesh : trimesh.Trimesh
| Tessellated version of the primitive.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Primitive:
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Primitive:
|
| __copy__ = None
|
| __deepcopy__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.base.Trimesh:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.base.Trimesh:
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| moment_inertia
| Return the moment of inertia matrix of the current mesh.
| If mesh isn't watertight this is garbage. The returned
| moment of inertia is *axis aligned* at the mesh's center
| of mass `mesh.center_mass`. If you want the moment at any
| other frame including the origin call:
| `mesh.moment_inertia_frame`
|
| Returns
| ---------
| inertia : (3, 3) float
| Moment of inertia of the current mesh at the center of
| mass and aligned with the cartesian axis.
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.base.Trimesh:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
class Primitive(trimesh.base.Trimesh)
| Geometric Primitives which are a subclass of Trimesh.
| Mesh is generated lazily when vertices or faces are requested.
|
| Method resolution order:
| Primitive
| trimesh.base.Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self)
| A Trimesh object contains a triangular 3D mesh.
|
| Parameters
| ------------
| vertices : (n, 3) float
| Array of vertex locations
| faces : (m, 3) or (m, 4) int
| Array of triangular or quad faces (triangulated on load)
| face_normals : (m, 3) float
| Array of normal vectors corresponding to faces
| vertex_normals : (n, 3) float
| Array of normal vectors for vertices
| face_colors : (n, 3|4) uint8
| Array of colors for faces
| vertex_colors : (n, 3|4) uint8
| Array of colors for vertices
| face_attributes : dict
| Attributes corresponding to faces
| vertex_attributes : dict
| Attributes corresponding to vertices
| metadata : dict
| Any metadata about the mesh
| process : bool
| if True, Nan and Inf values will be removed
| immediately and vertices will be merged
| validate : bool
| If True, degenerate and duplicate faces will be
| removed immediately, and some functions will alter
| the mesh to ensure consistent results.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| use_embree : bool
| If True try to use pyembree raytracer.
| If pyembree is not available it will automatically fall
| back to a much slower rtree/numpy implementation
| initial_cache : dict
| A way to pass things to the cache in case expensive
| things were calculated before creating the mesh object.
| visual : ColorVisuals or TextureVisuals
| Assigned to self.visual
|
| __repr__(self)
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_transform(self, matrix)
| Apply a transform to the current primitive by
| applying a new transform on top of existing
| `self.primitive.transform`. If the matrix
| contains scaling it will change parameters
| like `radius` or `height` automatically.
|
| Parameters
| ------------
| matrix: (4, 4) float
| Homogeneous transformation
|
| copy(self, include_visual=True, **kwargs)
| Return a copy of the Primitive object.
|
| Returns
| -------------
| copied : object
| Copy of current primitive
|
| to_dict(self)
| Should be implemented by each primitive.
|
| to_mesh(self, **kwargs)
| Return a copy of the Primitive object as a Trimesh.
|
| Parameters
| -----------
| kwargs : dict
| Passed to the Trimesh object constructor.
|
| Returns
| ------------
| mesh : trimesh.Trimesh
| Tessellated version of the primitive.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| transform
| The transform of the Primitive object.
|
| Returns
| -------------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'to_dict'})
|
| __annotations__ = {}
|
| __copy__ = None
|
| __deepcopy__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.base.Trimesh:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.base.Trimesh:
|
| area
| Summed area of all triangles in the current mesh.
|
| Returns
| ---------
| area : float
| Surface area of mesh
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| moment_inertia
| Return the moment of inertia matrix of the current mesh.
| If mesh isn't watertight this is garbage. The returned
| moment of inertia is *axis aligned* at the mesh's center
| of mass `mesh.center_mass`. If you want the moment at any
| other frame including the origin call:
| `mesh.moment_inertia_frame`
|
| Returns
| ---------
| inertia : (3, 3) float
| Moment of inertia of the current mesh at the center of
| mass and aligned with the cartesian axis.
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| volume
| Volume of the current mesh calculated using a surface
| integral. If the current mesh isn't watertight this is
| garbage.
|
| Returns
| ---------
| volume : float
| Volume of the current mesh
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.base.Trimesh:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
class PrimitiveAttributes(builtins.object)
| PrimitiveAttributes(parent, defaults, kwargs, mutable=True)
|
| Methods defined here:
|
| __dir__(self)
| Default dir() implementation.
|
| __getattr__(self, key)
|
| __init__(self, parent, defaults, kwargs, mutable=True)
| Hold the attributes for a Primitive.
|
| Parameters
| ------------
| parent : Primitive
| Parent object reference.
| defaults : dict
| The default values for this primitive type.
| kwargs : dict
| User-passed values, i.e. {'radius': 10.0}
|
| __setattr__(self, key, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Sphere(Primitive)
| Sphere(radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, center: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, subdivisions: Union[int, numpy.integer, numpy.unsignedinteger] = 3, mutable: bool = True)
|
| Method resolution order:
| Sphere
| Primitive
| trimesh.base.Trimesh
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger] = 1.0, center: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, subdivisions: Union[int, numpy.integer, numpy.unsignedinteger] = 3, mutable: bool = True)
| Create a Sphere Primitive, a subclass of Trimesh.
|
| Parameters
| ----------
| radius
| Radius of sphere
| center : None or (3,) float
| Center of sphere.
| transform : None or (4, 4) float
| Full homogeneous transform. Pass `center` OR `transform.
| subdivisions
| Number of subdivisions for icosphere.
| mutable
| Are extents and transform mutable after creation.
|
| to_dict(self)
| Get a copy of the current Sphere primitive as
| a JSON-serializable dict that matches the schema
| in `trimesh/resources/schema/sphere.schema.json`
|
| Returns
| ----------
| as_dict : dict
| Serializable data for this primitive.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| Surface area of the current sphere primitive.
|
| Returns
| --------
| area: float, surface area of the sphere Primitive
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounds
| The axis aligned bounds of the faces of the mesh.
|
| Returns
| -----------
| bounds : (2, 3) float or None
| Bounding box with [min, max] coordinates
| If mesh is empty will return None
|
| moment_inertia
| The analytic inertia tensor of the sphere primitive.
|
| Returns
| ----------
| tensor: (3, 3) float
| 3D inertia tensor.
|
| volume
| Volume of the current sphere primitive.
|
| Returns
| --------
| volume: float, volume of the sphere Primitive
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| center
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Primitive:
|
| __repr__(self)
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_transform(self, matrix)
| Apply a transform to the current primitive by
| applying a new transform on top of existing
| `self.primitive.transform`. If the matrix
| contains scaling it will change parameters
| like `radius` or `height` automatically.
|
| Parameters
| ------------
| matrix: (4, 4) float
| Homogeneous transformation
|
| copy(self, include_visual=True, **kwargs)
| Return a copy of the Primitive object.
|
| Returns
| -------------
| copied : object
| Copy of current primitive
|
| to_mesh(self, **kwargs)
| Return a copy of the Primitive object as a Trimesh.
|
| Parameters
| -----------
| kwargs : dict
| Passed to the Trimesh object constructor.
|
| Returns
| ------------
| mesh : trimesh.Trimesh
| Tessellated version of the primitive.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Primitive:
|
| transform
| The transform of the Primitive object.
|
| Returns
| -------------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Primitive:
|
| face_normals
| Return the unit normal vector for each face.
|
| If a face is degenerate and a normal can't be generated
| a zero magnitude unit vector will be returned for that face.
|
| Returns
| -----------
| normals : (len(self.faces), 3) float64
| Normal vectors of each face
|
| faces
| The faces of the mesh.
|
| This is regarded as core information which cannot be
| regenerated from cache and as such is stored in
| `self._data` which tracks the array for changes and
| clears cached values of the mesh altered.
|
| Returns
| ----------
| faces : (n, 3) int64
| References for `self.vertices` for triangles.
|
| vertices
| The vertices of the mesh.
|
| This is regarded as core information which cannot be
| generated from cache and as such is stored in self._data
| which tracks the array for changes and clears cached
| values of the mesh if this is altered.
|
| Returns
| ----------
| vertices : (n, 3) float
| Points in cartesian space referenced by self.faces
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Primitive:
|
| __copy__ = None
|
| __deepcopy__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.base.Trimesh:
|
| __add__(self, other: 'Trimesh') -> 'Trimesh'
| Concatenate the mesh with another mesh.
|
| Parameters
| ------------
| other : trimesh.Trimesh object
| Mesh to be concatenated with self
|
| Returns
| ----------
| concat : trimesh.Trimesh
| Mesh object of combined result
|
| compute_stable_poses(self, center_mass: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None, sigma: Union[float, numpy.floating] = 0.0, n_samples: Union[int, numpy.integer, numpy.unsignedinteger] = 1, threshold: Union[float, numpy.floating] = 0.0) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]]
| Computes stable orientations of a mesh and their quasi-static probabilities.
|
| This method samples the location of the center of mass from a multivariate
| gaussian (mean at com, cov equal to identity times sigma) over n_samples.
| For each sample, it computes the stable resting poses of the mesh on a
| a planar workspace and evaluates the probabilities of landing in
| each pose if the object is dropped onto the table randomly.
|
| This method returns the 4x4 homogeneous transform matrices that place
| the shape against the planar surface with the z-axis pointing upwards
| and a list of the probabilities for each pose.
| The transforms and probabilities that are returned are sorted, with the
| most probable pose first.
|
| Parameters
| ------------
| center_mass : (3, ) float
| The object center of mass (if None, this method
| assumes uniform density and watertightness and
| computes a center of mass explicitly)
| sigma : float
| The covariance for the multivariate gaussian used
| to sample center of mass locations
| n_samples : int
| The number of samples of the center of mass location
| threshold : float
| The probability value at which to threshold
| returned stable poses
|
| Returns
| -------
| transforms : (n, 4, 4) float
| The homogeneous matrices that transform the
| object to rest in a stable pose, with the
| new z-axis pointing upwards from the table
| and the object just touching the table.
|
| probs : (n, ) float
| A probability ranging from 0.0 to 1.0 for each pose
|
| contains(self, points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Given an array of points determine whether or not they
| are inside the mesh. This raises an error if called on a
| non-watertight mesh.
|
| Parameters
| ------------
| points : (n, 3) float
| Points in cartesian space
|
| Returns
| ---------
| contains : (n, ) bool
| Whether or not each point is inside the mesh
|
| convert_units(self, desired: str, guess: bool = False) -> Self
| Convert the units of the mesh into a specified unit.
|
| Parameters
| ------------
| desired : string
| Units to convert to (eg 'inches')
| guess : boolean
| If self.units are not defined should we
| guess the current units of the document and then convert?
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| convex_decomposition(self, **kwargs) -> list['Trimesh']
| Compute an approximate convex decomposition of a mesh
| using `pip install pyVHACD`.
|
| Returns
| -------
| meshes
| List of convex meshes that approximate the original
| **kwargs : VHACD keyword arguments
|
| difference(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean difference between this mesh and other meshes.
|
| Parameters
| ------------
| other
| One or more meshes to difference with the current mesh.
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| difference : trimesh.Trimesh
| Difference between self and other Trimesh objects
|
| eval_cached(self, statement: str, *args) -> Any
| Evaluate a statement and cache the result before returning.
|
| Statements are evaluated inside the Trimesh object, and
|
| Parameters
| ------------
| statement : str
| Statement of valid python code
| *args : list
| Available inside statement as args[0], etc
|
| Returns
| -----------
| result : result of running eval on statement with args
|
| Examples
| -----------
| r = mesh.eval_cached('np.dot(self.vertices, args[0])', [0, 0, 1])
|
| export(self, file_obj: Union[str, pathlib.Path, IO, _io.BytesIO, _io.StringIO, BinaryIO, TextIO, _io.BufferedRandom, dict, NoneType] = None, file_type: Optional[str] = None, **kwargs) -> Union[dict, bytes, str]
| Export the current mesh to a file object.
| If file_obj is a filename, file will be written there.
|
| Supported formats are stl, off, ply, collada, json,
| dict, glb, dict64, msgpack.
|
| Parameters
| ------------
| file_obj : open writeable file object
| str, file name where to save the mesh
| None, return the export blob
| file_type : str
| Which file type to export as, if `file_name`
| is passed this is not required.
|
| Returns
| ----------
| exported : bytes or str
| Result of exporter
|
| extend_faces(self, new_faces: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Extend `mesh.faces` in-place with new triangles.
|
| This does substantial bookkeeping: padding face colors
| and face attributes with default values, and preserving cached
| face normals to avoid recomputing every normal.
|
| Parameters
| ------------
| new_faces : (n, 3) integer
| The new faces as indexes of `self.vertices`
|
| fill_holes(self) -> bool
| Fill single triangle and single quad holes in the current mesh.
|
| Returns
| ----------
| watertight : bool
| Is the mesh watertight after the function completes
|
| fix_normals(self, multibody: Optional[bool] = None) -> Self
| Find and fix problems with self.face_normals and self.faces
| winding direction.
|
| For face normals ensure that vectors are consistently pointed
| outwards, and that self.faces is wound in the correct direction
| for all connected components.
|
| Parameters
| -------------
| multibody : None or bool
| Fix normals across multiple bodies or if unspecified
| check the current `Trimesh.body_count`.
|
| intersection(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean intersection between this mesh and other meshes.
|
| Parameters
| ------------
| other : trimesh.Trimesh, or list of trimesh.Trimesh objects
| Meshes to calculate intersections with
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| intersection : trimesh.Trimesh
| Mesh of the volume contained by all passed meshes
|
| invert(self) -> Self
| Invert the mesh in-place by reversing the winding of every
| face and negating normals without dumping the cache.
|
| Alters `self.faces` by reversing columns, and negating
| `self.face_normals` and `self.vertex_normals`.
|
| merge_vertices(self, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None, digits_vertex: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_norm: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, digits_uv: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Removes duplicate vertices grouped by position and
| optionally texture coordinate and normal.
|
| Parameters
| -------------
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
| digits_vertex : None or int
| Number of digits to consider for vertex position
| digits_norm : int
| Number of digits to consider for unit normals
| digits_uv : int
| Number of digits to consider for UV coordinates
|
| moment_inertia_frame(self, transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Get the moment of inertia of this mesh with respect to
| an arbitrary frame, versus with respect to the center
| of mass as returned by `mesh.moment_inertia`.
|
| For example if `transform` is an identity matrix `np.eye(4)`
| this will give the moment at the origin.
|
| Uses the parallel axis theorum to move the center mass
| tensor to this arbitrary frame.
|
| Parameters
| ------------
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3)
| Moment of inertia in the requested frame.
|
| nondegenerate_faces(self, height: Union[float, numpy.floating] = 1e-08) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| Identify degenerate faces (faces without 3 unique vertex indices)
| in the current mesh.
|
| Usage example for removing them:
| `mesh.update_faces(mesh.nondegenerate_faces())`
|
| If a height is specified, it will identify any face with a 2D oriented
| bounding box with one edge shorter than that height.
|
| If not specified, it will identify any face with a zero normal.
|
| Parameters
| ------------
| height : float
| If specified identifies faces with an oriented bounding
| box shorter than this on one side.
|
| Returns
| -------------
| nondegenerate : (len(self.faces), ) bool
| Mask that can be used to remove faces
|
| outline(self, face_ids: Optional[numpy.ndarray[Any, numpy.dtype[numpy.int64]]] = None, **kwargs) -> trimesh.path.path.Path3D
| Given a list of face indexes find the outline of those
| faces and return it as a Path3D.
|
| The outline is defined here as every edge which is only
| included by a single triangle.
|
| Note that this implies a non-watertight mesh as the
| outline of a watertight mesh is an empty path.
|
| Parameters
| ------------
| face_ids : (n, ) int
| Indices to compute the outline of.
| If None, outline of full mesh will be computed.
| **kwargs: passed to Path3D constructor
|
| Returns
| ----------
| path : Path3D
| Curve in 3D of the outline
|
| process(self, validate: bool = False, merge_tex: Optional[bool] = None, merge_norm: Optional[bool] = None) -> Self
| Do processing to make a mesh useful.
|
| Does this by:
| 1) removing NaN and Inf values
| 2) merging duplicate vertices
| If validate:
| 3) Remove triangles which have one edge
| of their 2D oriented bounding box
| shorter than tol.merge
| 4) remove duplicated triangles
| 5) Attempt to ensure triangles are consistently wound
| and normals face outwards.
|
| Parameters
| ------------
| validate : bool
| Remove degenerate and duplicate faces.
| merge_tex : bool
| If True textured meshes with UV coordinates will
| have vertices merged regardless of UV coordinates
| merge_norm : bool
| If True, meshes with vertex normals will have
| vertices merged ignoring different normals
|
| Returns
| ------------
| self: trimesh.Trimesh
| Current mesh
|
| projected(self, normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> trimesh.path.path.Path2D
| Project a mesh onto a plane and then extract the
| polygon that outlines the mesh projection on that
| plane.
|
| Parameters
| ----------
| normal : (3,) float
| Normal to extract flat pattern along
| origin : None or (3,) float
| Origin of plane to project mesh onto
| ignore_sign : bool
| Allow a projection from the normal vector in
| either direction: this provides a substantial speedup
| on watertight meshes where the direction is irrelevant
| but if you have a triangle soup and want to discard
| backfaces you should set this to False.
| rpad : float
| Proportion to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| apad : float
| Absolute padding to pad polygons by before unioning
| and then de-padding result by to avoid zero-width gaps.
| tol_dot : float
| Tolerance for discarding on-edge triangles.
| precise : bool
| Use the precise projection computation using shapely.
| precise_eps : float
| Tolerance for precise triangle checks.
|
| Returns
| ----------
| projected : trimesh.path.Path2D
| Outline of source mesh
|
| register(self, other: Union[trimesh.parent.Geometry3D, numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]], **kwargs) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.float64]
| Align a mesh with another mesh or a PointCloud using
| the principal axes of inertia as a starting point which
| is refined by iterative closest point.
|
| Parameters
| ------------
| other : trimesh.Trimesh or (n, 3) float
| Mesh or points in space
| samples : int
| Number of samples from mesh surface to align
| icp_first : int
| How many ICP iterations for the 9 possible
| combinations of
| icp_final : int
| How many ICP itertations for the closest
| candidate from the wider search
|
| Returns
| -----------
| mesh_to_other : (4, 4) float
| Transform to align mesh to the other object
| cost : float
| Average square distance per point
|
| remove_infinite_values(self) -> None
| Ensure that every vertex and face consists of finite numbers.
| This will remove vertices or faces containing np.nan and np.inf
|
| Alters `self.faces` and `self.vertices`
|
| remove_unreferenced_vertices(self) -> None
| Remove all vertices in the current mesh which are not
| referenced by a face.
|
| rezero(self) -> None
| Translate the mesh so that all vertex vertices are positive
| and the lower bound of `self.bounds` will be exactly zero.
|
| Alters `self.vertices`.
|
| sample(self, count: Union[int, numpy.integer, numpy.unsignedinteger], return_index: bool = False, face_weight: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
| Return random samples distributed across the
| surface of the mesh
|
| Parameters
| ------------
| count : int
| Number of points to sample
| return_index : bool
| If True will also return the index of which face each
| sample was taken from.
| face_weight : None or len(mesh.faces) float
| Weight faces by a factor other than face area.
| If None will be the same as face_weight=mesh.area
|
| Returns
| ---------
| samples : (count, 3) float
| Points on surface of mesh
| face_index : (count, ) int
| Index of self.faces
|
| scene(self, **kwargs) -> trimesh.scene.scene.Scene
| Returns a Scene object containing the current mesh.
|
| Returns
| ---------
| scene : trimesh.scene.scene.Scene
| Contains just the current mesh
|
| section(self, plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], **kwargs) -> Optional[trimesh.path.path.Path3D]
| Returns a 3D cross section of the current mesh and a plane
| defined by origin and normal.
|
| Parameters
| ------------
| plane_normal : (3,) float
| Normal vector of section plane.
| plane_origin : (3, ) float
| Point on the cross section plane.
|
| Returns
| ---------
| intersections
| Curve of intersection or None if it was not hit by plane.
|
| section_multiplane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], heights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> list[typing.Optional[trimesh.path.path.Path2D]]
| Return multiple parallel cross sections of the current
| mesh in 2D.
|
| Parameters
| ------------
| plane_origin : (3, ) float
| Point on the cross section plane
| plane_normal : (3) float
| Normal vector of section plane
| heights : (n, ) float
| Each section is offset by height along
| the plane normal.
|
| Returns
| ---------
| paths : (n, ) Path2D or None
| 2D cross sections at specified heights.
| path.metadata['to_3D'] contains transform
| to return 2D section back into 3D space.
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs) -> trimesh.scene.scene.Scene
| Render the mesh in an opengl window. Requires pyglet.
|
| Parameters
| ------------
| viewer : ViewerType
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| smooth : bool
| Run smooth shading on mesh or not,
| large meshes will be slow
|
| Returns
| -----------
| scene : trimesh.scene.Scene
| Scene with current mesh in it
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| A thin wrapper around `pip install fast-simplification`.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| Returns
| ---------
| simple : trimesh.Trimesh
| Simplified version of mesh.
|
| slice_plane(self, plane_origin: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], plane_normal: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], cap: bool = False, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, **kwargs) -> 'Trimesh'
| Slice the mesh with a plane, returning a new mesh that is the
| portion of the original mesh to the positive normal side of the plane
|
| plane_origin : (3,) float
| Point on plane to intersect with mesh
| plane_normal : (3,) float
| Normal vector of plane to intersect with mesh
| cap : bool
| If True, cap the result with a triangulated polygon
| face_index : ((m,) int)
| Indexes of mesh.faces to slice. When no mask is
| provided, the default is to slice all faces.
|
| Returns
| ---------
| new_mesh: trimesh.Trimesh or None
| Subset of current mesh that intersects the half plane
| to the positive normal side of the plane
|
| split(self, **kwargs) -> list['Trimesh']
| Split a mesh into multiple meshes from face
| connectivity.
|
| If only_watertight is true it will only return
| watertight meshes and will attempt to repair
| single triangle or quad holes.
|
| Parameters
| ----------
| mesh : trimesh.Trimesh
| The source multibody mesh to split
| only_watertight
| Only return watertight components and discard
| any connected component that isn't fully watertight.
| repair
| If set try to fill small holes in a mesh, before the
| discard step in `only_watertight.
| adjacency : (n, 2) int
| If passed will be used instead of `mesh.face_adjacency`
| engine
| Which graph engine to use for the connected components.
| kwargs
| Will be passed to `mesh.submesh`
|
| Returns
| ----------
| meshes : (m,) trimesh.Trimesh
| Results of splitting based on parameters.
|
| subdivide(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh with each subdivided face replaced
| with four smaller faces. Will return a copy of current
| mesh with subdivided faces.
|
| Parameters
| ------------
| face_index : (m, ) int or None
| If None all faces of mesh will be subdivided
| If (m, ) int array of indices: only specified faces will be
| subdivided. Note that in this case the mesh will generally
| no longer be manifold, as the additional vertex on the midpoint
| will not be used by the adjacent faces to the faces specified,
| and an additional postprocessing step will be required to
| make resulting mesh watertight
| iterations : int
| If passed will run subdivisions multiple times recursively.
| NOT COMPATIBLE with `face_index` and will raise a `ValueError`
| if both arguments are passed.
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_loop(self, iterations: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> 'Trimesh'
| Subdivide a mesh by dividing each triangle into four
| triangles and approximating their smoothed surface
| using loop subdivision. Loop subdivision often looks
| better on triangular meshes than catmul-clark, which
| operates primarily on quads.
|
| Parameters
| ------------
| iterations : int
| Number of iterations to run subdivision.
| multibody : bool
| If True will try to subdivide for each submesh
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| subdivide_to_size(self, max_edge: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger], max_iter: Union[int, numpy.integer, numpy.unsignedinteger] = 10, return_index: bool = False) -> Union[ForwardRef('Trimesh'), tuple['Trimesh', numpy.ndarray[Any, numpy.dtype[numpy.int64]]]]
| Subdivide a mesh until every edge is shorter than a
| specified length.
|
| Will return a triangle soup, not a nicely structured mesh.
|
| Parameters
| ------------
| max_edge
| Maximum length of any edge in the result
| max_iter : int
| The maximum number of times to run subdivision
| return_index : bool
| If True, return index of original face for new faces
|
| Returns
| ------------
| mesh: trimesh.Trimesh
| The copy of current mesh with subdivided faces.
|
| submesh(self, faces_sequence: collections.abc.Sequence[typing.Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]], only_watertight: bool = False, repair: bool = False, **kwargs) -> Union[ForwardRef('Trimesh'), list['Trimesh']]
| Return a subset of the mesh.
|
| Parameters
| ------------
| faces_sequence : sequence (m, ) int
| Face indices of mesh
| only_watertight : bool
| Only return submeshes which are watertight
| repair
| Try to repair the submesh if it is not watertight
| append : bool
| Return a single mesh which has the faces appended.
| if this flag is set, only_watertight is ignored
|
| Returns
| ---------
| submesh : Trimesh or (n,) Trimesh
| Single mesh if `append` or list of submeshes
|
| union(self, other: Union[ForwardRef('Trimesh'), collections.abc.Sequence['Trimesh']], engine: Literal['manifold', 'blender', None] = None, check_volume: bool = True, **kwargs) -> 'Trimesh'
| Boolean union between this mesh and other meshes.
|
| Parameters
| ------------
| other : Trimesh or (n, ) Trimesh
| Other meshes to union
| engine
| Which backend to use, the default
| recommendation is: `pip install manifold3d`.
| check_volume
| Raise an error if not all meshes are watertight
| positive volumes. Advanced users may want to ignore
| this check as it is expensive.
| kwargs
| Passed through to the `engine`.
|
| Returns
| ---------
| union : trimesh.Trimesh
| Union of self and other Trimesh objects
|
| unique_faces(self) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.bool]]
| On the current mesh find which faces are unique.
|
| Returns
| --------
| unique : (len(faces),) bool
| A mask where the first occurrence of a unique face is true.
|
| unmerge_vertices(self) -> None
| Removes all face references so that every face contains
| three unique vertex indices and no faces are adjacent.
|
| unwrap(self, image: <module 'PIL.Image' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\PIL\\Image.py'> = None) -> 'Trimesh'
| Returns a Trimesh object equivalent to the current mesh where
| the vertices have been assigned uv texture coordinates. Vertices
| may be split into as many as necessary by the unwrapping
| algorithm, depending on how many uv maps they appear in.
|
| Requires `pip install xatlas`
|
| Parameters
| ------------
| image : None or PIL.Image
| Image to assign to the material
|
| Returns
| --------
| unwrapped : trimesh.Trimesh
| Mesh with unwrapped uv coordinates
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> None
| In many cases, we will want to remove specific faces.
| However, there is additional bookkeeping to do this cleanly.
| This function updates the set of faces with a validity mask,
| as well as keeping track of normals and colors.
|
| Parameters
| ------------
| mask : (m) int or (len(self.faces)) bool
| Mask to remove faces
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], inverse: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> None
| Update vertices with a mask.
|
| Parameters
| ------------
| mask : (len(self.vertices)) bool
| Array of which vertices to keep
| inverse : (len(self.vertices)) int
| Array to reconstruct vertex references
| such as output by np.unique
|
| voxelized(self, pitch: Union[float, numpy.floating, NoneType], method: str = 'subdivide', **kwargs)
| Return a VoxelGrid object representing the current mesh
| discretized into voxels at the specified pitch
|
| Parameters
| ------------
| pitch : float
| The edge length of a single voxel
| method: implementation key. See `trimesh.voxel.creation.voxelizers`
| **kwargs: additional kwargs passed to the specified implementation.
|
| Returns
| ----------
| voxelized : VoxelGrid object
| Representing the current mesh
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.base.Trimesh:
|
| area_faces
| The area of each face in the mesh.
|
| Returns
| ---------
| area_faces : (n, ) float
| Area of each face
|
| body_count
| How many connected groups of vertices exist in this mesh.
| Note that this number may differ from result in mesh.split,
| which is calculated from FACE rather than vertex adjacency.
|
| Returns
| -----------
| count : int
| Number of connected vertex groups
|
| centroid
| The point in space which is the average of the triangle
| centroids weighted by the area of each triangle.
|
| This will be valid even for non-watertight meshes,
| unlike self.center_mass
|
| Returns
| ----------
| centroid : (3, ) float
| The average vertex weighted by face area
|
| convex_hull
| Returns a Trimesh object representing the convex hull of
| the current mesh.
|
| Returns
| --------
| convex : trimesh.Trimesh
| Mesh of convex hull of current mesh
|
| edges
| Edges of the mesh (derived from faces).
|
| Returns
| ---------
| edges : (n, 2) int
| List of vertex indices making up edges
|
| edges_face
| Which face does each edge belong to.
|
| Returns
| ---------
| edges_face : (n, ) int
| Index of self.faces
|
| edges_sorted
| Edges sorted along axis 1
|
| Returns
| ----------
| edges_sorted : (n, 2)
| Same as self.edges but sorted along axis 1
|
| edges_sorted_tree
| A KDTree for mapping edges back to edge index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with edges will return
| their index in mesh.edges_sorted
|
| edges_sparse
| Edges in sparse bool COO graph format where connected
| vertices are True.
|
| Returns
| ----------
| sparse: (len(self.vertices), len(self.vertices)) bool
| Sparse graph in COO format
|
| edges_unique
| The unique edges of the mesh.
|
| Returns
| ----------
| edges_unique : (n, 2) int
| Vertex indices for unique edges
|
| edges_unique_inverse
| Return the inverse required to reproduce
| self.edges_sorted from self.edges_unique.
|
| Useful for referencing edge properties:
| mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted
|
| Returns
| ----------
| inverse : (len(self.edges), ) int
| Indexes of self.edges_unique
|
| edges_unique_length
| How long is each unique edge.
|
| Returns
| ----------
| length : (len(self.edges_unique), ) float
| Length of each unique edge
|
| euler_number
| Return the Euler characteristic (a topological invariant) for the mesh
| In order to guarantee correctness, this should be called after
| remove_unreferenced_vertices
|
| Returns
| ----------
| euler_number : int
| Topological invariant
|
| extents
| The length, width, and height of the axis aligned
| bounding box of the mesh.
|
| Returns
| -----------
| extents : (3, ) float or None
| Array containing axis aligned [length, width, height]
| If mesh is empty returns None
|
| face_adjacency
| Find faces that share an edge i.e. 'adjacent' faces.
|
| Returns
| ----------
| adjacency : (n, 2) int
| Pairs of faces which share an edge
|
| Examples
| ---------
|
| In [1]: mesh = trimesh.load('models/featuretype.STL')
|
| In [2]: mesh.face_adjacency
| Out[2]:
| array([[ 0, 1],
| [ 2, 3],
| [ 0, 3],
| ...,
| [1112, 949],
| [3467, 3475],
| [1113, 3475]])
|
| In [3]: mesh.faces[mesh.face_adjacency[0]]
| Out[3]:
| TrackedArray([[ 1, 0, 408],
| [1239, 0, 1]], dtype=int64)
|
| In [4]: import networkx as nx
|
| In [5]: graph = nx.from_edgelist(mesh.face_adjacency)
|
| In [6]: groups = nx.connected_components(graph)
|
| face_adjacency_angles
| Return the unsigned angle between adjacent faces
| in radians.
|
| Note that if you want a signed angle you can easily
| use the `face_adjacency_convex` attribute to get a
| signed angle with advanced indexing:
|
| ```
| # get a sign per face_adacency pair from the "is it convex" boolean
| signs = np.array([-1.0, 1.0])[mesh.face_adjacency_convex.astype(np.int64)]
|
| # apply the signs to the angles
| angles = mesh.face_adjacency_angles * signs
| ```
|
| Returns
| --------
| adjacency_angle : (len(self.face_adjacency), ) float
| Unsigned angle between adjacent faces
| corresponding with `self.face_adjacency`
|
| face_adjacency_convex
| Return faces which are adjacent and locally convex.
|
| What this means is that given faces A and B, the one vertex
| in B that is not shared with A, projected onto the plane of A
| has a projection that is zero or negative.
|
| Returns
| ----------
| are_convex : (len(self.face_adjacency), ) bool
| Face pairs that are locally convex
|
| face_adjacency_edges
| Returns the edges that are shared by the adjacent faces.
|
| Returns
| --------
| edges : (n, 2) int
| Vertex indices which correspond to face_adjacency
|
| face_adjacency_edges_tree
| A KDTree for mapping edges back face adjacency index.
|
| Returns
| ------------
| tree : scipy.spatial.cKDTree
| Tree when queried with SORTED edges will return
| their index in mesh.face_adjacency
|
| face_adjacency_projections
| The projection of the non-shared vertex of a triangle onto
| its adjacent face
|
| Returns
| ----------
| projections : (len(self.face_adjacency), ) float
| Dot product of vertex
| onto plane of adjacent triangle.
|
| face_adjacency_radius
| The approximate radius of a cylinder that fits inside adjacent faces.
|
| Returns
| ------------
| radii : (len(self.face_adjacency), ) float
| Approximate radius formed by triangle pair
|
| face_adjacency_span
| The approximate perpendicular projection of the non-shared
| vertices in a pair of adjacent faces onto the shared edge of
| the two faces.
|
| Returns
| ------------
| span : (len(self.face_adjacency), ) float
| Approximate span between the non-shared vertices
|
| face_adjacency_tree
| An R-tree of face adjacencies.
|
| Returns
| --------
| tree
| Where each edge in self.face_adjacency has a
| rectangular cell
|
| face_adjacency_unshared
| Return the vertex index of the two vertices not in the shared
| edge between two adjacent faces
|
| Returns
| -----------
| vid_unshared : (len(mesh.face_adjacency), 2) int
| Indexes of mesh.vertices
|
| face_angles
| Returns the angle at each vertex of a face.
|
| Returns
| --------
| angles : (len(self.faces), 3) float
| Angle at each vertex of a face
|
| face_angles_sparse
| A sparse matrix representation of the face angles.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Float sparse matrix with with shape:
| (len(self.vertices), len(self.faces))
|
| face_neighborhood
| Find faces that share a vertex i.e. 'neighbors' faces.
|
| Returns
| ----------
| neighborhood : (n, 2) int
| Pairs of faces which share a vertex
|
| faces_sparse
| A sparse matrix representation of the faces.
|
| Returns
| ----------
| sparse : scipy.sparse.coo_matrix
| Has properties:
| dtype : bool
| shape : (len(self.vertices), len(self.faces))
|
| faces_unique_edges
| For each face return which indexes in mesh.unique_edges constructs
| that face.
|
| Returns
| ---------
| faces_unique_edges : (len(self.faces), 3) int
| Indexes of self.edges_unique that
| construct self.faces
|
| Examples
| ---------
| In [0]: mesh.faces[:2]
| Out[0]:
| TrackedArray([[ 1, 6946, 24224],
| [ 6946, 1727, 24225]])
|
| In [1]: mesh.edges_unique[mesh.faces_unique_edges[:2]]
| Out[1]:
| array([[[ 1, 6946],
| [ 6946, 24224],
| [ 1, 24224]],
| [[ 1727, 6946],
| [ 1727, 24225],
| [ 6946, 24225]]])
|
| facets
| Return a list of face indices for coplanar adjacent faces.
|
| Returns
| ---------
| facets : (n, ) sequence of (m, ) int
| Groups of indexes of self.faces
|
| facets_area
| Return an array containing the area of each facet.
|
| Returns
| ---------
| area : (len(self.facets), ) float
| Total area of each facet (group of faces)
|
| facets_boundary
| Return the edges which represent the boundary of each facet
|
| Returns
| ---------
| edges_boundary : sequence of (n, 2) int
| Indices of self.vertices
|
| facets_normal
| Return the normal of each facet
|
| Returns
| ---------
| normals: (len(self.facets), 3) float
| A unit normal vector for each facet
|
| facets_on_hull
| Find which facets of the mesh are on the convex hull.
|
| Returns
| ---------
| on_hull : (len(mesh.facets), ) bool
| is A facet on the meshes convex hull or not
|
| facets_origin
| Return a point on the facet plane.
|
| Returns
| ------------
| origins : (len(self.facets), 3) float
| A point on each facet plane
|
| identifier
| Return a float vector which is unique to the mesh
| and is robust to rotation and translation.
|
| Returns
| -----------
| identifier : (7,) float
| Identifying properties of the current mesh
|
| identifier_hash
| A hash of the rotation invariant identifier vector.
|
| Returns
| ---------
| hashed : str
| Hex string of the SHA256 hash from
| the identifier vector at hand-tuned sigfigs.
|
| integral_mean_curvature
| The integral mean curvature, or the surface integral of the mean curvature.
|
| Returns
| ---------
| area : float
| Integral mean curvature of mesh
|
| is_convex
| Check if a mesh is convex or not.
|
| Returns
| ----------
| is_convex: bool
| Is mesh convex or not
|
| is_empty
| Does the current mesh have data defined.
|
| Returns
| --------
| empty : bool
| If True, no data is set on the current mesh
|
| is_volume
| Check if a mesh has all the properties required to represent
| a valid volume, rather than just a surface.
|
| These properties include being watertight, having consistent
| winding and outward facing normals.
|
| Returns
| ---------
| valid
| Does the mesh represent a volume
|
| is_watertight
| Check if a mesh is watertight by making sure every edge is
| included in two faces.
|
| Returns
| ----------
| is_watertight : bool
| Is mesh watertight or not
|
| is_winding_consistent
| Does the mesh have consistent winding or not.
| A mesh with consistent winding has each shared edge
| going in an opposite direction from the other in the pair.
|
| Returns
| --------
| consistent : bool
| Is winding is consistent or not
|
| kdtree
| Return a scipy.spatial.cKDTree of the vertices of the mesh.
| Not cached as this lead to observed memory issues and segfaults.
|
| Returns
| ---------
| tree : scipy.spatial.cKDTree
| Contains mesh.vertices
|
| mass
| Mass of the current mesh, based on specified density and
| volume. If the current mesh isn't watertight this is garbage.
|
| Returns
| ---------
| mass : float
| Mass of the current mesh
|
| mass_properties
| Returns the mass properties of the current mesh.
|
| Assumes uniform density, and result is probably garbage if mesh
| isn't watertight.
|
| Returns
| ----------
| properties : dict
| With keys:
| 'volume' : in global units^3
| 'mass' : From specified density
| 'density' : Included again for convenience (same as kwarg density)
| 'inertia' : Taken at the center of mass and aligned with global
| coordinate system
| 'center_mass' : Center of mass location, in global coordinate system
|
| principal_inertia_components
| Return the principal components of inertia
|
| Ordering corresponds to mesh.principal_inertia_vectors
|
| Returns
| ----------
| components : (3, ) float
| Principal components of inertia
|
| principal_inertia_transform
| A transform which moves the current mesh so the principal
| inertia vectors are on the X,Y, and Z axis, and the centroid is
| at the origin.
|
| Returns
| ----------
| transform : (4, 4) float
| Homogeneous transformation matrix
|
| principal_inertia_vectors
| Return the principal axis of inertia as unit vectors.
| The order corresponds to `mesh.principal_inertia_components`.
|
| Returns
| ----------
| vectors : (3, 3) float
| Three vectors pointing along the
| principal axis of inertia directions
|
| referenced_vertices
| Which vertices in the current mesh are referenced by a face.
|
| Returns
| -------------
| referenced : (len(self.vertices), ) bool
| Which vertices are referenced by a face
|
| smooth_shaded
| Smooth shading in OpenGL relies on which vertices are shared,
| this function will disconnect regions above an angle threshold
| and return a non-watertight version which will look better
| in an OpenGL rendering context.
|
| If you would like to use non-default arguments see `graph.smooth_shade`.
|
| Returns
| ---------
| smooth_shaded : trimesh.Trimesh
| Non watertight version of current mesh.
|
| symmetry
| Check whether a mesh has rotational symmetry around
| an axis (radial) or point (spherical).
|
| Returns
| -----------
| symmetry : None, 'radial', 'spherical'
| What kind of symmetry does the mesh have.
|
| symmetry_axis
| If a mesh has rotational symmetry, return the axis.
|
| Returns
| ------------
| axis : (3, ) float
| Axis around which a 2D profile was revolved to create this mesh.
|
| symmetry_section
| If a mesh has rotational symmetry return the two
| vectors which make up a section coordinate frame.
|
| Returns
| ----------
| section : (2, 3) float
| Vectors to take a section along
|
| triangles
| Actual triangles of the mesh (points, not indexes)
|
| Returns
| ---------
| triangles : (n, 3, 3) float
| Points of triangle vertices
|
| triangles_center
| The center of each triangle (barycentric [1/3, 1/3, 1/3])
|
| Returns
| ---------
| triangles_center : (len(self.faces), 3) float
| Center of each triangular face
|
| triangles_cross
| The cross product of two edges of each triangle.
|
| Returns
| ---------
| crosses : (n, 3) float
| Cross product of each triangle
|
| triangles_tree
| An R-tree containing each face of the mesh.
|
| Returns
| ----------
| tree : rtree.index
| Each triangle in self.faces has a rectangular cell
|
| vertex_adjacency_graph
| Returns a networkx graph representing the vertices and their connections
| in the mesh.
|
| Returns
| ---------
| graph: networkx.Graph
| Graph representing vertices and edges between
| them where vertices are nodes and edges are edges
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| mesh = trimesh.primitives.Box()
| graph = mesh.vertex_adjacency_graph
| graph.neighbors(0)
| > [1, 2, 3, 4]
|
| vertex_defects
| Return the vertex defects, or (2*pi) minus the sum of the angles
| of every face that includes that vertex.
|
| If a vertex is only included by coplanar triangles, this
| will be zero. For convex regions this is positive, and
| concave negative.
|
| Returns
| --------
| vertex_defect : (len(self.vertices), ) float
| Vertex defect at the every vertex
|
| vertex_degree
| Return the number of faces each vertex is included in.
|
| Returns
| ----------
| degree : (len(self.vertices), ) int
| Number of faces each vertex is included in
|
| vertex_faces
| A representation of the face indices that correspond to each vertex.
|
| Returns
| ----------
| vertex_faces : (n,m) int
| Each row contains the face indices that correspond to the given vertex,
| padded with -1 up to the max number of faces corresponding to any one vertex
| Where n == len(self.vertices), m == max number of faces for a single vertex
|
| vertex_neighbors
| The vertex neighbors of each vertex of the mesh, determined from
| the cached vertex_adjacency_graph, if already existent.
|
| Returns
| ----------
| vertex_neighbors : (len(self.vertices), ) int
| Represents immediate neighbors of each vertex along
| the edge of a triangle
|
| Examples
| ----------
| This is useful for getting nearby vertices for a given vertex,
| potentially for some simple smoothing techniques.
|
| >>> mesh = trimesh.primitives.Box()
| >>> mesh.vertex_neighbors[0]
| [1, 2, 3, 4]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.base.Trimesh:
|
| center_mass
| The point in space which is the center of mass/volume.
|
| Returns
| -----------
| center_mass : (3, ) float
| Volumetric center of mass of the mesh.
|
| density
| The density of the mesh used in inertia calculations.
|
| Returns
| -----------
| density
| The density of the primitive.
|
| mutable
| Is the current mesh allowed to be altered in-place?
|
| Returns
| -------------
| mutable
| If data is allowed to be set for the mesh.
|
| vertex_normals
| The vertex normals of the mesh. If the normals were loaded
| we check to make sure we have the same number of vertex
| normals and vertices before returning them. If there are
| no vertex normals defined or a shape mismatch we calculate
| the vertex normals from the mean normals of the faces the
| vertex is used in.
|
| Returns
| ----------
| vertex_normals : (n, 3) float
| Represents the surface normal at each vertex.
| Where n == len(self.vertices)
|
| visual
| Get the stored visuals for the current mesh.
|
| Returns
| -------------
| visual : ColorVisuals or TextureVisuals
| Contains visual information about the mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __hash__(self)
| Get a hash of the current geometry.
|
| Returns
| ---------
| hash
| Hash of current graph and geometry.
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| scale
| A loosely specified "order of magnitude scale" for the
| geometry which always returns a value and can be used
| to make code more robust to large scaling differences.
|
| It returns the diagonal of the axis aligned bounding box
| or if anything is invalid or undefined, `1.0`.
|
| Returns
| ----------
| scale : float
| Approximate order of magnitude scale of the geometry.
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
log = <Logger trimesh.util (WARNING)>
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\primitives.py
trimesh.proximity
Python Library Documentation: module trimesh.proximity in trimesh
NAME
trimesh.proximity
DESCRIPTION
proximity.py
---------------
Query mesh- point proximity.
CLASSES
builtins.object
NearestQueryResult
ProximityQuery
class NearestQueryResult(builtins.object)
| Stores the nearest points and attributes for nearest points queries.
|
| Methods defined here:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| has_normals(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ProximityQuery(builtins.object)
| ProximityQuery(mesh)
|
| Proximity queries for the current mesh.
|
| Methods defined here:
|
| __init__(self, mesh)
| Initialize self. See help(type(self)) for accurate signature.
|
| on_surface(*args, **kwargs) from trimesh.constants.log_time.<locals>
| Given list of points, for each point find the closest point
| on any triangle of the mesh.
|
| Parameters
| ----------
| points : (m,3) float, points in space
|
| Returns
| ----------
| closest : (m, 3) float
| Closest point on triangles for each point
| distance : (m,) float
| Distance to surface
| triangle_id : (m,) int
| Index of closest triangle for each point.
|
| signed_distance(self, points)
| Find the signed distance from a mesh to a list of points.
|
| * Points OUTSIDE the mesh will have NEGATIVE distance
| * Points within tol.merge of the surface will have POSITIVE distance
| * Points INSIDE the mesh will have POSITIVE distance
|
| Parameters
| -----------
| points : (n, 3) float
| Points in space
|
| Returns
| ----------
| signed_distance : (n,) float
| Signed distance from point to mesh.
|
| vertex(self, points)
| Given a set of points, return the closest vertex index to each point
|
| Parameters
| ----------
| points : (n, 3) float
| Points in space
|
| Returns
| ----------
| distance : (n,) float
| Distance from source point to vertex.
| vertex_id : (n,) int
| Index of mesh.vertices for closest vertex.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
closest_point(mesh, points)
Given a mesh and a list of points find the closest point
on any triangle.
Parameters
----------
mesh : trimesh.Trimesh
Mesh to query
points : (m, 3) float
Points in space
Returns
----------
closest : (m, 3) float
Closest point on triangles for each point
distance : (m,) float
Distance to mesh.
triangle_id : (m,) int
Index of triangle containing closest point
closest_point_naive(mesh, points)
Given a mesh and a list of points find the closest point
on any triangle.
Does this by constructing a very large intermediate array and
comparing every point to every triangle.
Parameters
----------
mesh : Trimesh
Takes mesh to have same interfaces as `closest_point`
points : (m, 3) float
Points in space
Returns
----------
closest : (m, 3) float
Closest point on triangles for each point
distance : (m,) float
Distances between point and triangle
triangle_id : (m,) int
Index of triangle containing closest point
longest_ray(mesh, points, directions)
Find the lengths of the longest rays which do not intersect the mesh
cast from a list of points in the provided directions.
Parameters
-----------
points : (n, 3) float
Points in space.
directions : (n, 3) float
Directions of rays.
Returns
----------
signed_distance : (n,) float
Length of rays.
max_tangent_sphere(mesh, points, inwards=True, normals=None, threshold=1e-06, max_iter=100)
Find the center and radius of the sphere which is tangent to
the mesh at the given point and at least one more point with no
non-tangential intersections with the mesh.
Masatomo Inui, Nobuyuki Umezu & Ryohei Shimane (2016)
Shrinking sphere:
A parallel algorithm for computing the thickness of 3D objects,
Computer-Aided Design and Applications, 13:2, 199-207,
DOI: 10.1080/16864360.2015.1084186
Parameters
----------
points : (n, 3) float
Points in space.
inwards : bool
Whether to have the sphere inside or outside the mesh.
normals : (n, 3) float or None
Normals of the mesh at the given points
if is None computed automatically.
Returns
----------
centers : (n,3) float
Centers of spheres
radii : (n,) float
Radii of spheres
nearby_faces(mesh, points)
For each point find nearby faces relatively quickly.
The closest point on the mesh to the queried point is guaranteed to be
on one of the faces listed.
Does this by finding the nearest vertex on the mesh to each point, and
then returns all the faces that intersect the axis aligned bounding box
centered at the queried point and extending to the nearest vertex.
Parameters
----------
mesh : trimesh.Trimesh
Mesh to query.
points : (n, 3) float
Points in space
Returns
-----------
candidates : (points,) int
Sequence of indexes for mesh.faces
signed_distance(mesh, points)
Find the signed distance from a mesh to a list of points.
* Points OUTSIDE the mesh will have NEGATIVE distance
* Points within tol.merge of the surface will have POSITIVE distance
* Points INSIDE the mesh will have POSITIVE distance
Parameters
-----------
mesh : trimesh.Trimesh
Mesh to query.
points : (n, 3) float
Points in space
Returns
----------
signed_distance : (n,) float
Signed distance from point to mesh
thickness(mesh, points, exterior=False, normals=None, method='max_sphere')
Find the thickness of the mesh at the given points.
Parameters
----------
points : (n, 3) float
Points in space
exterior : bool
Whether to compute the exterior thickness
(a.k.a. reach)
normals : (n, 3) float
Normals of the mesh at the given points
If is None computed automatically.
method : string
One of 'max_sphere' or 'ray'
Returns
----------
thickness : (n,) float
Thickness at given points.
DATA
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\proximity.py
trimesh.ray
Python Library Documentation: package trimesh.ray in trimesh
NAME
trimesh.ray
PACKAGE CONTENTS
ray_pyembree
ray_triangle
ray_util
DATA
__all__ = ['ray_pyembree', 'ray_triangle']
ray_pyembree = <trimesh.exceptions.ExceptionWrapper object>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\ray\__init__.py
trimesh.registration
Python Library Documentation: module trimesh.registration in trimesh
NAME
trimesh.registration
DESCRIPTION
registration.py
---------------
Functions for registering (aligning) point clouds with meshes.
FUNCTIONS
icp(a, b, initial=None, threshold=1e-05, max_iterations=20, **kwargs)
Apply the iterative closest point algorithm to align a point cloud with
another point cloud or mesh. Will only produce reasonable results if the
initial transformation is roughly correct. Initial transformation can be
found by applying Procrustes' analysis to a suitable set of landmark
points (often picked manually).
Parameters
----------
a : (n,3) float
List of points in space.
b : (m,3) float or Trimesh
List of points in space or mesh.
initial : (4,4) float
Initial transformation.
threshold : float
Stop when change in cost is less than threshold
max_iterations : int
Maximum number of iterations
kwargs : dict
Args to pass to procrustes
Returns
----------
matrix : (4,4) float
The transformation matrix sending a to b
transformed : (n,3) float
The image of a under the transformation
cost : float
The cost of the transformation
mesh_other(mesh, other, samples: Union[int, numpy.integer, numpy.unsignedinteger] = 500, scale: bool = False, icp_first: Union[int, numpy.integer, numpy.unsignedinteger] = 10, icp_final: Union[int, numpy.integer, numpy.unsignedinteger] = 50, **kwargs)
Align a mesh with another mesh or a PointCloud using
the principal axes of inertia as a starting point which
is refined by iterative closest point.
Parameters
------------
mesh : trimesh.Trimesh object
Mesh to align with other
other : trimesh.Trimesh or (n, 3) float
Mesh or points in space
samples : int
Number of samples from mesh surface to align
scale : bool
Allow scaling in transform
icp_first : int
How many ICP iterations for the 9 possible
combinations of sign flippage
icp_final : int
How many ICP iterations for the closest
candidate from the wider search
kwargs : dict
Passed through to `icp`, which passes through to `procrustes`
Returns
-----------
mesh_to_other : (4, 4) float
Transform to align mesh to the other object
cost : float
Average squared distance per point
nricp_amberg(source_mesh, target_geometry, source_landmarks=None, target_positions=None, steps=None, eps=0.0001, gamma=1, distance_threshold=0.1, return_records=False, use_faces=True, use_vertex_normals=True, neighbors_count=8)
Non Rigid Iterative Closest Points
Implementation of "Amberg et al. 2007: Optimal Step
Nonrigid ICP Algorithms for Surface Registration."
Allows to register non-rigidly a mesh on another or
on a point cloud. The core algorithm is explained
at the end of page 3 of the paper.
Comparison between nricp_amberg and nricp_sumner:
* nricp_amberg fits to the target mesh in less steps
* nricp_amberg can generate sharp edges
* only vertices and their neighbors are considered
* nricp_sumner tend to preserve more the original shape
* nricp_sumner parameters are easier to tune
* nricp_sumner solves for triangle positions whereas
nricp_amberg solves for vertex transforms
* nricp_sumner is less optimized when wn > 0
Parameters
----------
source_mesh : Trimesh
Source mesh containing both vertices and faces.
target_geometry : Trimesh or PointCloud or (n, 3) float
Target geometry. It can contain no faces or be a PointCloud.
source_landmarks : (n,) int or ((n,) int, (n, 3) float)
n landmarks on the the source mesh.
Represented as vertex indices (n,) int.
It can also be represented as a tuple of triangle
indices and barycentric coordinates ((n,) int, (n, 3) float,).
target_positions : (n, 3) float
Target positions assigned to source landmarks
steps : Core parameters of the algorithm
Iterable of iterables (ws, wl, wn, max_iter,).
ws is smoothness term, wl weights landmark importance, wn normal importance
and max_iter is the maximum number of iterations per step.
eps : float
If the error decrease if inferior to this value, the current step ends.
gamma : float
Weight the translation part against the rotational/skew part.
Recommended value : 1.
distance_threshold : float
Distance threshold to account for a vertex match or not.
return_records : bool
If True, also returns all the intermediate results. It can help debugging
and tune the parameters to match a specific case.
use_faces : bool
If True and if target geometry has faces, use proximity.closest_point to find
matching points. Else use scipy's cKDTree object.
use_vertex_normals : bool
If True and if target geometry has faces, interpolate the normals of the target
geometry matching points.
Else use face normals or estimated normals if target geometry has no faces.
neighbors_count : int
number of neighbors used for normal estimation. Only used if target geometry has
no faces or if use_faces is False.
Returns
----------
result : (n, 3) float or List[(n, 3) float]
The vertices positions of source_mesh such that it is registered non-rigidly
onto the target geometry.
If return_records is True, it returns the list of the vertex positions at each
iteration.
nricp_sumner(source_mesh, target_geometry, source_landmarks=None, target_positions=None, steps=None, distance_threshold=0.1, return_records=False, use_faces=True, use_vertex_normals=True, neighbors_count=8, face_pairs_type='vertex')
Non Rigid Iterative Closest Points
Implementation of the correspondence computation part of
"Sumner and Popovic 2004: Deformation Transfer for Triangle Meshes"
Allows to register non-rigidly a mesh on another geometry.
Comparison between nricp_amberg and nricp_sumner:
* nricp_amberg fits to the target mesh in less steps
* nricp_amberg can generate sharp edges
* only vertices and their neighbors are considered
* nricp_sumner tend to preserve more the original shape
* nricp_sumner parameters are easier to tune
* nricp_sumner solves for triangle positions whereas
nricp_amberg solves for vertex transforms
* nricp_sumner is less optimized when wn > 0
Parameters
----------
source_mesh : Trimesh
Source mesh containing both vertices and faces.
target_geometry : Trimesh or PointCloud or (n, 3) float
Target geometry. It can contain no faces or be a PointCloud.
source_landmarks : (n,) int or ((n,) int, (n, 3) float)
n landmarks on the the source mesh.
Represented as vertex indices (n,) int.
It can also be represented as a tuple of triangle indices and barycentric
coordinates ((n,) int, (n, 3) float,).
target_positions : (n, 3) float
Target positions assigned to source landmarks
steps : Core parameters of the algorithm
Iterable of iterables (wc, wi, ws, wl, wn).
wc is the correspondence term (strength of fitting), wi is the identity term
(recommended value : 0.001), ws is smoothness term, wl weights the landmark
importance and wn the normal importance.
distance_threshold : float
Distance threshold to account for a vertex match or not.
return_records : bool
If True, also returns all the intermediate results. It can help debugging
and tune the parameters to match a specific case.
use_faces : bool
If True and if target geometry has faces, use proximity.closest_point to find
matching points. Else use scipy's cKDTree object.
use_vertex_normals : bool
If True and if target geometry has faces, interpolate the normals of the target
geometry matching points.
Else use face normals or estimated normals if target geometry has no faces.
neighbors_count : int
number of neighbors used for normal estimation. Only used if target geometry has
no faces or if use_faces is False.
face_pairs_type : str 'vertex' or 'edge'
Method to determine face pairs used in the smoothness cost. 'vertex' yields
smoother results.
Returns
----------
result : (n, 3) float or List[(n, 3) float]
The vertices positions of source_mesh such that it is registered non-rigidly
onto the target geometry.
If return_records is True, it returns the list of the vertex positions at each
iteration.
procrustes(a: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], b: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], weights: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, reflection: bool = True, translation: bool = True, scale: bool = True, return_cost: bool = True)
Perform Procrustes' analysis to quickly align two corresponding
point clouds subject to constraints. This is much cheaper than
any other registration method but only applies if the two inputs
correspond in order.
Finds the transformation T mapping a to b which minimizes the
square sum distances between Ta and b, also called the cost.
Optionally filter the points in a and b via a binary weights array.
Non-uniform weights are also supported, but won't yield the optimal rotation.
Parameters
----------
a : (n,3) float
List of points in space
b : (n,3) float
List of points in space
weights : (n,) float
List of floats representing how much weight is assigned to each point.
Binary entries can be used to filter the arrays; normalization is not required.
Translation and scaling are adjusted according to the weighting.
Note, however, that this method does not yield the optimal rotation for
non-uniform weighting,
as this would require an iterative, nonlinear optimization approach.
reflection : bool
If the transformation is allowed reflections
translation : bool
If the transformation is allowed translation and rotation.
scale : bool
If the transformation is allowed scaling
return_cost : bool
Whether to return the cost and transformed a as well
Returns
----------
matrix : (4,4) float
The transformation matrix sending a to b
transformed : (n,3) float
The image of a under the transformation
cost : float
The cost of the transformation
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\registration.py
trimesh.remesh
Python Library Documentation: module trimesh.remesh in trimesh
NAME
trimesh.remesh
DESCRIPTION
remesh.py
-------------
Deal with re- triangulation of existing meshes.
FUNCTIONS
subdivide(vertices, faces, face_index=None, vertex_attributes=None, return_index=False)
Subdivide a mesh into smaller triangles.
Note that if `face_index` is passed, only those
faces will be subdivided and their neighbors won't
be modified making the mesh no longer "watertight."
Parameters
------------
vertices : (n, 3) float
Vertices in space
faces : (m, 3) int
Indexes of vertices which make up triangular faces
face_index : faces to subdivide.
if None: all faces of mesh will be subdivided
if (n,) int array of indices: only specified faces
vertex_attributes : dict
Contains (n, d) attribute data
return_index : bool
If True, return index of original face for new faces
Returns
----------
new_vertices : (q, 3) float
Vertices in space
new_faces : (p, 3) int
Remeshed faces
index_dict : dict
Only returned if `return_index`, {index of
original face : index of new faces}.
subdivide_loop(vertices, faces, iterations=None)
Subdivide a mesh by dividing each triangle into four triangles
and approximating their smoothed surface (loop subdivision).
This function is an array-based implementation of loop subdivision,
which avoids slow for loop and enables faster calculation.
Overall process:
1. Calculate odd vertices.
Assign a new odd vertex on each edge and
calculate the value for the boundary case and the interior case.
The value is calculated as follows.
v2
/ f0 \ 0
v0--e--v1 / \
\f1 / v0--e--v1
v3
- interior case : 3:1 ratio of mean(v0,v1) and mean(v2,v3)
- boundary case : mean(v0,v1)
2. Calculate even vertices.
The new even vertices are calculated with the existing
vertices and their adjacent vertices.
1---2
/ \/ \ 0---1
0---v---3 / \/ \
\ /\/ b0---v---b1
k...4
- interior case : (1-kB):B ratio of v and k adjacencies
- boundary case : 3:1 ratio of v and mean(b0,b1)
3. Compose new faces with new vertices.
Parameters
------------
vertices : (n, 3) float
Vertices in space
faces : (m, 3) int
Indices of vertices which make up triangles
Returns
------------
vertices : (j, 3) float
Vertices in space
faces : (q, 3) int
Indices of vertices
iterations : int
Number of iterations to run subdivision
subdivide_to_size(vertices, faces, max_edge, max_iter=10, return_index=False)
Subdivide a mesh until every edge is shorter than a
specified length.
Will return a triangle soup, not a nicely structured mesh.
Parameters
------------
vertices : (n, 3) float
Vertices in space
faces : (m, 3) int
Indices of vertices which make up triangles
max_edge : float
Maximum length of any edge in the result
max_iter : int
The maximum number of times to run subdivision
return_index : bool
If True, return index of original face for new faces
Returns
------------
vertices : (j, 3) float
Vertices in space
faces : (q, 3) int
Indices of vertices
index : (q, 3) int
Only returned if `return_index`, index of
original face for each new face.
DATA
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\remesh.py
trimesh.rendering
Python Library Documentation: module trimesh.rendering in trimesh
NAME
trimesh.rendering
DESCRIPTION
rendering.py
--------------
Functions to convert trimesh objects to pyglet/opengl objects.
FUNCTIONS
colors_to_gl(colors, count)
Given a list of colors (or None) return a GL-acceptable
list of colors.
Parameters
------------
colors: (count, (3 or 4)) float
Input colors as an array
Returns
---------
colors_type : str
Color type
colors_gl : (count,) list
Colors to pass to pyglet
convert_to_vertexlist(geometry, **kwargs)
Try to convert various geometry objects to the constructor
args for a pyglet indexed vertex list.
Parameters
------------
obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float
Object to render
Returns
------------
args : tuple
Args to be passed to pyglet indexed vertex list
constructor.
light_to_gl(light, transform, lightN)
Convert trimesh.scene.lighting.Light objects into
args for gl.glLightFv calls
Parameters
--------------
light : trimesh.scene.lighting.Light
Light object to be converted to GL
transform : (4, 4) float
Transformation matrix of light
lightN : int
Result of gl.GL_LIGHT0, gl.GL_LIGHT1, etc
Returns
--------------
multiarg : [tuple]
List of args to pass to gl.glLightFv eg:
[gl.glLightfb(*a) for a in multiarg]
material_to_texture(material, upsize=True)
Convert a trimesh.visual.texture.Material object into
a pyglet-compatible texture object.
Parameters
--------------
material : trimesh.visual.texture.Material
Material to be converted
upsize: bool
If True, will upscale textures to their nearest power
of two resolution to avoid weirdness
Returns
---------------
texture : pyglet.image.Texture
Texture loaded into pyglet form
matrix_to_gl(matrix)
Convert a numpy row-major homogeneous transformation matrix
to a flat column-major GLfloat transformation.
Parameters
-------------
matrix : (4,4) float
Row-major homogeneous transform
Returns
-------------
glmatrix : (16,) gl.GLfloat
Transform in pyglet format
mesh_to_vertexlist(mesh, group=None, smooth=True, smooth_threshold=60000)
Convert a Trimesh object to arguments for an
indexed vertex list constructor.
Parameters
-------------
mesh : trimesh.Trimesh
Mesh to be rendered
group : str
Rendering group for the vertex list
smooth : bool
Should we try to smooth shade the mesh
smooth_threshold : int
Maximum number of faces to smooth shade
Returns
--------------
args : (7,) tuple
Args for vertex list constructor
path_to_vertexlist(path, group=None, **kwargs)
Convert a Path3D object to arguments for a
pyglet indexed vertex list constructor.
Parameters
-------------
path : trimesh.path.Path3D object
Mesh to be rendered
group : str
Rendering group for the vertex list
Returns
--------------
args : (7,) tuple
Args for vertex list constructor
points_to_vertexlist(points, colors=None, group=None, **kwargs)
Convert a numpy array of 3D points to args for
a vertex list constructor.
Parameters
-------------
points : (n, 3) float
Points to be rendered
colors : (n, 3) or (n, 4) float
Colors for each point
group : str
Rendering group for the vertex list
Returns
--------------
args : (7,) tuple
Args for vertex list constructor
vector_to_gl(array, *args)
Convert an array and an optional set of args into a
flat vector of gl.GLfloat
DATA
GL_LINES = 1
GL_POINTS = 0
GL_TRIANGLES = 4
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\rendering.py
trimesh.repair
Python Library Documentation: module trimesh.repair in trimesh
NAME
trimesh.repair
DESCRIPTION
repair.py
-------------
Fill holes and fix winding and normals of meshes.
FUNCTIONS
broken_faces(mesh, color=None)
Return the index of faces in the mesh which break the
watertight status of the mesh.
Parameters
--------------
mesh : trimesh.Trimesh
Mesh to check broken faces on
color: (4,) uint8 or None
Will set broken faces to this color if not None
Returns
---------------
broken : (n, ) int
Indexes of mesh.faces
fill_holes(mesh, use_fan: bool = False)
Fill boundary holes in-place using fans, which may result
in bad answers if the holes are non convex!
Face colors and attributes will be padded with default values
so shapes match.
Parameters
----------
mesh : trimesh.Trimesh
Mesh will be repaired in-place.
use_fan
If passed, holes larger than quads will be triangulated
using fans which are only valid for non-convex holes.
fix_inversion(mesh, multibody: bool = False)
Check to see if a mesh has normals pointing "out."
Parameters
-------------
mesh : trimesh.Trimesh
Mesh to fix in-place.
multibody : bool
If True will try to fix normals on every body
fix_normals(mesh, multibody=False)
Fix the winding and direction of a mesh face and
face normals in-place.
Really only meaningful on watertight meshes but will orient all
faces and winding in a uniform way for non-watertight face
patches as well.
Parameters
-------------
mesh : trimesh.Trimesh
Mesh to fix normals on
multibody : bool
if True try to correct normals direction
on every body rather than just one
Notes
--------------
mesh.faces : will flip columns on inverted faces
fix_winding(mesh)
Traverse and change mesh faces in-place to make sure
winding is correct with edges on adjacent faces in
opposite directions.
Parameters
-------------
mesh : Trimesh
Source geometry to alter in-place.
stitch(mesh, faces=None, insert_vertices=False)
Create a fan stitch over the boundary of the specified
faces. If the boundary is non-convex a triangle fan
is going to be extremely wonky.
Parameters
-----------
mesh : trimesh.Trimesh
Mesh to create fan stitch on.
faces : (n,) int
Face indexes to stitch with triangle fans.
insert_vertices : bool
Allow stitching to insert new vertices?
Returns
----------
fan : (m, 3) int
New triangles referencing mesh.vertices.
vertices : (p, 3) float
Inserted vertices (only returned `if insert_vertices`)
DATA
log = <Logger trimesh.util (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\repair.py
trimesh.resolvers
Python Library Documentation: module trimesh.resolvers in trimesh
NAME
trimesh.resolvers
DESCRIPTION
resolvers.py
---------------
Provides a common interface to load assets referenced by name
like MTL files, texture images, etc. Assets can be from ZIP
archives, web assets, or a local file path.
CLASSES
abc.ABC(builtins.object)
Resolver
FilePathResolver
GithubResolver
WebResolver
ZipResolver
class FilePathResolver(Resolver)
| FilePathResolver(source: str)
|
| Resolve files from a source path on the file system.
|
| Method resolution order:
| FilePathResolver
| Resolver
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, source: str)
| Resolve files based on a source path.
|
| Parameters
| ------------
| source : str
| File path where mesh was loaded from
|
| get(self, name: str)
| Get an asset.
|
| Parameters
| -------------
| name : str
| Name of the asset
|
| Returns
| ------------
| data : bytes
| Loaded data from asset
|
| keys(self)
| List all files available to be loaded.
|
| Yields
| -----------
| name : str
| Name of a file which can be accessed.
|
| namespaced(self, namespace: str) -> 'FilePathResolver'
| Return a resolver which changes the root of the
| resolver by an added namespace.
|
| Parameters
| -------------
| namespace : str
| Probably a subdirectory
|
| Returns
| --------------
| resolver : FilePathResolver
| Resolver with root directory changed.
|
| write(self, name: str, data: Union[str, bytes])
| Write an asset to a file path.
|
| Parameters
| -----------
| name : str
| Name of the file to write
| data : str or bytes
| Data to write to the file
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Resolver:
|
| __contains__(self, key: str) -> bool
|
| __getitem__(self, key: str)
|
| __setitem__(self, key: str, value)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Resolver:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class GithubResolver(Resolver)
| GithubResolver(repo: str, branch: Optional[str] = None, commit: Optional[str] = None, save: Optional[str] = None)
|
| Method resolution order:
| GithubResolver
| Resolver
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, repo: str, branch: Optional[str] = None, commit: Optional[str] = None, save: Optional[str] = None)
| Get files from a remote Github repository by
| downloading a zip file with the entire branch
| or a specific commit.
|
| Parameters
| -------------
| repo
| In the format of `owner/repo`
| branch
| The remote branch you want to get files from.
| commit
| The full commit hash: pass either this OR branch.
| save
| A path if you want to save results locally.
|
| get(self, key)
|
| keys(self)
| List the available files in the repository.
|
| Returns
| ----------
| keys : iterable
| Keys available to the resolved.
|
| namespaced(self, namespace)
| Return a "sub-resolver" with a root namespace.
|
| Parameters
| -------------
| namespace : str
| The root of the key to clip off, i.e. if
| this resolver has key `a/b/c` you can get
| 'a/b/c' with resolver.namespaced('a/b').get('c')
|
| Returns
| -----------
| resolver : Resolver
| Namespaced resolver.
|
| write(self, name, data)
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| zipped
| - opened zip file
| - locally saved zip file
| - retrieve zip file and saved
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Resolver:
|
| __contains__(self, key: str) -> bool
|
| __getitem__(self, key: str)
|
| __setitem__(self, key: str, value)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Resolver:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class Resolver(abc.ABC)
| Resolver(*args, **kwargs)
|
| The base class for resolvers.
|
| Method resolution order:
| Resolver
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __contains__(self, key: str) -> bool
|
| __getitem__(self, key: str)
|
| __init__(self, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __setitem__(self, key: str, value)
|
| get(self, key)
|
| keys(self)
|
| namespaced(self, namespace: str)
|
| write(self, name: str, data)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__init__', 'get', 'keys', 'namespace...
|
| __annotations__ = {}
class WebResolver(Resolver)
| WebResolver(url: str)
|
| Resolve assets from a remote URL.
|
| Method resolution order:
| WebResolver
| Resolver
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, url: str)
| Resolve assets from a base URL.
|
| Parameters
| --------------
| url : str
| Location where a mesh was stored or
| directory where mesh was stored
|
| get(self, name: str) -> bytes
| Get a resource from the remote site.
|
| Parameters
| -------------
| name : str
| Asset name, i.e. 'quadknot.obj.mtl'
|
| get_base(self) -> bytes
| Fetch the data at the full URL this resolver was
| instantiated with, i.e. `https://stuff.com/hi.glb`
| this will return the response.
|
| Returns
| --------
| content
| The value at `self.url`
|
| keys(self)
|
| namespaced(self, namespace: str) -> 'WebResolver'
| Return a namespaced version of current resolver.
|
| Parameters
| -------------
| namespace : str
| URL fragment
|
| Returns
| -----------
| resolver : WebResolver
| With sub-url: `https://example.com/{namespace}`
|
| write(self, key, value)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Resolver:
|
| __contains__(self, key: str) -> bool
|
| __getitem__(self, key: str)
|
| __setitem__(self, key: str, value)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Resolver:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ZipResolver(Resolver)
| ZipResolver(archive: Optional[dict] = None, namespace: Optional[str] = None)
|
| Resolve files inside a ZIP archive.
|
| Method resolution order:
| ZipResolver
| Resolver
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __init__(self, archive: Optional[dict] = None, namespace: Optional[str] = None)
| Resolve files inside a ZIP archive as loaded by
| trimesh.util.decompress
|
| Parameters
| -------------
| archive : dict
| Contains resources as file object
| namespace : None or str
| If passed will only show keys that start
| with this value and this substring must be
| removed for any get calls.
|
| export(self) -> bytes
| Export the contents of the current archive as
| a ZIP file.
|
| Returns
| ------------
| compressed : bytes
| Compressed data in ZIP format.
|
| get(self, name: str) -> bytes
| Get an asset from the ZIP archive.
|
| Parameters
| -------------
| name : str
| Name of the asset
|
| Returns
| -------------
| data : bytes
| Loaded data from asset
|
| keys(self)
| Get the available keys in the current archive.
|
| Returns
| -----------
| keys : iterable
| Keys in the current archive.
|
| namespaced(self, namespace: str) -> 'ZipResolver'
| Return a "sub-resolver" with a root namespace.
|
| Parameters
| -------------
| namespace : str
| The root of the key to clip off, i.e. if
| this resolver has key `a/b/c` you can get
| 'a/b/c' with resolver.namespaced('a/b').get('c')
|
| Returns
| -----------
| resolver : Resolver
| Namespaced resolver.
|
| write(self, key: str, value) -> None
| Store a value in the current archive.
|
| Parameters
| -----------
| key : hashable
| Key to store data under.
| value : str, bytes, file-like
| Value to store.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Resolver:
|
| __contains__(self, key: str) -> bool
|
| __getitem__(self, key: str)
|
| __setitem__(self, key: str, value)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Resolver:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
nearby_names(name, namespace=None)
Try to find nearby variants of a specified name.
Parameters
------------
name : str
Initial name.
Yields
-----------
nearby : str
Name that is a lightly permutated version
of the initial name.
DATA
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
ResolverLike = typing.Union[trimesh.resolvers.Resolver, collections.ab...
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\resolvers.py
trimesh.resources
Python Library Documentation: package trimesh.resources in trimesh
NAME
trimesh.resources
PACKAGE CONTENTS
FUNCTIONS
get_bytes(name: str) -> bytes
Get a resource from the `trimesh/resources` folder as binary data.
Parameters
-------------
name
File path relative to `trimesh/resources`
Returns
-------------
resource
File data as raw bytes.
get_json(name: str) -> dict
Get a resource from the `trimesh/resources` folder as a decoded string.
Parameters
-------------
name : str
File path relative to `trimesh/resources/{name}`
Returns
-------------
resource
File data decoded from JSON.
get_schema(name: str) -> dict
Load a schema and evaluate the referenced files.
Parameters
------------
name : str
Filename of schema.
Returns
----------
schema
Loaded and resolved schema.
get_stream(name: str) -> _io.BytesIO
Get a resource from the `trimesh/resources` folder as a binary stream.
Parameters
-------------
name : str
File path relative to `trimesh/resources`
Returns
-------------
resource
File data as a binary stream.
get_string(name: str) -> str
Get a resource from the `trimesh/resources` folder as a decoded string.
Parameters
-------------
name
File path relative to `trimesh/resources`
Returns
-------------
resource
File data as a string.
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\resources\__init__.py
trimesh.sample
Python Library Documentation: module trimesh.sample in trimesh
NAME
trimesh.sample
DESCRIPTION
sample.py
------------
Randomly sample surface and volume of meshes.
FUNCTIONS
sample_surface(mesh, count: Union[int, numpy.integer, numpy.unsignedinteger], face_weight: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, sample_color=False, seed=None)
Sample the surface of a mesh, returning the specified
number of points
For individual triangle sampling uses this method:
http://mathworld.wolfram.com/TrianglePointPicking.html
Parameters
-----------
mesh : trimesh.Trimesh
Geometry to sample the surface of
count : int
Number of points to return
face_weight : None or len(mesh.faces) float
Weight faces by a factor other than face area.
If None will be the same as face_weight=mesh.area
sample_color : bool
Option to calculate the color of the sampled points.
Default is False.
seed : None or int
If passed as an integer will provide deterministic results
otherwise pulls the seed from operating system entropy.
Returns
---------
samples : (count, 3) float
Points in space on the surface of mesh
face_index : (count,) int
Indices of faces for each sampled point
colors : (count, 4) float
Colors of each sampled point
Returns only when the sample_color is True
sample_surface_even(mesh, count: Union[int, numpy.integer, numpy.unsignedinteger], radius: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None, seed=None)
Sample the surface of a mesh, returning samples which are
VERY approximately evenly spaced. This is accomplished by
sampling and then rejecting pairs that are too close together.
Note that since it is using rejection sampling it may return
fewer points than requested (i.e. n < count). If this is the
case a log.warning will be emitted.
Parameters
-----------
mesh : trimesh.Trimesh
Geometry to sample the surface of
count : int
Number of points to return
radius : None or float
Removes samples below this radius
seed : None or int
Provides deterministic values
Returns
---------
samples : (n, 3) float
Points in space on the surface of mesh
face_index : (n,) int
Indices of faces for each sampled point
sample_surface_sphere(count: int) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Correctly pick random points on the surface of a unit sphere
Uses this method:
http://mathworld.wolfram.com/SpherePointPicking.html
Parameters
-----------
count : int
Number of points to return
Returns
----------
points : (count, 3) float
Random points on the surface of a unit sphere
volume_mesh(mesh, count: Union[int, numpy.integer, numpy.unsignedinteger]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Use rejection sampling to produce points randomly
distributed in the volume of a mesh.
Parameters
-----------
mesh : trimesh.Trimesh
Geometry to sample
count : int
Number of points to return
Returns
---------
samples : (n, 3) float
Points in the volume of the mesh where n <= count
volume_rectangular(extents, count: Union[int, numpy.integer, numpy.unsignedinteger], transform: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Return random samples inside a rectangular volume,
useful for sampling inside oriented bounding boxes.
Parameters
-----------
extents : (3,) float
Side lengths of rectangular solid
count : int
Number of points to return
transform : (4, 4) float
Homogeneous transformation matrix
Returns
---------
samples : (count, 3) float
Points in requested volume
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\sample.py
trimesh.scene
Python Library Documentation: package trimesh.scene in trimesh
NAME
trimesh.scene
PACKAGE CONTENTS
cameras
lighting
scene
transforms
CLASSES
builtins.object
trimesh.scene.cameras.Camera
trimesh.parent.Geometry3D(trimesh.parent.Geometry)
trimesh.scene.scene.Scene
class Camera(builtins.object)
| Camera(name=None, resolution=None, focal=None, fov=None, z_near=0.01, z_far=1000.0)
|
| Methods defined here:
|
| __init__(self, name=None, resolution=None, focal=None, fov=None, z_near=0.01, z_far=1000.0)
| Create a new Camera object that stores camera intrinsic
| and extrinsic parameters.
|
| TODO: skew is not supported
| TODO: cx and cy that are not half of width and height
|
| Parameters
| ------------
| name : str or None
| Name for camera to be used as node name
| resolution : (2,) int
| Pixel size in (height, width)
| focal : (2,) float
| Focal length in pixels. Either pass this OR FOV
| but not both. focal = (K[0][0], K[1][1])
| fov : (2,) float
| Field of view (fovx, fovy) in degrees
| z_near : float
| What is the closest
|
| __repr__(self)
| Return repr(self).
|
| angles(self)
| Get ray spherical coordinates in radians.
|
|
| Returns
| --------------
| angles : (n, 2) float
| Ray spherical coordinate angles in radians.
|
| copy(self)
| Safely get a copy of the current camera.
|
| look_at(self, points, **kwargs)
| Generate transform for a camera to keep a list
| of points in the camera's field of view.
|
| Parameters
| -------------
| points : (n, 3) float
| Points in space
| rotation : None, or (4, 4) float
| Rotation matrix for initial rotation
| distance : None or float
| Distance from camera to center
| center : None, or (3,) float
| Center of field of view.
|
| Returns
| --------------
| transform : (4, 4) float
| Transformation matrix from world to camera
|
| to_rays(self)
| Calculate ray direction vectors.
|
| Will return one ray per pixel, as set in self.resolution.
|
| Returns
| --------------
| vectors : (n, 3) float
| Ray direction vectors in camera frame with z == -1
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| K
| Get the intrinsic matrix for the Camera object.
|
| Returns
| -----------
| K : (3, 3) float
| Intrinsic matrix for camera
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| focal
| Get the focal length in pixels for the camera.
|
| Returns
| ------------
| focal : (2,) float
| Focal length in pixels
|
| fov
| Get the field of view in degrees.
|
| Returns
| -------------
| fov : (2,) float
| XY field of view in degrees
|
| resolution
| Get the camera resolution in pixels.
|
| Returns
| ------------
| resolution (2,) float
| Camera resolution in pixels
class Scene(trimesh.parent.Geometry3D)
| Scene(geometry: Union[trimesh.parent.Geometry, collections.abc.Iterable[trimesh.parent.Geometry], dict[str, trimesh.parent.Geometry], collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, base_frame: str = 'world', metadata: Optional[dict] = None, graph: Optional[trimesh.scene.transforms.SceneGraph] = None, camera: Optional[trimesh.scene.cameras.Camera] = None, lights: Optional[collections.abc.Sequence[trimesh.scene.lighting.Light]] = None, camera_transform: Optional[numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]] = None)
|
| A simple scene graph which can be rendered directly via
| pyglet/openGL or through other endpoints such as a
| raytracer. Meshes are added by name, which can then be
| moved by updating transform in the transform tree.
|
| Method resolution order:
| Scene
| trimesh.parent.Geometry3D
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
| Concatenate the current scene with another scene or mesh.
|
| Parameters
| ------------
| other : trimesh.Scene, trimesh.Trimesh, trimesh.Path
| Other object to append into the result scene
|
| Returns
| ------------
| appended : trimesh.Scene
| Scene with geometry from both scenes
|
| __hash__(self) -> int
| Return information about scene which is hashable.
|
| Returns
| ---------
| hashed
| String hashing scene.
|
| __init__(self, geometry: Union[trimesh.parent.Geometry, collections.abc.Iterable[trimesh.parent.Geometry], dict[str, trimesh.parent.Geometry], collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, base_frame: str = 'world', metadata: Optional[dict] = None, graph: Optional[trimesh.scene.transforms.SceneGraph] = None, camera: Optional[trimesh.scene.cameras.Camera] = None, lights: Optional[collections.abc.Sequence[trimesh.scene.lighting.Light]] = None, camera_transform: Optional[numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]] = None)
| Create a new Scene object.
|
| Parameters
| -------------
| geometry : Trimesh, Path2D, Path3D PointCloud or list
| Geometry to initially add to the scene
| base_frame
| Name of base frame
| metadata
| Any metadata about the scene
| graph
| A passed transform graph to use
| camera : Camera or None
| A passed camera to use
| lights : [trimesh.scene.lighting.Light] or None
| A passed lights to use
| camera_transform
| Homogeneous (4, 4) camera transform in the base frame
|
| add_geometry(self, geometry: Union[trimesh.parent.Geometry, collections.abc.Iterable[trimesh.parent.Geometry], dict[str, trimesh.parent.Geometry], collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], node_name: Optional[str] = None, geom_name: Optional[str] = None, parent_node_name: Optional[str] = None, transform: Optional[numpy.ndarray[Any, numpy.dtype[+_ScalarType_co]]] = None, metadata: Optional[dict] = None)
| Add a geometry to the scene.
|
| If the mesh has multiple transforms defined in its
| metadata, they will all be copied into the
| TransformForest of the current scene automatically.
|
| Parameters
| ----------
| geometry : Trimesh, Path2D, Path3D PointCloud or list
| Geometry to initially add to the scene
| node_name : None or str
| Name of the added node.
| geom_name : None or str
| Name of the added geometry.
| parent_node_name : None or str
| Name of the parent node in the graph.
| transform : None or (4, 4) float
| Transform that applies to the added node.
| metadata : None or dict
| Optional metadata for the node.
|
| Returns
| ----------
| node_name : str
| Name of single node in self.graph (passed in) or None if
| node was not added (eg. geometry was null or a Scene).
|
| apply_transform(self, transform)
| Apply a transform to all children of the base frame
| without modifying any geometry.
|
| Parameters
| --------------
| transform : (4, 4)
| Homogeneous transformation matrix.
|
| camera_rays(self) -> tuple[numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], numpy.ndarray[typing.Any, numpy.dtype[numpy.int64]]]
| Calculate the trimesh.scene.Camera origin and ray
| direction vectors. Returns one ray per pixel as set
| in camera.resolution
|
| Returns
| --------------
| origin: (n, 3) float
| Ray origins in space
| vectors: (n, 3) float
| Ray direction unit vectors in world coordinates
| pixels : (n, 2) int
| Which pixel does each ray correspond to in an image
|
| convert_units(self, desired: str, guess: bool = False) -> 'Scene'
| If geometry has units defined convert them to new units.
|
| Returns a new scene with geometries and transforms scaled.
|
| Parameters
| ----------
| desired : str
| Desired final unit system: 'inches', 'mm', etc.
| guess : bool
| Is the converter allowed to guess scale when models
| don't have it specified in their metadata.
|
| Returns
| ----------
| scaled : trimesh.Scene
| Copy of scene with scaling applied and units set
| for every model
|
| copy(self) -> 'Scene'
| Return a deep copy of the current scene
|
| Returns
| ----------
| copied : trimesh.Scene
| Copy of the current scene
|
| delete_geometry(self, names: Union[set, str, collections.abc.Sequence]) -> None
| Delete one more multiple geometries from the scene and also
| remove any node in the transform graph which references it.
|
| Parameters
| --------------
| name : hashable
| Name that references self.geometry
|
| dump(self, concatenate: bool = False) -> list[trimesh.parent.Geometry]
| Get a list of every geometry moved to its instance position,
| i.e. freezing or "baking" transforms.
|
| Parameters
| ------------
| concatenate
| KWARG IS DEPRECATED FOR REMOVAL APRIL 2025
| Concatenate results into single geometry.
| This keyword argument will make the type hint incorrect and
| you should replace `Scene.dump(concatenate=True)` with:
| - `Scene.to_geometry()` for a Trimesh, Path2D or Path3D
| - `Scene.to_mesh()` for only `Trimesh` components.
|
| Returns
| ----------
| dumped
| Copies of `Scene.geometry` transformed to their instance position.
|
| explode(self, vector=None, origin=None) -> None
| Explode the current scene in-place around a point and vector.
|
| Parameters
| -----------
| vector : (3,) float or float
| Explode radially around a direction vector or spherically
| origin : (3,) float
| Point to explode around
|
| export(self, file_obj=None, file_type=None, **kwargs)
| Export a snapshot of the current scene.
|
| Parameters
| ----------
| file_obj : str, file-like, or None
| File object to export to
| file_type : str or None
| What encoding to use for meshes
| IE: dict, dict64, stl
|
| Returns
| ----------
| export : bytes
| Only returned if file_obj is None
|
| moment_inertia_frame(self, transform)
| Return the moment of inertia of the current scene relative
| to a transform from the base frame.
|
| Parameters
| transform : (4, 4) float
| Homogeneous transformation matrix.
|
| Returns
| -------------
| inertia : (3, 3) float
| Inertia tensor at requested frame.
|
| reconstruct_instances(self, cost_threshold: Union[float, numpy.floating] = 1e-05) -> 'Scene'
| If a scene has been "baked" with meshes it means that
| the duplicate nodes have *corresponding vertices* but are
| rigidly transformed to different places.
|
| This means the problem of finding ab instance transform can
| use the `procrustes` analysis which is *very* fast relative
| to more complicated registration problems that require ICP
| and nearest-point-on-surface calculations.
|
| TODO : construct a parent non-geometry node for containing every group.
|
| Parameters
| ----------
| scene
| The scene to handle.
| cost_threshold
| The maximum value for `procrustes` cost which is "squared mean
| vertex distance between pair". If the fit is above this value
| the instance will be left even if it is a duplicate.
|
| Returns
| ---------
| dedupe
| A copy of the scene de-duplicated as much as possible.
|
| rezero(self) -> None
| Move the current scene so that the AABB of the whole
| scene is centered at the origin.
|
| Does this by changing the base frame to a new, offset
| base frame.
|
| save_image(self, resolution=None, **kwargs) -> bytes
| Get a PNG image of a scene.
|
| Parameters
| -----------
| resolution : (2,) int
| Resolution to render image
| **kwargs
| Passed to SceneViewer constructor
|
| Returns
| -----------
| png : bytes
| Render of scene as a PNG
|
| scaled(self, scale: Union[float, numpy.floating, collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> 'Scene'
| Return a copy of the current scene, with meshes and scene
| transforms scaled to the requested factor.
|
| Parameters
| -----------
| scale : float or (3,) float
| Factor to scale meshes and transforms
|
| Returns
| -----------
| scaled : trimesh.Scene
| A copy of the current scene but scaled
|
| set_camera(self, angles=None, distance=None, center=None, resolution=None, fov=None) -> trimesh.scene.cameras.Camera
| Create a camera object for self.camera, and add
| a transform to self.graph for it.
|
| If arguments are not passed sane defaults will be figured
| out which show the mesh roughly centered.
|
| Parameters
| -----------
| angles : (3,) float
| Initial euler angles in radians
| distance : float
| Distance from centroid
| center : (3,) float
| Point camera should be center on
| camera : Camera object
| Object that stores camera parameters
|
| show(self, viewer: Union[NoneType, collections.abc.Callable, Literal['gl', 'jupyter', 'marimo']] = None, **kwargs)
| Display the current scene.
|
| Parameters
| -----------
| viewer
| What kind of viewer to use, such as
| `gl` to open a pyglet window
| `jupyter` for a jupyter notebook
| `marimo'` for a marimo notebook
| None for a "best guess"
| kwargs
| Passed to viewer, such as `smooth=False` which will turn
| off automatic smooth shading
|
| simplify_quadric_decimation(self, percent: Union[float, numpy.floating, NoneType] = None, face_count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, aggression: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> None
| Apply in-place `mesh.simplify_quadric_decimation` to any meshes
| in the scene.
|
| Parameters
| -----------
| percent
| A number between 0.0 and 1.0 for how much
| face_count
| Target number of faces desired in the resulting mesh.
| aggression
| An integer between `0` and `10`, the scale being roughly
| `0` is "slow and good" and `10` being "fast and bad."
|
| strip_visuals(self) -> None
| Strip visuals from every Trimesh geometry
| and set them to an empty `ColorVisuals`.
|
| subscene(self, node: str) -> 'Scene'
| Get part of a scene that succeeds a specified node.
|
| Parameters
| ------------
| node
| Hashable key in `scene.graph`
|
| Returns
| -----------
| subscene
| Partial scene generated from current.
|
| to_geometry(self) -> trimesh.parent.Geometry
| Concatenate geometry in the scene into a single like-typed geometry,
| applying the transforms and "baking" the result. May drop geometry
| if the scene has mixed geometry.
|
| Returns
| ---------
| concat
| Either a Trimesh, Path2D, or Path3D depending on what is in the scene.
|
| to_mesh(self) -> 'trimesh.Trimesh'
| Concatenate every mesh instances in the scene into a single mesh,
| applying transforms and "baking" the result. Will drop any geometry
| in the scene that is not a `Trimesh` object.
|
| Returns
| ----------
| mesh
| All meshes in the scene concatenated into one.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| area
| What is the summed area of every geometry which
| has area.
|
| Returns
| ------------
| area : float
| Summed area of every instanced geometry
|
| bounds
| Return the overall bounding box of the scene.
|
| Returns
| --------
| bounds : (2, 3) float or None
| Position of [min, max] bounding box
| Returns None if no valid bounds exist
|
| bounds_corners
| Get the post-transform AABB for each node
| which has geometry defined.
|
| Returns
| -----------
| corners
| Bounds for each node with vertices:
| {node_name : (2, 3) float}
|
| center_mass
| Find the center of mass for every instance in the scene.
|
| Returns
| ------------
| center_mass : (3,) float
| The center of mass of the scene
|
| centroid
| Return the center of the bounding box for the scene.
|
| Returns
| --------
| centroid : (3) float
| Point for center of bounding box
|
| convex_hull
| The convex hull of the whole scene.
|
| Returns
| ---------
| hull : trimesh.Trimesh
| Trimesh object which is a convex hull of all meshes in scene
|
| duplicate_nodes
| Return a sequence of node keys of identical meshes.
|
| Will include meshes with different geometry but identical
| spatial hashes as well as meshes repeated by self.nodes.
|
| Returns
| -----------
| duplicates
| Keys of self.graph that represent identical geometry
|
| extents
| Return the axis aligned box size of the current scene
| or None if the scene is empty.
|
| Returns
| ----------
| extents
| Bounding box sides length or None for empty scene.
|
| geometry_identifiers
| Look up geometries by identifier hash.
|
| Returns
| ---------
| identifiers
| {Identifier hash: key in self.geometry}
|
| has_camera
|
| identifier_hash
| Get a unique identifier for the scene.
|
| is_empty
| Does the scene have anything in it.
|
| Returns
| ----------
| is_empty
| True if nothing is in the scene
|
| is_valid
| Is every geometry connected to the root node.
|
| Returns
| -----------
| is_valid : bool
| Does every geometry have a transform
|
| moment_inertia
| Return the moment of inertia of the current scene with
| respect to the center of mass of the current scene.
|
| Returns
| ------------
| inertia : (3, 3) float
| Inertia with respect to cartesian axis at `scene.center_mass`
|
| scale
| The approximate scale of the mesh
|
| Returns
| -----------
| scale : float
| The mean of the bounding box edge lengths
|
| triangles
| Return a correctly transformed polygon soup of the
| current scene.
|
| Returns
| ----------
| triangles : (n, 3, 3) float
| Triangles in space
|
| triangles_node
| Which node of self.graph does each triangle come from.
|
| Returns
| ---------
| triangles_index : (len(self.triangles),)
| Node name for each triangle
|
| volume
| What is the summed volume of every geometry which
| has volume
|
| Returns
| ------------
| volume : float
| Summed area of every instanced geometry
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| camera
| Get the single camera for the scene. If not manually
| set one will abe automatically generated.
|
| Returns
| ----------
| camera : trimesh.scene.Camera
| Camera object defined for the scene
|
| camera_transform
| Get camera transform in the base frame.
|
| Returns
| -------
| camera_transform : (4, 4) float
| Camera transform in the base frame
|
| lights
| Get a list of the lights in the scene. If nothing is
| set it will generate some automatically.
|
| Returns
| -------------
| lights : [trimesh.scene.lighting.Light]
| Lights in the scene.
|
| units
| Get the units for every model in the scene. If the scene has
| mixed units or no units this will return None.
|
| Returns
| -----------
| units
| Units for every model in the scene or None
| if there are no units or mixed units
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry3D:
|
| apply_obb(self, **kwargs) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
| Apply the oriented bounding box transform to the current mesh.
|
| This will result in a mesh with an AABB centered at the
| origin and the same dimensions as the OBB.
|
| Parameters
| ------------
| kwargs
| Passed through to `bounds.oriented_bounds`
|
| Returns
| ----------
| matrix : (4, 4) float
| Transformation matrix that was applied
| to mesh to move it into OBB frame
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry3D:
|
| bounding_box
| An axis aligned bounding box for the current mesh.
|
| Returns
| ----------
| aabb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the axis aligned bounding box of the mesh
|
| bounding_box_oriented
| An oriented bounding box for the current mesh.
|
| Returns
| ---------
| obb : trimesh.primitives.Box
| Box object with transform and extents defined
| representing the minimum volume oriented
| bounding box of the mesh
|
| bounding_cylinder
| A minimum volume bounding cylinder for the current mesh.
|
| Returns
| --------
| mincyl : trimesh.primitives.Cylinder
| Cylinder primitive containing current mesh
|
| bounding_primitive
| The minimum volume primitive (box, sphere, or cylinder) that
| bounds the mesh.
|
| Returns
| ---------
| bounding_primitive : object
| Smallest primitive which bounds the mesh:
| trimesh.primitives.Sphere
| trimesh.primitives.Box
| trimesh.primitives.Cylinder
|
| bounding_sphere
| A minimum volume bounding sphere for the current mesh.
|
| Note that the Sphere primitive returned has an unpadded
| exact `sphere_radius` so while the distance of every vertex
| of the current mesh from sphere_center will be less than
| sphere_radius, the faceted sphere primitive may not
| contain every vertex.
|
| Returns
| --------
| minball : trimesh.primitives.Sphere
| Sphere primitive containing current mesh
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
split_scene(geometry, **kwargs)
Given a geometry, list of geometries, or a Scene
return them as a single Scene object.
Parameters
----------
geometry : splittable
Returns
---------
scene: trimesh.Scene
DATA
__all__ = ['Camera', 'Scene', 'split_scene']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\scene\__init__.py
trimesh.smoothing
Python Library Documentation: module trimesh.smoothing in trimesh
NAME
trimesh.smoothing
FUNCTIONS
dilate_slope(vertices, faces, normals, v, eps)
Get the derivate of dilation scalar by the volume variation by finite differences
Thus, Vertices += vertex_normals*dilate_slope*(Initial_Volume - Srinked_Volume)
Parameters
-------------
mesh : trimesh.Trimesh
Input geometry
vertices: mesh.vertices
faces: mesh.faces
normals: array
vertices normals
Returns
----------
dilate_slope: float
derivative
filter_humphrey(mesh, alpha=0.1, beta=0.5, iterations=10, laplacian_operator=None)
Smooth a mesh in-place using laplacian smoothing
and Humphrey filtering.
Articles
"Improved Laplacian Smoothing of Noisy Surface Meshes"
J. Vollmer, R. Mencl, and H. Muller
Parameters
------------
mesh : trimesh.Trimesh
Mesh to be smoothed in place
alpha : float
Controls shrinkage, range is 0.0 - 1.0
If 0.0, not considered
If 1.0, no smoothing
beta : float
Controls how aggressive smoothing is
If 0.0, no smoothing
If 1.0, full aggressiveness
iterations : int
Number of passes to run filter
laplacian_operator : None or scipy.sparse.coo.coo_matrix
Sparse matrix laplacian operator
Will be autogenerated if None
filter_laplacian(mesh, lamb=0.5, iterations=10, implicit_time_integration=False, volume_constraint=True, laplacian_operator=None)
Smooth a mesh in-place using laplacian smoothing.
Articles
1 - "Improved Laplacian Smoothing of Noisy Surface Meshes"
J. Vollmer, R. Mencl, and H. Muller
2 - "Implicit Fairing of Irregular Meshes using Diffusion
and Curvature Flow". M. Desbrun, M. Meyer,
P. Schroder, A.H.B. Caltech
Parameters
------------
mesh : trimesh.Trimesh
Mesh to be smoothed in place
lamb : float
Diffusion speed constant
If 0.0, no diffusion
If > 0.0, diffusion occurs
implicit_time_integration: boolean
if False: explicit time integration
-lamb <= 1.0 - Stability Limit (Article 1)
if True: implicit time integration
-lamb no limit (Article 2)
iterations : int
Number of passes to run filter
laplacian_operator : None or scipy.sparse.coo.coo_matrix
Sparse matrix laplacian operator
Will be autogenerated if None
filter_mut_dif_laplacian(mesh, lamb=0.5, iterations=10, volume_constraint=True, laplacian_operator=None)
Smooth a mesh in-place using laplacian smoothing using a
mutable diffusion laplacian.
Articles
Barroqueiro, B., Andrade-Campos, A., Dias-de-Oliveira,
J., and Valente, R. (January 21, 2021).
"Bridging between topology optimization and additive
manufacturing via Laplacian smoothing." ASME. J. Mech. Des.
Parameters
------------
mesh : trimesh.Trimesh
Mesh to be smoothed in place
lamb : float
Diffusion speed constant
If 0.0, no diffusion
If > 0.0, diffusion occurs
iterations : int
Number of passes to run filter
laplacian_operator : None or scipy.sparse.coo.coo_matrix
Sparse matrix laplacian operator
Will be autogenerated if None
filter_taubin(mesh, lamb=0.5, nu=0.5, iterations=10, laplacian_operator=None)
Smooth a mesh in-place using laplacian smoothing
and taubin filtering.
Articles
"Improved Laplacian Smoothing of Noisy Surface Meshes"
J. Vollmer, R. Mencl, and H. Muller
Parameters
------------
mesh : trimesh.Trimesh
Mesh to be smoothed in place.
lamb : float
Controls shrinkage, range is 0.0 - 1.0
nu : float
Controls dilation, range is 0.0 - 1.0
Nu shall be between 0.0 < 1.0/lambda - 1.0/nu < 0.1
iterations : int
Number of passes to run the filter
laplacian_operator : None or scipy.sparse.coo.coo_matrix
Sparse matrix laplacian operator
Will be autogenerated if None
get_vertices_normals(mesh)
Compute Vertex normals using equal weighting of neighbors faces.
Parameters
-------------
mesh : trimesh.Trimesh
Input geometry
Returns
----------
vertices_normals: array
Vertices normals
laplacian_calculation(mesh: trimesh.base.Trimesh, equal_weight: bool = True, pinned_vertices: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None)
Calculate a sparse matrix for laplacian operations.
Note that setting equal_weight to False significantly hampers performance.
Parameters
-------------
mesh : trimesh.Trimesh
Input geometry
equal_weight : bool
If True, all neighbors will be considered equally
If False, all neighbors will be weighted by inverse distance
pinned_vertices : None or list of ints
If None, no vertices are pinned
If list, vertices will be pinned, such that they will not be moved
Returns
----------
laplacian : scipy.sparse.coo.coo_matrix
Laplacian operator
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\smoothing.py
trimesh.tol
Python Library Documentation: ToleranceMesh in module trimesh.constants object
class ToleranceMesh(builtins.object)
| ToleranceMesh(zero: float = np.float64(1e-13), merge: float = 1e-08, planar: float = 1e-05, facet_threshold: int = 5000, strict: bool = False) -> None
|
| ToleranceMesh objects hold tolerance information about meshes.
|
| Parameters
| ----------------
| tol.zero : float
| Floating point numbers smaller than this are considered zero
| tol.merge : float
| When merging vertices, consider vertices closer than this
| to be the same vertex. Here we use the same value (1e-8)
| as SolidWorks uses, according to their documentation.
| tol.planar : float
| The maximum distance from a plane a point can be and
| still be considered to be on the plane
| tol.facet_threshold : float
| Threshold for two facets to be considered coplanar
| tol.strict : bool
| If True, run additional in- process checks (slower)
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __init__(self, zero: float = np.float64(1e-13), merge: float = 1e-08, planar: float = 1e-05, facet_threshold: int = 5000, strict: bool = False) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'facet_threshold': <class 'int'>, 'merge': <class '...
|
| __dataclass_fields__ = {'facet_threshold': Field(name='facet_threshold...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('zero', 'merge', 'planar', 'facet_threshold', 'stric...
|
| facet_threshold = 5000
|
| merge = 1e-08
|
| planar = 1e-05
|
| strict = False
|
| zero = np.float64(1e-13)
trimesh.transform_points
Python Library Documentation: function transform_points in module trimesh.transformations
transform_points(points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], matrix: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], translate: bool = True) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Returns points rotated by a homogeneous
transformation matrix.
If points are (n, 2) matrix must be (3, 3)
If points are (n, 3) matrix must be (4, 4)
Parameters
----------
points : (n, dim) float
Points where `dim` is 2 or 3.
matrix : (3, 3) or (4, 4) float
Homogeneous rotation matrix.
translate : bool
Apply translation from matrix or not.
Returns
----------
transformed : (n, dim) float
Transformed points.
trimesh.transformations
Python Library Documentation: module trimesh.transformations in trimesh
NAME
trimesh.transformations - Homogeneous Transformation Matrices and Quaternions.
DESCRIPTION
A library for calculating 4x4 matrices for translating, rotating, reflecting,
scaling, shearing, projecting, orthogonalizing, and superimposing arrays of
3D homogeneous coordinates as well as for converting between rotation matrices,
Euler angles, and quaternions. Also includes an Arcball control object and
functions to decompose transformation matrices.
:Author:
`Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_
:Organization:
Laboratory for Fluorescence Dynamics, University of California, Irvine
:Version: 2017.02.17
Requirements
------------
* `CPython 2.7 or 3.4 <http://www.python.org>`_
* `numpy 1.9 <http://www.np.org>`_
* `Transformations.c 2015.03.19 <http://www.lfd.uci.edu/~gohlke/>`_
(recommended for speedup of some functions)
Notes
-----
The API is not stable yet and is expected to change between revisions.
This Python code is not optimized for speed. Refer to the transformations.c
module for a faster implementation of some functions.
Documentation in HTML format can be generated with epydoc.
Matrices (M) can be inverted using np.linalg.inv(M), be concatenated using
np.dot(M0, M1), or transform homogeneous coordinate arrays (v) using
np.dot(M, v) for shape (4, *) column vectors, respectively
np.dot(v, M.T) for shape (*, 4) row vectors ("array of points").
This module follows the "column vectors on the right" and "row major storage"
(C contiguous) conventions. The translation components are in the right column
of the transformation matrix, i.e. M[:3, 3].
The transpose of the transformation matrices may have to be used to interface
with other graphics systems, e.g. with OpenGL's glMultMatrixd(). See also [16].
Calculations are carried out with np.float64 precision.
Vector, point, quaternion, and matrix function arguments are expected to be
"array like", i.e. tuple, list, or numpy arrays.
Return types are numpy arrays unless specified otherwise.
Angles are in radians unless specified otherwise.
Quaternions w+ix+jy+kz are represented as [w, x, y, z].
A triple of Euler angles can be applied/interpreted in 24 ways, which can
be specified using a 4 character string or encoded 4-tuple:
*Axes 4-string*: e.g. 'sxyz' or 'ryxy'
- first character : rotations are applied to 's'tatic or 'r'otating frame
- remaining characters : successive rotation axis 'x', 'y', or 'z'
*Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)
- inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix.
- parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed
by 'z', or 'z' is followed by 'x'. Otherwise odd (1).
- repetition : first and last axis are same (1) or different (0).
- frame : rotations are applied to static (0) or rotating (1) frame.
Other Python packages and modules for 3D transformations and quaternions:
* `Transforms3d <https://pypi.python.org/pypi/transforms3d>`_
includes most code of this module.
* `Blender.mathutils <http://www.blender.org/api/blender_python_api>`_
* `numpy-dtypes <https://github.com/numpy/numpy-dtypes>`_
References
----------
(1) Matrices and transformations. Ronald Goldman.
In "Graphics Gems I", pp 472-475. Morgan Kaufmann, 1990.
(2) More matrices and transformations: shear and pseudo-perspective.
Ronald Goldman. In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(3) Decomposing a matrix into simple transformations. Spencer Thomas.
In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(4) Recovering the data from the transformation matrix. Ronald Goldman.
In "Graphics Gems II", pp 324-331. Morgan Kaufmann, 1991.
(5) Euler angle conversion. Ken Shoemake.
In "Graphics Gems IV", pp 222-229. Morgan Kaufmann, 1994.
(6) Arcball rotation control. Ken Shoemake.
In "Graphics Gems IV", pp 175-192. Morgan Kaufmann, 1994.
(7) Representing attitude: Euler angles, unit quaternions, and rotation
vectors. James Diebel. 2006.
(8) A discussion of the solution for the best rotation to relate two sets
of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828.
(9) Closed-form solution of absolute orientation using unit quaternions.
BKP Horn. J Opt Soc Am A. 1987. 4(4):629-642.
(10) Quaternions. Ken Shoemake.
http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf
(11) From quaternion to matrix and back. JMP van Waveren. 2005.
http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm
(12) Uniform random rotations. Ken Shoemake.
In "Graphics Gems III", pp 124-132. Morgan Kaufmann, 1992.
(13) Quaternion in molecular modeling. CFF Karney.
J Mol Graph Mod, 25(5):595-604
(14) New method for extracting the quaternion from a rotation matrix.
Itzhack Y Bar-Itzhack, J Guid Contr Dynam. 2000. 23(6): 1085-1087.
(15) Multiple View Geometry in Computer Vision. Hartley and Zissermann.
Cambridge University Press; 2nd Ed. 2004. Chapter 4, Algorithm 4.7, p 130.
(16) Column Vectors vs. Row Vectors.
http://steve.hollasch.net/cgindex/math/matrix/column-vec.html
Examples
--------
>>> alpha, beta, gamma = 0.123, -1.234, 2.345
>>> origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]
>>> I = identity_matrix()
>>> Rx = rotation_matrix(alpha, xaxis)
>>> Ry = rotation_matrix(beta, yaxis)
>>> Rz = rotation_matrix(gamma, zaxis)
>>> R = concatenate_matrices(Rx, Ry, Rz)
>>> euler = euler_from_matrix(R, 'rxyz')
>>> np.allclose([alpha, beta, gamma], euler)
True
>>> Re = euler_matrix(alpha, beta, gamma, 'rxyz')
>>> is_same_transform(R, Re)
True
>>> al, be, ga = euler_from_matrix(Re, 'rxyz')
>>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz'))
True
>>> qx = quaternion_about_axis(alpha, xaxis)
>>> qy = quaternion_about_axis(beta, yaxis)
>>> qz = quaternion_about_axis(gamma, zaxis)
>>> q = quaternion_multiply(qx, qy)
>>> q = quaternion_multiply(q, qz)
>>> Rq = quaternion_matrix(q)
>>> is_same_transform(R, Rq)
True
>>> S = scale_matrix(1.23, origin)
>>> T = translation_matrix([1, 2, 3])
>>> Z = shear_matrix(beta, xaxis, origin, zaxis)
>>> R = random_rotation_matrix(np.random.rand(3))
>>> M = concatenate_matrices(T, R, Z, S)
>>> scale, shear, angles, trans, persp = decompose_matrix(M)
>>> np.allclose(scale, 1.23)
True
>>> np.allclose(trans, [1, 2, 3])
True
>>> np.allclose(shear, [0, np.tan(beta), 0])
True
>>> is_same_transform(R, euler_matrix(axes='sxyz', *angles))
True
>>> M1 = compose_matrix(scale, shear, angles, trans, persp)
>>> is_same_transform(M, M1)
True
>>> v0, v1 = random_vector(3), random_vector(3)
>>> M = rotation_matrix(angle_between_vectors(v0, v1), vector_product(v0, v1))
>>> v2 = np.dot(v0, M[:3,:3].T)
>>> np.allclose(unit_vector(v1), unit_vector(v2))
True
CLASSES
builtins.object
Arcball
class Arcball(builtins.object)
| Arcball(initial=None)
|
| Virtual Trackball Control.
|
| >>> ball = Arcball()
| >>> ball = Arcball(initial=np.identity(4))
| >>> ball.place([320, 320], 320)
| >>> ball.down([500, 250])
| >>> ball.drag([475, 275])
| >>> R = ball.matrix()
| >>> np.allclose(np.sum(R), 3.90583455)
| True
| >>> ball = Arcball(initial=[1, 0, 0, 0])
| >>> ball.place([320, 320], 320)
| >>> ball.setaxes([1, 1, 0], [-1, 1, 0])
| >>> ball.constrain = True
| >>> ball.down([400, 200])
| >>> ball.drag([200, 400])
| >>> R = ball.matrix()
| >>> np.allclose(np.sum(R), 0.2055924)
| True
| >>> ball.next()
|
| Methods defined here:
|
| __init__(self, initial=None)
| Initialize virtual trackball control.
|
| initial : quaternion or rotation matrix
|
| down(self, point)
| Set initial cursor window coordinates and pick constrain-axis.
|
| drag(self, point)
| Update current cursor window coordinates.
|
| matrix(self)
| Return homogeneous rotation matrix.
|
| next(self, acceleration=0.0)
| Continue rotation in direction of last drag.
|
| place(self, center, radius)
| Place Arcball, e.g. when window size changes.
|
| center : sequence[2]
| Window coordinates of trackball center.
| radius : float
| Radius of trackball in window coordinates.
|
| setaxes(self, *axes)
| Set axes to constrain rotations.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| constrain
| Return state of constrain to axis mode.
FUNCTIONS
affine_matrix_from_points(v0, v1, shear=True, scale=True, usesvd=True)
Return affine transform matrix to register two point sets.
v0 and v1 are shape (ndims, *) arrays of at least ndims non-homogeneous
coordinates, where ndims is the dimensionality of the coordinate space.
If shear is False, a similarity transformation matrix is returned.
If also scale is False, a rigid/Euclidean transformation matrix
is returned.
By default the algorithm by Hartley and Zissermann [15] is used.
If usesvd is True, similarity and Euclidean transformation matrices
are calculated by minimizing the weighted sum of squared deviations
(RMSD) according to the algorithm by Kabsch [8].
Otherwise, and if ndims is 3, the quaternion based algorithm by Horn [9]
is used, which is slower when using this Python implementation.
The returned matrix performs rotation, translation and uniform scaling
(if specified).
>>> v0 = [[0, 1031, 1031, 0], [0, 0, 1600, 1600]]
>>> v1 = [[675, 826, 826, 677], [55, 52, 281, 277]]
>>> mat = affine_matrix_from_points(v0, v1)
>>> T = translation_matrix(np.random.random(3)-0.5)
>>> R = random_rotation_matrix(np.random.random(3))
>>> S = scale_matrix(random.random())
>>> M = concatenate_matrices(T, R, S)
>>> v0 = (np.random.rand(4, 100) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = np.dot(M, v0)
>>> v0[:3] += np.random.normal(0, 1e-8, 300).reshape(3, -1)
>>> M = affine_matrix_from_points(v0[:3], v1[:3])
>>> check = np.allclose(v1, np.dot(M, v0))
More examples in superimposition_matrix()
angle_between_vectors(v0, v1, directed=True, axis=0)
Return angle between vectors.
If directed is False, the input vectors are interpreted as undirected axes,
i.e. the maximum angle is pi/2.
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
>>> np.allclose(a, np.pi)
True
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
>>> np.allclose(a, 0)
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> a = angle_between_vectors(v0, v1)
>>> np.allclose(a, [0, 1.5708, 1.5708, 0.95532])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> a = angle_between_vectors(v0, v1, axis=1)
>>> np.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
True
arcball_constrain_to_axis(point, axis)
Return sphere point perpendicular to axis.
arcball_map_to_sphere(point, center, radius)
Return unit sphere coordinates from window coordinates.
arcball_nearest_axis(point, axes)
Return axis, which arc is nearest to point.
clip_matrix(left, right, bottom, top, near, far, perspective=False)
Return matrix to obtain normalized device coordinates from frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinates are
inside the frustum.
If perspective is True the frustum is a truncated pyramid with the
perspective point at origin and direction along z axis, otherwise an
orthographic canonical view volume (a box).
Homogeneous coordinates transformed by the perspective clip matrix
need to be dehomogenized (divided by w coordinate).
>>> frustum = np.random.rand(6)
>>> frustum[1] += frustum[0]
>>> frustum[3] += frustum[2]
>>> frustum[5] += frustum[4]
>>> M = clip_matrix(perspective=False, *frustum)
>>> a = np.dot(M, [frustum[0], frustum[2], frustum[4], 1])
>>> np.allclose(a, [-1., -1., -1., 1.])
True
>>> b = np.dot(M, [frustum[1], frustum[3], frustum[5], 1])
>>> np.allclose(b, [ 1., 1., 1., 1.])
True
>>> M = clip_matrix(perspective=True, *frustum)
>>> v = np.dot(M, [frustum[0], frustum[2], frustum[4], 1])
>>> c = v / v[3]
>>> np.allclose(c, [-1., -1., -1., 1.])
True
>>> v = np.dot(M, [frustum[1], frustum[3], frustum[4], 1])
>>> d = v / v[3]
>>> np.allclose(d, [ 1., 1., -1., 1.])
True
compose_matrix(scale=None, shear=None, angles=None, translate=None, perspective=None)
Return transformation matrix from sequence of transformations.
This is the inverse of the decompose_matrix function.
Sequence of transformations:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
>>> scale = np.random.random(3) - 0.5
>>> shear = np.random.random(3) - 0.5
>>> angles = (np.random.random(3) - 0.5) * (2*np.pi)
>>> trans = np.random.random(3) - 0.5
>>> persp = np.random.random(4) - 0.5
>>> M0 = compose_matrix(scale, shear, angles, trans, persp)
>>> result = decompose_matrix(M0)
>>> M1 = compose_matrix(*result)
>>> is_same_transform(M0, M1)
True
concatenate_matrices(*matrices)
Return concatenation of series of transformation matrices.
>>> M = np.random.rand(16).reshape((4, 4)) - 0.5
>>> np.allclose(M, concatenate_matrices(M))
True
>>> np.allclose(np.dot(M, M.T), concatenate_matrices(M, M.T))
True
decompose_matrix(matrix)
Return sequence of transformations from transformation matrix.
matrix : array_like
Non-degenerative homogeneous transformation matrix
Return tuple of:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
Raise ValueError if matrix is of wrong type or degenerative.
>>> T0 = translation_matrix([1, 2, 3])
>>> scale, shear, angles, trans, persp = decompose_matrix(T0)
>>> T1 = translation_matrix(trans)
>>> np.allclose(T0, T1)
True
>>> S = scale_matrix(0.123)
>>> scale, shear, angles, trans, persp = decompose_matrix(S)
>>> bool(np.isclose(scale[0], 0.123))
True
>>> R0 = euler_matrix(1, 2, 3)
>>> scale, shear, angles, trans, persp = decompose_matrix(R0)
>>> R1 = euler_matrix(*angles)
>>> np.allclose(R0, R1)
True
euler_from_matrix(matrix, axes='sxyz')
Return Euler angles from rotation matrix for specified axis sequence.
axes : One of 24 axis sequences as string or encoded tuple
Note that many Euler angle triplets can describe one matrix.
>>> R0 = euler_matrix(1, 2, 3, 'syxz')
>>> al, be, ga = euler_from_matrix(R0, 'syxz')
>>> R1 = euler_matrix(al, be, ga, 'syxz')
>>> np.allclose(R0, R1)
True
>>> angles = (4*np.pi) * (np.random.random(3) - 0.5)
>>> for axes in _AXES2TUPLE.keys():
... R0 = euler_matrix(axes=axes, *angles)
... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes))
... if not np.allclose(R0, R1): print(axes, "failed")
euler_from_quaternion(quaternion, axes='sxyz')
Return Euler angles from quaternion for specified axis sequence.
>>> angles = euler_from_quaternion([0.99810947, 0.06146124, 0, 0])
>>> np.allclose(angles, [0.123, 0, 0])
True
euler_matrix(ai, aj, ak, axes='sxyz')
Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> np.allclose(np.sum(R[0]), -1.34786452)
True
>>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1))
>>> np.allclose(np.sum(R[0]), -0.383436184)
True
>>> ai, aj, ak = (4*np.pi) * (np.random.random(3) - 0.5)
>>> for axes in _AXES2TUPLE.keys():
... R = euler_matrix(ai, aj, ak, axes)
>>> for axes in _TUPLE2AXES.keys():
... R = euler_matrix(ai, aj, ak, axes)
fix_rigid(matrix, max_deviance=1e-05)
If a homogeneous transformation matrix is *almost* a rigid
transform but many matrix-multiplies have accumulated some
floating point error try to restore the matrix using SVD.
Parameters
-----------
matrix : (4, 4) or (3, 3) float
Homogeneous transformation matrix.
max_deviance : float
Do not alter the matrix if it is not rigid by more
than this amount.
Returns
----------
repaired : (4, 4) or (3, 3) float
Repaired homogeneous transformation matrix
flips_winding(matrix)
Check to see if a matrix will invert triangles.
Parameters
-------------
matrix : (4, 4) float
Homogeneous transformation matrix
Returns
--------------
flip : bool
True if matrix will flip winding of triangles.
identity_matrix()
Return 4x4 identity/unit matrix.
>>> I = identity_matrix()
>>> np.allclose(I, np.dot(I, I))
True
>>> float(np.sum(I)), float(np.trace(I))
(4.0, 4.0)
>>> np.allclose(I, np.identity(4))
True
inverse_matrix(matrix)
Return inverse of square transformation matrix.
>>> M0 = random_rotation_matrix()
>>> M1 = inverse_matrix(M0.T)
>>> np.allclose(M1, np.linalg.inv(M0.T))
True
>>> for size in range(1, 7):
... M0 = np.random.rand(size, size)
... M1 = inverse_matrix(M0)
... if not np.allclose(M1, np.linalg.inv(M0)): print(size)
is_rigid(matrix, epsilon=1e-08)
Check to make sure a homogeonous transformation
matrix is a rigid transform.
Parameters
-----------
matrix : (4, 4) float
A transformation matrix
Returns
-----------
check : bool
True if matrix is a a transform with
only translation, scale, and rotation
is_same_quaternion(q0, q1)
Return True if two quaternions are equal.
is_same_transform(matrix0, matrix1)
Return True if two matrices perform same transformation.
>>> is_same_transform(np.identity(4), np.identity(4))
True
>>> is_same_transform(np.identity(4), random_rotation_matrix())
False
orthogonalization_matrix(lengths, angles)
Return orthogonalization matrix for crystallographic cell coordinates.
Angles are expected in degrees.
The de-orthogonalization matrix is the inverse.
>>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90])
>>> np.allclose(O[:3, :3], np.identity(3, float) * 10)
True
>>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
>>> np.allclose(np.sum(O), 43.063229)
True
planar_matrix(offset=None, theta=None, point=None, scale=None)
2D homogeonous transformation matrix.
Parameters
----------
offset : (2,) float
XY offset
theta : float
Rotation around Z in radians
point : (2, ) float
Point to rotate around
scale : (2,) float or None
Scale to apply
Returns
----------
matrix : (3, 3) flat
Homogeneous 2D transformation matrix
planar_matrix_to_3D(matrix_2D)
Given a 2D homogeneous rotation matrix convert it to a 3D rotation
matrix that is rotating around the Z axis
Parameters
----------
matrix_2D: (3,3) float, homogeneous 2D rotation matrix
Returns
----------
matrix_3D: (4,4) float, homogeneous 3D rotation matrix
projection_from_matrix(matrix, pseudo=False)
Return projection plane and perspective point from projection matrix.
Return values are same as arguments for projection_matrix function:
point, normal, direction, perspective, and pseudo.
>>> point = np.random.random(3) - 0.5
>>> normal = np.random.random(3) - 0.5
>>> direct = np.random.random(3) - 0.5
>>> persp = np.random.random(3) - 0.5
>>> P0 = projection_matrix(point, normal)
>>> result = projection_from_matrix(P0)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, direct)
>>> result = projection_from_matrix(P0)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False)
>>> result = projection_from_matrix(P0, pseudo=False)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True)
>>> result = projection_from_matrix(P0, pseudo=True)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
projection_matrix(point, normal, direction=None, perspective=None, pseudo=False)
Return matrix to project onto plane defined by point and normal.
Using either perspective point, projection direction, or none of both.
If pseudo is True, perspective projections will preserve relative depth
such that Perspective = dot(Orthogonal, PseudoPerspective).
>>> P = projection_matrix([0, 0, 0], [1, 0, 0])
>>> np.allclose(P[1:, 1:], np.identity(4)[1:, 1:])
True
>>> point = np.random.random(3) - 0.5
>>> normal = np.random.random(3) - 0.5
>>> direct = np.random.random(3) - 0.5
>>> persp = np.random.random(3) - 0.5
>>> P0 = projection_matrix(point, normal)
>>> P1 = projection_matrix(point, normal, direction=direct)
>>> P2 = projection_matrix(point, normal, perspective=persp)
>>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True)
>>> is_same_transform(P2, np.dot(P0, P3))
True
>>> P = projection_matrix([3, 0, 0], [1, 1, 0], [1, 0, 0])
>>> v0 = (np.random.rand(4, 5) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = np.dot(P, v0)
>>> np.allclose(v1[1], v0[1])
True
>>> np.allclose(v1[0], 3-v1[1])
True
quaternion_about_axis(angle, axis)
Return quaternion for rotation about axis.
>>> q = quaternion_about_axis(0.123, [1, 0, 0])
>>> np.allclose(q, [0.99810947, 0.06146124, 0, 0])
True
quaternion_conjugate(quaternion)
Return conjugate of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_conjugate(q0)
>>> q1[0] == q0[0] and all(q1[1:] == -q0[1:])
True
quaternion_from_euler(ai, aj, ak, axes='sxyz')
Return quaternion from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> q = quaternion_from_euler(1, 2, 3, 'ryxz')
>>> np.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435])
True
quaternion_from_matrix(matrix, isprecise=False)
Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
>>> q = quaternion_from_matrix(np.identity(4), True)
>>> np.allclose(q, [1, 0, 0, 0])
True
>>> q = quaternion_from_matrix(np.diag([1, -1, -1, 1]))
>>> np.allclose(q, [0, 1, 0, 0]) or np.allclose(q, [0, -1, 0, 0])
True
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R, True)
>>> np.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786])
True
>>> R = [[-0.545, 0.797, 0.260, 0], [0.733, 0.603, -0.313, 0],
... [-0.407, 0.021, -0.913, 0], [0, 0, 0, 1]]
>>> q = quaternion_from_matrix(R)
>>> np.allclose(q, [0.19069, 0.43736, 0.87485, -0.083611])
True
>>> R = [[0.395, 0.362, 0.843, 0], [-0.626, 0.796, -0.056, 0],
... [-0.677, -0.498, 0.529, 0], [0, 0, 0, 1]]
>>> q = quaternion_from_matrix(R)
>>> np.allclose(q, [0.82336615, -0.13610694, 0.46344705, -0.29792603])
True
>>> R = random_rotation_matrix()
>>> q = quaternion_from_matrix(R)
>>> is_same_transform(R, quaternion_matrix(q))
True
>>> is_same_quaternion(quaternion_from_matrix(R, isprecise=False),
... quaternion_from_matrix(R, isprecise=True))
True
>>> R = euler_matrix(0.0, 0.0, np.pi/2.0)
>>> is_same_quaternion(quaternion_from_matrix(R, isprecise=False),
... quaternion_from_matrix(R, isprecise=True))
True
quaternion_imag(quaternion)
Return imaginary part of quaternion.
>>> quaternion_imag([3, 0, 1, 2])
array([0., 1., 2.])
quaternion_inverse(quaternion)
Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> np.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True
quaternion_matrix(quaternion)
Return a homogeneous rotation matrix from quaternion.
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> np.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> np.allclose(M, np.identity(4))
True
>>> M = quaternion_matrix([0, 1, 0, 0])
>>> np.allclose(M, np.diag([1, -1, -1, 1]))
True
>>> M = quaternion_matrix([[1, 0, 0, 0],[0, 1, 0, 0]])
>>> np.allclose(M, np.array([np.identity(4), np.diag([1, -1, -1, 1])]))
True
quaternion_multiply(quaternion1, quaternion0)
Return multiplication of two quaternions.
>>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7])
>>> np.allclose(q, [28, -44, -14, 48])
True
quaternion_real(quaternion)
Return real part of quaternion.
>>> quaternion_real([3, 0, 1, 2])
3.0
quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True)
Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0)
>>> np.allclose(q, q0)
True
>>> q = quaternion_slerp(q0, q1, 1, 1)
>>> np.allclose(q, q1)
True
>>> q = quaternion_slerp(q0, q1, 0.5)
>>> angle = np.arccos(np.dot(q0, q))
>>> np.allclose(2, np.arccos(np.dot(q0, q1)) / angle) or np.allclose(2, np.arccos(-np.dot(q0, q1)) / angle)
True
random_quaternion(rand=None, num=1)
Return uniform random unit quaternion.
rand: array like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
>>> q = random_quaternion()
>>> np.allclose(1, vector_norm(q))
True
>>> q = random_quaternion(num=10)
>>> np.allclose(1, vector_norm(q, axis=1))
True
>>> q = random_quaternion(np.random.random(3))
>>> len(q.shape), q.shape[0]==4
(1, True)
random_rotation_matrix(rand: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, num: Union[int, numpy.integer, numpy.unsignedinteger] = 1, translate: Union[float, numpy.floating, int, numpy.integer, numpy.unsignedinteger, NoneType] = None)
Return uniform random rotation matrix.
Parameters
------------
rand : (3,)
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
num
Number of matrices to return.
translate
If passed the rotation matrix will include translation
that is random and between positive and negative half this value.
>>> R = random_rotation_matrix()
>>> np.allclose(np.dot(R.T, R), np.identity(4))
True
>>> R = random_rotation_matrix(num=10)
>>> np.allclose(np.einsum('...ji,...jk->...ik', R, R), np.identity(4))
True
random_vector(size)
Return array of random doubles in the half-open interval [0.0, 1.0).
>>> v = random_vector(10000)
>>> bool(np.all(v >= 0) and np.all(v < 1))
True
>>> v0 = random_vector(10)
>>> v1 = random_vector(10)
>>> bool(np.any(v0 == v1))
False
reflection_from_matrix(matrix)
Return mirror plane point and normal vector from reflection matrix.
>>> v0 = np.random.random(3) - 0.5
>>> v1 = np.random.random(3) - 0.5
>>> M0 = reflection_matrix(v0, v1)
>>> point, normal = reflection_from_matrix(M0)
>>> M1 = reflection_matrix(point, normal)
>>> is_same_transform(M0, M1)
True
reflection_matrix(point, normal)
Return matrix to mirror at plane defined by point and normal vector.
>>> v0 = np.random.random(4) - 0.5
>>> v0[3] = 1.
>>> v1 = np.random.random(3) - 0.5
>>> R = reflection_matrix(v0, v1)
>>> np.allclose(2, np.trace(R))
True
>>> np.allclose(v0, np.dot(R, v0))
True
>>> v2 = v0.copy()
>>> v2[:3] += v1
>>> v3 = v0.copy()
>>> v2[:3] -= v1
>>> np.allclose(v2, np.dot(R, v3))
True
rotation_from_matrix(matrix)
Return rotation angle and axis from rotation matrix.
>>> angle = (random.random() - 0.5) * (2*np.pi)
>>> direc = np.random.random(3) - 0.5
>>> point = np.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True
rotation_matrix(angle, direction, point=None)
Return matrix to rotate about axis defined by point and
direction.
Parameters
-------------
angle : float, or sympy.Symbol
Angle, in radians or symbolic angle
direction : (3,) float
Any vector along rotation axis
point : (3, ) float, or None
Origin point of rotation axis
Returns
-------------
matrix : (4, 4) float, or (4, 4) sympy.Matrix
Homogeneous transformation matrix
Examples
-------------
>>> R = rotation_matrix(np.pi/2, [0, 0, 1], [1, 0, 0])
>>> np.allclose(np.dot(R, [0, 0, 0, 1]), [1, -1, 0, 1])
True
>>> angle = (random.random() - 0.5) * (2*np.pi)
>>> direc = np.random.random(3) - 0.5
>>> point = np.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(angle-2*np.pi, direc, point)
>>> is_same_transform(R0, R1)
True
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(-angle, -direc, point)
>>> is_same_transform(R0, R1)
True
>>> I = np.identity(4, np.float64)
>>> np.allclose(I, rotation_matrix(np.pi*2, direc))
True
>>> np.allclose(2, np.trace(rotation_matrix(np.pi/2,direc,point)))
True
scale_and_translate(scale=None, translate=None)
Optimized version of `compose_matrix` for just
scaling then translating.
Scalar args are broadcast to arrays of shape (3,)
Parameters
--------------
scale : float or (3,) float
Scale factor
translate : float or (3,) float
Translation
scale_from_matrix(matrix)
Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = np.random.random(3) - 0.5
>>> direct = np.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
>>> S0 = scale_matrix(factor, origin, direct)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
scale_matrix(factor, origin=None, direction=None)
Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
>>> v = (np.random.rand(4, 5) - 0.5) * 20
>>> v[3] = 1
>>> S = scale_matrix(-1.234)
>>> np.allclose(np.dot(S, v)[:3], -1.234*v[:3])
True
>>> factor = random.random() * 10 - 5
>>> origin = np.random.random(3) - 0.5
>>> direct = np.random.random(3) - 0.5
>>> S = scale_matrix(factor, origin)
>>> S = scale_matrix(factor, origin, direct)
shear_from_matrix(matrix)
Return shear angle, direction and plane from shear matrix.
>>> angle = np.pi / 2.0
>>> direct = [0.0, 1.0, 0.0]
>>> point = [0.0, 0.0, 0.0]
>>> normal = np.cross(direct, np.roll(direct,1))
>>> S0 = shear_matrix(angle, direct, point, normal)
>>> angle, direct, point, normal = shear_from_matrix(S0)
>>> S1 = shear_matrix(angle, direct, point, normal)
>>> is_same_transform(S0, S1)
True
shear_matrix(angle, direction, point, normal)
Return matrix to shear by angle along direction vector on shear plane.
The shear plane is defined by a point and normal vector. The direction
vector must be orthogonal to the plane's normal vector.
A point P is transformed by the shear matrix into P" such that
the vector P-P" is parallel to the direction vector and its extent is
given by the angle of P-P'-P", where P' is the orthogonal projection
of P onto the shear plane.
>>> angle = (random.random() - 0.5) * 4*np.pi
>>> direct = np.random.random(3) - 0.5
>>> point = np.random.random(3) - 0.5
>>> normal = np.cross(direct, np.random.random(3))
>>> S = shear_matrix(angle, direct, point, normal)
>>> np.allclose(1, np.linalg.det(S))
True
spherical_matrix(theta, phi, axes='sxyz')
Give a spherical coordinate vector, find the rotation that will
transform a [0,0,1] vector to those coordinates
Parameters
-----------
theta: float, rotation angle in radians
phi: float, rotation angle in radians
Returns
----------
matrix: (4,4) rotation matrix where the following will
be a cartesian vector in the direction of the
input spherical coordinates:
np.dot(matrix, [0,0,1,0])
superimposition_matrix(v0, v1, scale=False, usesvd=True)
Return matrix to transform given 3D point set into second point set.
v0 and v1 are shape (3, *) or (4, *) arrays of at least 3 points.
The parameters scale and usesvd are explained in the more general
affine_matrix_from_points function.
The returned matrix is a similarity or Euclidean transformation matrix.
This function has a fast C implementation in transformations.c.
>>> v0 = np.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> np.allclose(M, np.identity(4))
True
>>> R = random_rotation_matrix(np.random.random(3))
>>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]]
>>> v1 = np.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> np.allclose(v1, np.dot(M, v0))
True
>>> v0 = (np.random.rand(4, 100) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = np.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> np.allclose(v1, np.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(np.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = np.dot(M, v0)
>>> v0[:3] += np.random.normal(0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scale=True)
>>> np.allclose(v1, np.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> np.allclose(v1, np.dot(M, v0))
True
>>> v = np.zeros((4, 100, 3))
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> np.allclose(v1, np.dot(M, v[:, :, 0]))
True
transform_around(matrix, point)
Given a transformation matrix, apply its rotation
around a point in space.
Parameters
----------
matrix: (4,4) or (3, 3) float, transformation matrix
point: (3,) or (2,) float, point in space
Returns
---------
result: (4,4) transformation matrix
transform_points(points: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], matrix: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], translate: bool = True) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Returns points rotated by a homogeneous
transformation matrix.
If points are (n, 2) matrix must be (3, 3)
If points are (n, 3) matrix must be (4, 4)
Parameters
----------
points : (n, dim) float
Points where `dim` is 2 or 3.
matrix : (3, 3) or (4, 4) float
Homogeneous rotation matrix.
translate : bool
Apply translation from matrix or not.
Returns
----------
transformed : (n, dim) float
Transformed points.
translation_from_matrix(matrix)
Return translation vector from translation matrix.
>>> v0 = np.random.random(3) - 0.5
>>> v1 = translation_from_matrix(translation_matrix(v0))
>>> np.allclose(v0, v1)
True
translation_matrix(direction)
Return matrix to translate by direction vector.
>>> v = np.random.random(3) - 0.5
>>> np.allclose(v, translation_matrix(v)[:3, 3])
True
unit_vector(data, axis=None, out=None)
Return ndarray normalized by length, i.e. Euclidean norm, along axis.
>>> v0 = np.random.random(3)
>>> v1 = unit_vector(v0)
>>> np.allclose(v1, v0 / np.linalg.norm(v0))
True
>>> v0 = np.random.rand(5, 4, 3)
>>> v1 = unit_vector(v0, axis=-1)
>>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=2)), 2)
>>> np.allclose(v1, v2)
True
>>> v1 = unit_vector(v0, axis=1)
>>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=1)), 1)
>>> np.allclose(v1, v2)
True
>>> v1 = np.zeros((5, 4, 3))
>>> unit_vector(v0, axis=1, out=v1)
>>> np.allclose(v1, v2)
True
>>> list(unit_vector([]))
[]
>>> [float(i) for i in unit_vector([1])]
[1.0]
vector_norm(data, axis=None, out=None)
Return length, i.e. Euclidean norm, of ndarray along axis.
>>> v = np.random.random(3)
>>> n = vector_norm(v)
>>> np.allclose(n, np.linalg.norm(v))
True
>>> v = np.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>> np.allclose(n, np.sqrt(np.sum(v*v, axis=2)))
True
>>> n = vector_norm(v, axis=1)
>>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))
True
>>> v = np.random.rand(5, 4, 3)
>>> n = np.zeros((5, 3))
>>> vector_norm(v, axis=1, out=n)
>>> np.allclose(n, np.sqrt(np.sum(v*v, axis=1)))
True
>>> float(vector_norm([]))
0.0
>>> float(vector_norm([1]))
1.0
vector_product(v0, v1, axis=0)
Return vector perpendicular to vectors.
>>> v = vector_product([2, 0, 0], [0, 3, 0])
>>> np.allclose(v, [0, 0, 6])
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> v = vector_product(v0, v1)
>>> np.allclose(v, [[0, 0, 0, 0], [0, 0, 6, 6], [0, -6, 0, -6]])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> v = vector_product(v0, v1, axis=1)
>>> np.allclose(v, [[0, 0, 6], [0, -6, 0], [6, 0, 0], [0, -6, 6]])
True
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\transformations.py
trimesh.triangles
Python Library Documentation: module trimesh.triangles in trimesh
NAME
trimesh.triangles
DESCRIPTION
triangles.py
-------------
Functions for dealing with triangle soups in (n, 3, 3) float form.
CLASSES
builtins.object
MassProperties
class MassProperties(builtins.object)
| MassProperties(density: float, mass: float, volume: float, center_mass: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], inertia: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None) -> None
|
| MassProperties(density: float, mass: float, volume: float, center_mass: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], inertia: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None)
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __getitem__(self, item: str)
|
| __init__(self, density: float, mass: float, volume: float, center_mass: numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]], inertia: Optional[numpy.ndarray[Any, numpy.dtype[numpy.float64]]] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'center_mass': numpy.ndarray[typing.Any, numpy.dtyp...
|
| __dataclass_fields__ = {'center_mass': Field(name='center_mass',type=n...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __hash__ = None
|
| __match_args__ = ('density', 'mass', 'volume', 'center_mass', 'inertia...
|
| inertia = None
FUNCTIONS
all_coplanar(triangles)
Check to see if a list of triangles are all coplanar
Parameters
----------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
---------------
all_coplanar : bool
True if all triangles are coplanar
angles(triangles)
Calculates the angles of input triangles.
Parameters
------------
triangles : (n, 3, 3) float
Vertex positions
Returns
------------
angles : (n, 3) float
Angles at vertex positions in radians
Degenerate angles will be returned as zero
any_coplanar(triangles)
For a list of triangles if the FIRST triangle is coplanar
with ANY of the following triangles, return True.
Otherwise, return False.
area(triangles=None, crosses=None)
Calculates the sum area of input triangles
Parameters
----------
triangles : (n, 3, 3) float
Vertices of triangles
crosses : (n, 3) float or None
As a speedup don't re- compute cross products
sum : bool
Return summed area or individual triangle area
Returns
----------
area : (n,) float or float
Individual or summed area depending on `sum` argument
barycentric_to_points(triangles, barycentric)
Convert a list of barycentric coordinates on a list of triangles
to cartesian points.
Parameters
------------
triangles : (n, 3, 3) float
Triangles in space
barycentric : (n, 2) float
Barycentric coordinates
Returns
-----------
points : (m, 3) float
Points in space
bounds_tree(triangles)
Given a list of triangles, create an r-tree for broad- phase
collision detection
Parameters
---------
triangles : (n, 3, 3) float
Triangles in space
Returns
---------
tree : rtree.Rtree
One node per triangle
closest_point(triangles, points)
Return the closest point on the surface of each triangle for a
list of corresponding points.
Implements the method from "Real Time Collision Detection" and
use the same variable names as "ClosestPtPointTriangle" to avoid
being any more confusing.
Parameters
----------
triangles : (n, 3, 3) float
Triangle vertices in space
points : (n, 3) float
Points in space
Returns
----------
closest : (n, 3) float
Point on each triangle closest to each point
cross(triangles: numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Returns the cross product of two edges from input triangles
Parameters
--------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
--------------
crosses : (n, 3) float
Cross product of two edge vectors
extents(triangles, areas=None)
Return the 2D bounding box size of each triangle.
Parameters
----------
triangles : (n, 3, 3) float
Triangles in space
areas : (n,) float
Optional area of input triangles
Returns
----------
box : (n, 2) float
The size of each triangle's 2D oriented bounding box
mass_properties(triangles, crosses=None, density=None, center_mass=None, skip_inertia=False) -> trimesh.triangles.MassProperties
Calculate the mass properties of a group of triangles.
Implemented from:
http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf
Parameters
----------
triangles : (n, 3, 3) float
Triangle vertices in space
crosses : (n,) float
Optional cross products of triangles
density : float
Optional override for density
center_mass : (3,) float
Optional override for center mass
skip_inertia : bool
if True will not return moments matrix
Returns
---------
info : dict
Mass properties
nondegenerate(triangles, areas=None, height=None)
Find all triangles which have an oriented bounding box
where both of the two sides is larger than a specified height.
Degenerate triangles can be when:
1) Two of the three vertices are colocated
2) All three vertices are unique but colinear
Parameters
----------
triangles : (n, 3, 3) float
Triangles in space
height : float
Minimum edge length of a triangle to keep
Returns
----------
nondegenerate : (n,) bool
True if a triangle meets required minimum height
normals(triangles=None, crosses=None)
Calculates the normals of input triangles
Parameters
------------
triangles : (n, 3, 3) float
Vertex positions
crosses : (n, 3) float
Cross products of edge vectors
Returns
------------
normals : (m, 3) float
Normal vectors
valid : (n,) bool
Was the face nonzero area or not
points_to_barycentric(triangles, points, method='cramer')
Find the barycentric coordinates of points relative to triangles.
The Cramer's rule solution implements:
http://blackpawn.com/texts/pointinpoly
The cross product solution implements:
https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf
Parameters
-----------
triangles : (n, 3, 2 | 3) float
Triangles vertices in space
points : (n, 2 | 3) float
Point in space associated with a triangle
method : str
Which method to compute the barycentric coordinates with:
- 'cross': uses a method using cross products, roughly 2x slower but
different numerical robustness properties
- anything else: uses a cramer's rule solution
Returns
-----------
barycentric : (n, 3) float
Barycentric coordinates of each point
to_kwargs(triangles)
Convert a list of triangles to the kwargs for the Trimesh
constructor.
Parameters
---------
triangles : (n, 3, 3) float
Triangles in space
Returns
---------
kwargs : dict
Keyword arguments for the trimesh.Trimesh constructor
Includes keys 'vertices' and 'faces'
Examples
---------
>>> mesh = trimesh.Trimesh(**trimesh.triangles.to_kwargs(triangles))
windings_aligned(triangles, normals_compare)
Given a list of triangles and a list of normals determine if the
two are aligned
Parameters
----------
triangles : (n, 3, 3) float
Vertex locations in space
normals_compare : (n, 3) float
List of normals to compare
Returns
----------
aligned : (n,) bool
Are normals aligned with triangles
DATA
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
log = <Logger trimesh.triangles (WARNING)>
tol = ToleranceMesh(zero=np.float64(1e-13), merge=1e-08, planar=1e-05,...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\triangles.py
trimesh.typed
Python Library Documentation: module trimesh.typed in trimesh
NAME
trimesh.typed
CLASSES
builtins.float(builtins.object)
numpy.float64(numpy.floating, builtins.float)
builtins.object
builtins.dict
builtins.list
builtins.set
builtins.tuple
collections.abc.Callable
collections.abc.Hashable
collections.abc.Iterable
typing.Any
collections.abc.Collection(collections.abc.Sized, collections.abc.Iterable, collections.abc.Container)
collections.abc.Mapping
collections.abc.Sequence(collections.abc.Reversible, collections.abc.Collection)
collections.abc.Reversible(collections.abc.Iterable)
collections.abc.Sequence(collections.abc.Reversible, collections.abc.Collection)
numpy.floating(numpy.inexact)
numpy.float64(numpy.floating, builtins.float)
numpy.signedinteger(numpy.integer)
numpy.int64
typing.Generic(builtins.object)
typing.IO
typing.BinaryIO
class Any(builtins.object)
| Any(*args, **kwargs)
|
| Special type indicating an unconstrained type.
|
| - Any is compatible with every type.
| - Any assumed to have all methods.
| - All values assumed to be instances of Any.
|
| Note that all the above statements are true from the point of view of
| static type checkers. At runtime, Any should not be used with instance
| checks.
|
| Static methods defined here:
|
| __new__(cls, *args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class BinaryIO(IO)
| Typed version of the return of open() in binary mode.
|
| Method resolution order:
| BinaryIO
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'BinaryIO'
|
| write(self, s: Union[bytes, bytearray]) -> int
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __orig_bases__ = (typing.IO[bytes],)
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from IO:
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties inherited from IO:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class Callable(builtins.object)
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = _CallableGenericAlias(args)
| Represent `Callable[argtypes, resulttype]`.
|
| This sets ``__args__`` to a tuple containing the flattened ``argtypes``
| followed by ``resulttype``.
|
| Example: ``Callable[[int, str], float]`` sets ``__args__`` to
| ``(int, str, float)``.
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__call__'})
Dict = class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Built-in subclasses:
| StgDict
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class Hashable(builtins.object)
| Methods defined here:
|
| __hash__(self)
| Return hash(self).
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__hash__'})
class IO(Generic)
| Generic base class for TextIO and BinaryIO.
|
| This is an abstract, generic version of the return of open().
|
| NOTE: This does not distinguish between the different possible
| classes (text vs. binary, read vs. write vs. read/write,
| append-only, unbuffered). The TextIO and BinaryIO subclasses
| below capture the distinctions between text vs. binary, which is
| pervasive in the interface; however we currently do not offer a
| way to track the other distinctions in the type system.
|
| Method resolution order:
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'IO[AnyStr]'
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| write(self, s: ~AnyStr) -> int
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __orig_bases__ = (typing.Generic[~AnyStr],)
|
| __parameters__ = (~AnyStr,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class Iterable(builtins.object)
| Methods defined here:
|
| __iter__(self)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__iter__'})
List = class list(object)
| List(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, index, /)
| Return self[index].
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Sort the list in ascending order and return None.
|
| The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
| order of two equal elements is maintained).
|
| If a key function is given, apply it once to each list item and sort them,
| ascending or descending, according to their function values.
|
| The reverse flag can be set to sort in descending order.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| See PEP 585
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class Mapping(Collection)
| A Mapping is a generic container for associating key/value
| pairs.
|
| This class provides concrete generic implementations of all
| methods except for __getitem__, __iter__, and __len__.
|
| Method resolution order:
| Mapping
| Collection
| Sized
| Iterable
| Container
| builtins.object
|
| Methods defined here:
|
| __contains__(self, key)
|
| __eq__(self, other)
| Return self==value.
|
| __getitem__(self, key)
|
| get(self, key, default=None)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(self)
| D.items() -> a set-like object providing a view on D's items
|
| keys(self)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(self)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__getitem__', '__iter__', '__len__'}...
|
| __hash__ = None
|
| __reversed__ = None
|
| ----------------------------------------------------------------------
| Class methods inherited from Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Methods inherited from Sized:
|
| __len__(self)
|
| ----------------------------------------------------------------------
| Methods inherited from Iterable:
|
| __iter__(self)
|
| ----------------------------------------------------------------------
| Class methods inherited from Iterable:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
class Sequence(Reversible, Collection)
| All the operations on a read-only sequence.
|
| Concrete subclasses must override __new__ or __init__,
| __getitem__, and __len__.
|
| Method resolution order:
| Sequence
| Reversible
| Collection
| Sized
| Iterable
| Container
| builtins.object
|
| Methods defined here:
|
| __contains__(self, value)
|
| __getitem__(self, index)
|
| __iter__(self)
|
| __reversed__(self)
|
| count(self, value)
| S.count(value) -> integer -- return number of occurrences of value
|
| index(self, value, start=0, stop=None)
| S.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
| Supporting start and stop arguments is optional, but
| recommended.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__getitem__', '__len__'})
|
| ----------------------------------------------------------------------
| Class methods inherited from Reversible:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Methods inherited from Sized:
|
| __len__(self)
|
| ----------------------------------------------------------------------
| Class methods inherited from Iterable:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
Set = class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __contains__(...)
| x.__contains__(y) <==> y in x.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __gt__(self, value, /)
| Return self>value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __reduce__(...)
| Return state information for pickling.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(...)
| S.__sizeof__() -> size of S in memory, in bytes
|
| __sub__(self, value, /)
| Return self-value.
|
| __xor__(self, value, /)
| Return self^value.
|
| add(...)
| Add an element to a set.
|
| This has no effect if the element is already present.
|
| clear(...)
| Remove all elements from this set.
|
| copy(...)
| Return a shallow copy of a set.
|
| difference(...)
| Return the difference of two or more sets as a new set.
|
| (i.e. all elements that are in this set but not the others.)
|
| difference_update(...)
| Remove all elements of another set from this set.
|
| discard(...)
| Remove an element from a set if it is a member.
|
| Unlike set.remove(), the discard() method does not raise
| an exception when an element is missing from the set.
|
| intersection(...)
| Return the intersection of two sets as a new set.
|
| (i.e. all elements that are in both sets.)
|
| intersection_update(...)
| Update a set with the intersection of itself and another.
|
| isdisjoint(...)
| Return True if two sets have a null intersection.
|
| issubset(self, other, /)
| Test whether every element in the set is in other.
|
| issuperset(self, other, /)
| Test whether every element in other is in the set.
|
| pop(...)
| Remove and return an arbitrary set element.
| Raises KeyError if the set is empty.
|
| remove(...)
| Remove an element from a set; it must be a member.
|
| If the element is not a member, raise a KeyError.
|
| symmetric_difference(...)
| Return the symmetric difference of two sets as a new set.
|
| (i.e. all elements that are in exactly one of the sets.)
|
| symmetric_difference_update(...)
| Update a set with the symmetric difference of itself and another.
|
| union(...)
| Return the union of sets as a new set.
|
| (i.e. all elements that are in either set.)
|
| update(...)
| Update a set with the union of itself and others.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| See PEP 585
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
Tuple = class tuple(object)
| Tuple(iterable=(), /)
|
| Built-in immutable sequence.
|
| If no argument is given, the constructor returns an empty tuple.
| If iterable is specified the tuple is initialized from iterable's items.
|
| If the argument is a tuple, the return value is the same object.
|
| Built-in subclasses:
| asyncgen_hooks
| UnraisableHookArgs
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| See PEP 585
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
class float64(floating, builtins.float)
| float64(x=0, /)
|
| Double-precision floating-point number type, compatible with Python
| :class:`float` and C ``double``.
|
| :Character code: ``'d'``
| :Canonical name: `numpy.double`
| :Alias on this platform (win32 AMD64): `numpy.float64`: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.
|
| Method resolution order:
| float64
| floating
| inexact
| number
| generic
| builtins.float
| builtins.object
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| as_integer_ratio(...)
| double.as_integer_ratio() -> (int, int)
|
| Return a pair of integers, whose ratio is exactly equal to the original
| floating point number, and with a positive denominator.
| Raise `OverflowError` on infinities and a `ValueError` on NaNs.
|
| >>> np.double(10.0).as_integer_ratio()
| (10, 1)
| >>> np.double(0.0).as_integer_ratio()
| (0, 1)
| >>> np.double(-.25).as_integer_ratio()
| (-1, 4)
|
| is_integer(...)
| double.is_integer() -> bool
|
| Return ``True`` if the floating point number is finite with integral
| value, and ``False`` otherwise.
|
| .. versionadded:: 1.22
|
| Examples
| --------
| >>> np.double(-2.0).is_integer()
| True
| >>> np.double(3.2).is_integer()
| False
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.number` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.number` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.signedinteger[Any]
| numpy.signedinteger[typing.Any]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from floating:
|
| __round__(...)
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __format__(...)
| NumPy array scalar formatter
|
| __getitem__(self, key, /)
| Return self[key].
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __reduce__(...)
| Helper for pickle.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.float:
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __getnewargs__(self, /)
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.float:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
class int64(signedinteger)
| Default signed integer type, 64bit on 64bit systems and 32bit on 32bit
| systems.
|
| :Character code: ``'q'``
| :Canonical name: `numpy.int_`
| :Alias on this platform (win32 AMD64): `numpy.int64`: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``).
| :Alias on this platform (win32 AMD64): `numpy.intp`: Signed integer large enough to fit pointer, compatible with C ``intptr_t``.
|
| Method resolution order:
| int64
| signedinteger
| integer
| number
| generic
| builtins.object
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| bit_count(...)
| int64.bit_count() -> int
|
| Computes the number of 1-bits in the absolute value of the input.
| Analogous to the builtin `int.bit_count` or ``popcount`` in C++.
|
| Examples
| --------
| >>> np.int64(127).bit_count()
| 7
| >>> np.int64(-127).bit_count()
| 7
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.number` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.number` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.signedinteger[Any]
| numpy.signedinteger[typing.Any]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from integer:
|
| __round__(...)
|
| is_integer(...)
| integer.is_integer() -> bool
|
| Return ``True`` if the number is finite with integral value.
|
| .. versionadded:: 1.22
|
| Examples
| --------
| >>> import numpy as np
| >>> np.int64(-2).is_integer()
| True
| >>> np.uint32(5).is_integer()
| True
|
| ----------------------------------------------------------------------
| Data descriptors inherited from integer:
|
| denominator
| denominator of value (1)
|
| numerator
| numerator of value (the value itself)
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __format__(...)
| NumPy array scalar formatter
|
| __getitem__(self, key, /)
| Return self[key].
|
| __reduce__(...)
| Helper for pickle.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
DTypeLike = typing.Union[numpy.dtype[typing.Any], NoneType, ...e_like....
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
Loadable = typing.Union[str, pathlib.Path, typing.IO, _io.B...yping.Te...
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Number = typing.Union[float, numpy.floating, int, numpy.integer, numpy...
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
Self = typing.Self
Used to spell the type of "self" in classes.
Example::
from typing import Self
class Foo:
def return_self(self) -> Self:
...
return self
This is especially useful for:
- classmethods that are used as alternative constructors
- annotating an `__enter__` method which returns self
Stream = typing.Union[typing.IO, _io.BytesIO, _io.StringI...ping.Binar...
ViewerType = typing.Union[NoneType, collections.abc.Callable, typing.L...
__all__ = ['IO', 'Any', 'ArrayLike', 'BinaryIO', 'Callable', 'DTypeLik...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\typed.py
trimesh.unitize
Python Library Documentation: function unitize in module trimesh.util
unitize(vectors, check_valid=False, threshold=None)
Unitize a vector or an array or row-vectors.
Parameters
------------
vectors : (n,m) or (j) float
Vector or vectors to be unitized
check_valid : bool
If set, will return mask of nonzero vectors
threshold : float
Cutoff for a value to be considered zero.
Returns
---------
unit : (n,m) or (j) float
Input vectors but unitized
valid : (n,) bool or bool
Mask of nonzero vectors returned if `check_valid`
trimesh.units
Python Library Documentation: module trimesh.units in trimesh
NAME
trimesh.units
DESCRIPTION
units.py
--------------
Deal with physical unit systems (i.e. inches, mm)
Very basic conversions, and no requirement for
sympy.physics.units or pint.
FUNCTIONS
keys() -> set
Return a set containing all currently valid units.
Returns
--------
keys
All units with conversions i.e. {'in', 'm', ...}
to_inch(unit: str) -> float
Calculate the conversion to an arbitrary common unit.
Parameters
------------
unit
Either a key in `units_to_inches.json` or in the simple
`{float} * {str}` form, i.e. "1.2 * meters". We don't
support arbitrary `eval` of any math string
Returns
----------
conversion
Factor to multiply by to get to an `inch` system.
unit_conversion(current: str, desired: str) -> float
Calculate the conversion from one set of units to another.
Parameters
---------
current : str
Unit system values are in now (eg 'millimeters')
desired : str
Unit system we'd like values in (eg 'inches')
Returns
---------
conversion : float
Number to multiply by to put values into desired units
units_from_metadata(obj: trimesh.parent.Geometry, guess: bool = True) -> str
Try to extract hints from metadata and if that fails
guess based on the object scale.
Parameters
------------
obj
A geometry object.
guess
If metadata doesn't have units make a "best guess"
Returns
------------
units
A guess of what the units might be
DATA
log = <Logger trimesh.util (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\units.py
trimesh.util
Python Library Documentation: module trimesh.util in trimesh
NAME
trimesh.util - Grab bag of utility functions.
CLASSES
collections.abc.Mapping(collections.abc.Collection)
FunctionRegistry
class FunctionRegistry(collections.abc.Mapping)
| FunctionRegistry(**kwargs)
|
| Non-overwritable mapping of string keys to functions.
|
| This allows external packages to register additional implementations
| of common functionality without risk of breaking implementations provided
| by trimesh.
|
| See trimesh.voxel.morphology for example usage.
|
| Method resolution order:
| FunctionRegistry
| collections.abc.Mapping
| collections.abc.Collection
| collections.abc.Sized
| collections.abc.Iterable
| collections.abc.Container
| builtins.object
|
| Methods defined here:
|
| __call__(self, key, *args, **kwargs)
| Call self as a function.
|
| __contains__(self, key)
|
| __getitem__(self, key)
|
| __init__(self, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __setitem__(self, key, value)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.Mapping:
|
| __eq__(self, other)
| Return self==value.
|
| get(self, key, default=None)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(self)
| D.items() -> a set-like object providing a view on D's items
|
| keys(self)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(self)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from collections.abc.Mapping:
|
| __hash__ = None
|
| __reversed__ = None
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Iterable:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
FUNCTIONS
allclose(a, b, atol: float = 1e-08)
A replacement for np.allclose that does few checks
and validation and as a result is faster.
Parameters
------------
a : np.ndarray
To be compared
b : np.ndarray
To be compared
atol : float
Acceptable distance between `a` and `b` to be "close"
Returns
-----------
bool indicating if all elements are within `atol`.
append_faces(vertices_seq, faces_seq)
Given a sequence of zero-indexed faces and vertices
combine them into a single array of faces and
a single array of vertices.
Parameters
-----------
vertices_seq : (n, ) sequence of (m, d) float
Multiple arrays of verticesvertex arrays
faces_seq : (n, ) sequence of (p, j) int
Zero indexed faces for matching vertices
Returns
----------
vertices : (i, d) float
Points in space
faces : (j, 3) int
Reference vertex indices
array_to_encoded(array, dtype=None, encoding='base64')
Export a numpy array to a compact serializable dictionary.
Parameters
------------
array : array
Any numpy array
dtype : str or None
Optional dtype to encode array
encoding : str
'base64' or 'binary'
Returns
---------
encoded : dict
Has keys:
'dtype': str, of dtype
'shape': tuple of shape
'base64': str, base64 encoded string
array_to_string(array, col_delim=' ', row_delim='\n', digits=8, value_format='{}')
Convert a 1 or 2D array into a string with a specified number
of digits and delimiter. The reason this exists is that the
basic numpy array to string conversions are surprisingly bad.
Parameters
------------
array : (n,) or (n, d) float or int
Data to be converted
If shape is (n,) only column delimiter will be used
col_delim : str
What string should separate values in a column
row_delim : str
What string should separate values in a row
digits : int
How many digits should floating point numbers include
value_format : str
Format string for each value or sequence of values
If multiple values per value_format it must divide
into array evenly.
Returns
----------
formatted : str
String representation of original array
attach_to_log(level=10, handler=None, loggers: Optional[collections.abc.Iterable[logging.Logger]] = None, colors: bool = True, capture_warnings: bool = True, blacklist: Optional[collections.abc.Iterable] = None, only_parent: bool = True)
Attach a stream handler to all loggers.
Parameters
------------
level : enum
Logging level, like logging.INFO
handler : None or logging.Handler
Handler to attach
loggers : None or (n,) logging.Logger
If None, will try to attach to all available
colors : bool
If True try to use colorlog formatter
blacklist : (n,) str
Names of loggers NOT to attach to
only_parent
Only attach to parent loggers, i.e. `trimesh`, `trimesh.sub1`, `trimesh.sub2`
will only attach to `trimesh` and not the sub-loggers
bounds_tree(bounds)
Given a set of axis aligned bounds create an r-tree for
broad-phase collision detection.
Parameters
------------
bounds : (n, 2D) or (n, 2, D) float
Non-interleaved bounds where D=dimension
E.G a 2D bounds tree:
[(minx, miny, maxx, maxy), ...]
Returns
---------
tree : Rtree
Tree containing bounds by index
comment_strip(text, starts_with='#', new_line='\n')
Strip comments from a text block.
Parameters
-----------
text : str
Text to remove comments from
starts_with : str
Character or substring that starts a comment
new_line : str
Character or substring that ends a comment
Returns
-----------
stripped : str
Text with comments stripped
compress(info, **kwargs)
Compress data stored in a dict.
Parameters
-----------
info : dict
Data to compress in form:
{file name in archive: bytes or file-like object}
kwargs : dict
Passed to zipfile.ZipFile
Returns
-----------
compressed : bytes
Compressed file data
concatenate(a, b=None) -> Union[ForwardRef('trimesh.Trimesh'), ForwardRef('trimesh.path.Path2D'), ForwardRef('trimesh.path.Path3D')]
Concatenate two or more meshes.
Parameters
------------
a : trimesh.Trimesh
Mesh or list of meshes to be concatenated
object, or list of such
b : trimesh.Trimesh
Mesh or list of meshes to be concatenated
Returns
----------
result
Concatenated mesh
convert_like(item, like)
Convert an item to have the dtype of another item
Parameters
------------
item : any
Item to be converted
like : any
Object with target dtype
If None, item is returned unmodified
Returns
----------
result: item, but in dtype of like
decimal_to_digits(decimal, min_digits=None) -> int
Return the number of digits to the first nonzero decimal.
Parameters
-----------
decimal: float
min_digits: int, minimum number of digits to return
Returns
-----------
digits: int, number of digits to the first nonzero decimal
decode_keys(store, encoding='utf-8')
If a dictionary has keys that are bytes decode them to a str.
Parameters
------------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converted to ASCII strings.
Example
-----------
In [1]: d
Out[1]: {1020: 'nah', b'hi': 'stuff'}
In [2]: trimesh.util.decode_keys(d)
Out[2]: {1020: 'nah', 'hi': 'stuff'}
decode_text(text, initial='utf-8')
Try to decode byte input as a string.
Tries initial guess (UTF-8) then if that fails it
uses charset_normalizer to try another guess before failing.
Parameters
------------
text : bytes
Data that might be a string
initial : str
Initial guess for text encoding.
Returns
------------
decoded : str
Data as a string
decompress(file_obj, file_type)
Given an open file object and a file type, return all components
of the archive as open file objects in a dict.
Parameters
------------
file_obj : file-like
Containing compressed data
file_type : str
File extension, 'zip', 'tar.gz', etc
Returns
---------
decompressed : dict
Data from archive in format {file name : file-like}
diagonal_dot(a, b)
Dot product by row of a and b.
There are a lot of ways to do this though
performance varies very widely. This method
uses a dot product to sum the row and avoids
function calls if at all possible.
Comparing performance of some equivalent versions:
```
In [1]: import numpy as np; import trimesh
In [2]: a = np.random.random((10000, 3))
In [3]: b = np.random.random((10000, 3))
In [4]: %timeit (a * b).sum(axis=1)
1000 loops, best of 3: 181 us per loop
In [5]: %timeit np.einsum('ij,ij->i', a, b)
10000 loops, best of 3: 62.7 us per loop
In [6]: %timeit np.diag(np.dot(a, b.T))
1 loop, best of 3: 429 ms per loop
In [7]: %timeit np.dot(a * b, np.ones(a.shape[1]))
10000 loops, best of 3: 61.3 us per loop
In [8]: %timeit trimesh.util.diagonal_dot(a, b)
10000 loops, best of 3: 55.2 us per loop
```
Parameters
------------
a : (m, d) float
First array
b : (m, d) float
Second array
Returns
-------------
result : (m,) float
Dot product of each row
distance_to_end(file_obj)
For an open file object how far is it to the end
Parameters
------------
file_obj: open file-like object
Returns
----------
distance: int, bytes to end of file
encoded_to_array(encoded: Union[dict, collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Turn a dictionary with base64 encoded strings back into a numpy array.
Parameters
------------
encoded
Has keys:
dtype: string of dtype
shape: int tuple of shape
base64: base64 encoded string of flat array
binary: decode result coming from numpy.tobytes
Returns
----------
array
euclidean(a, b) -> float
DEPRECATED: use `np.linalg.norm(a - b)` instead of this.
generate_basis(z, epsilon=1e-12)
Generate an arbitrary basis (also known as a coordinate frame)
from a given z-axis vector.
Parameters
------------
z : (3,) float
A vector along the positive z-axis.
epsilon : float
Numbers smaller than this considered zero.
Returns
---------
x : (3,) float
Vector along x axis.
y : (3,) float
Vector along y axis.
z : (3,) float
Vector along z axis.
grid_arange(bounds, step)
Return a grid from an (2,dimension) bounds with samples step distance apart.
Parameters
------------
bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]
step: float, or (dimension) floats, separation between points
Returns
---------
grid: (n, dimension), points inside the specified bounds
grid_linspace(bounds, count)
Return a grid spaced inside a bounding box with edges spaced using np.linspace.
Parameters
------------
bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]
count: int, or (dimension,) int, number of samples per side
Returns
---------
grid: (n, dimension) float, points in the specified bounds
has_module(name: str) -> bool
Check to see if a module is installed by name without
actually importing the module.
Parameters
------------
name : str
The name of the module to check
Returns
------------
installed : bool
True if module is installed
is_binary_file(file_obj)
Returns True if file has non-ASCII characters (> 0x7F, or 127)
Should work in both Python 2 and 3
is_ccw(points, return_all=False)
Check if connected 2D points are counterclockwise.
Parameters
-----------
points : (n, 2) float
Connected points on a plane
return_all : bool
Return polygon area and centroid or just counter-clockwise.
Returns
----------
ccw : bool
True if points are counter-clockwise
area : float
Only returned if `return_centroid`
centroid : (2,) float
Centroid of the polygon.
is_file(obj)
Check if an object is file-like
Parameters
------------
obj : object
Any object type to be checked
Returns
-----------
is_file : bool
True if object is a file
is_instance_named(obj, name)
Given an object, if it is a member of the class 'name',
or a subclass of 'name', return True.
Parameters
------------
obj : instance
Some object of some class
name: str
The name of the class we want to check for
Returns
---------
is_instance : bool
Whether the object is a member of the named class
is_pathlib(obj)
Check if the object is a `pathlib.Path` or subclass.
Parameters
------------
obj : object
Object to be checked
Returns
------------
is_pathlib : bool
Is the input object a pathlib path
is_sequence(obj) -> bool
Check if an object is a sequence or not.
Parameters
-------------
obj : object
Any object type to be checked
Returns
-------------
is_sequence : bool
True if object is sequence
is_shape(obj, shape, allow_zeros: bool = False) -> bool
Compare the shape of a numpy.ndarray to a target shape,
with any value less than zero being considered a wildcard
Note that if a list-like object is passed that is not a numpy
array, this function will not convert it and will return False.
Parameters
------------
obj : np.ndarray
Array to check the shape on
shape : list or tuple
Any negative term will be considered a wildcard
Any tuple term will be evaluated as an OR
allow_zeros: bool
if False, zeros do not match negatives in shape
Returns
---------
shape_ok : bool
True if shape of obj matches query shape
Examples
------------------------
In [1]: a = np.random.random((100, 3))
In [2]: a.shape
Out[2]: (100, 3)
In [3]: trimesh.util.is_shape(a, (-1, 3))
Out[3]: True
In [4]: trimesh.util.is_shape(a, (-1, 3, 5))
Out[4]: False
In [5]: trimesh.util.is_shape(a, (100, -1))
Out[5]: True
In [6]: trimesh.util.is_shape(a, (-1, (3, 4)))
Out[6]: True
In [7]: trimesh.util.is_shape(a, (-1, (4, 5)))
Out[7]: False
is_string(obj) -> bool
DEPRECATED : this is not necessary since we dropped Python 2.
Replace with `isinstance(obj, str)`
isclose(a, b, atol: float = 1e-08)
A replacement for np.isclose that does fewer checks
and validation and as a result is roughly 4x faster.
Note that this is used in tight loops, and as such
a and b MUST be np.ndarray, not list or "array-like"
Parameters
------------
a : np.ndarray
To be compared
b : np.ndarray
To be compared
atol : float
Acceptable distance between `a` and `b` to be "close"
Returns
-----------
close : np.ndarray, bool
Per-element closeness
jsonify(obj, **kwargs)
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : list, dict
A JSON-serializable blob
kwargs : dict
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj
make_sequence(obj)
Given an object, if it is a sequence return, otherwise
add it to a length 1 sequence and return.
Useful for wrapping functions which sometimes return single
objects and other times return lists of objects.
Parameters
-------------
obj : object
An object to be made a sequence
Returns
--------------
as_sequence : (n,) sequence
Contains input value
multi_dict(pairs)
Given a set of key value pairs, create a dictionary.
If a key occurs multiple times, stack the values into an array.
Can be called like the regular dict(pairs) constructor
Parameters
------------
pairs: (n, 2) array of key, value pairs
Returns
----------
result: dict, with all values stored (rather than last with regular dict)
now = time(...)
time() -> floating-point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
pairwise(iterable)
For an iterable, group values into pairs.
Parameters
------------
iterable : (m, ) list
A sequence of values
Returns
-----------
pairs: (n, 2)
Pairs of sequential values
Example
-----------
In [1]: data
Out[1]: [0, 1, 2, 3, 4, 5, 6]
In [2]: list(trimesh.util.pairwise(data))
Out[2]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
row_norm(data)
Compute the norm per-row of a numpy array.
This is identical to np.linalg.norm(data, axis=1) but roughly
three times faster due to being less general.
In [3]: %timeit trimesh.util.row_norm(a)
76.3 us +/- 651 ns per loop
In [4]: %timeit np.linalg.norm(a, axis=1)
220 us +/- 5.41 us per loop
Parameters
-------------
data : (n, d) float
Input 2D data to calculate per-row norm of
Returns
-------------
norm : (n,) float
Norm of each row of input array
sigfig_int(values, sigfig)
Convert a set of floating point values into integers
with a specified number of significant figures and an
exponent.
Parameters
------------
values : (n,) float or int
Array of values
sigfig : (n,) int
Number of significant figures to keep
Returns
------------
as_int : (n,) int
Every value[i] has sigfig[i] digits
multiplier : (n, int)
Exponent, so as_int * 10 ** multiplier is
the same order of magnitude as the input
sigfig_round(values, sigfig=1)
Round a single value to a specified number of significant figures.
Parameters
------------
values : float
Value to be rounded
sigfig : int
Number of significant figures to reduce to
Returns
----------
rounded : float
Value rounded to the specified number of significant figures
Examples
----------
In [1]: trimesh.util.round_sigfig(-232453.00014045456, 1)
Out[1]: -200000.0
In [2]: trimesh.util.round_sigfig(.00014045456, 1)
Out[2]: 0.0001
In [3]: trimesh.util.round_sigfig(.00014045456, 4)
Out[3]: 0.0001405
spherical_to_vector(spherical: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]]) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
Convert an array of `(n, 2)` spherical angles to `(n, 3)` unit vectors.
Parameters
------------
spherical : (n , 2) float
Angles, in radians
Returns
-----------
vectors : (n, 3) float
Unit vectors
split_extension(file_name, special=None) -> str
Find the file extension of a file name, including support for
special case multipart file extensions (like .tar.gz)
Parameters
------------
file_name : str
File name
special : list of str
Multipart extensions
eg: ['tar.bz2', 'tar.gz']
Returns
----------
extension : str
Last characters after a period, or
a value from 'special'
stack_3D(points, return_2D=False)
For a list of (n, 2) or (n, 3) points return them
as (n, 3) 3D points, 2D points on the XY plane.
Parameters
------------
points : (n, 2) or (n, 3) float
Points in either 2D or 3D space
return_2D : bool
Were the original points 2D?
Returns
----------
points : (n, 3) float
Points in space
is_2D : bool
[OPTIONAL] if source points were (n, 2)
stack_lines(indices)
Stack a list of values that represent a polyline into
individual line segments with duplicated consecutive values.
Parameters
------------
indices : (m,) any
List of items to be stacked
Returns
---------
stacked : (n, 2) any
Stacked items
Examples
----------
In [1]: trimesh.util.stack_lines([0, 1, 2])
Out[1]:
array([[0, 1],
[1, 2]])
In [2]: trimesh.util.stack_lines([0, 1, 2, 4, 5])
Out[2]:
array([[0, 1],
[1, 2],
[2, 4],
[4, 5]])
In [3]: trimesh.util.stack_lines([[0, 0], [1, 1], [2, 2], [3, 3]])
Out[3]:
array([[0, 0],
[1, 1],
[1, 1],
[2, 2],
[2, 2],
[3, 3]])
structured_array_to_string(array, col_delim=' ', row_delim='\n', digits=8, value_format='{}')
Convert an unstructured array into a string with a specified
number of digits and delimiter. The reason thisexists is
that the basic numpy array to string conversionsare
surprisingly bad.
Parameters
------------
array : (n,) or (n, d) float or int
Data to be converted
If shape is (n,) only column delimiter will be used
col_delim : str
What string should separate values in a column
row_delim : str
What string should separate values in a row
digits : int
How many digits should floating point numbers include
value_format : str
Format string for each value or sequence of values
If multiple values per value_format it must divide
into array evenly.
Returns
----------
formatted : str
String representation of original array
submesh(mesh, faces_sequence, repair: bool = True, only_watertight: bool = False, min_faces: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None, append: bool = False)
Return a subset of a mesh.
Parameters
------------
mesh : Trimesh
Source mesh to take geometry from
faces_sequence : sequence (p,) int
Indexes of mesh.faces
repair
Try to make submeshes watertight
only_watertight
Only return submeshes which are watertight
min_faces
Minimum number of faces allowed in a submesh.
append : bool
Return a single mesh which has the faces appended,
if this flag is set, only_watertight is ignored
Returns
---------
result : Trimesh | list[Trimesh]
Depending on if `append` is true or not.
to_ascii(text)
Force a string or other to ASCII text ignoring errors.
Parameters
-----------
text : any
Input to be converted to ASCII string
Returns
-----------
ascii : str
Input as an ASCII string
tolist(data)
Ensure that any arrays or dicts passed containing
numpy arrays are properly converted to lists
Parameters
-------------
data : any
Usually a dict with some numpy arrays as values
Returns
----------
result : any
JSON-serializable version of data
triangle_fans_to_faces(fans)
Convert fans of m + 2 vertex indices in fan format to m triangles
Parameters
----------
fans: (n,) list of (m + 2,) int
Vertex indices
Returns
-------
faces: (m, 3) int
Vertex indices representing triangles
triangle_strips_to_faces(strips)
Convert a sequence of triangle strips to (n, 3) faces.
Processes all strips at once using np.concatenate and is significantly
faster than loop-based methods.
From the OpenGL programming guide describing a single triangle
strip [v0, v1, v2, v3, v4]:
Draws a series of triangles (three-sided polygons) using vertices
v0, v1, v2, then v2, v1, v3 (note the order), then v2, v3, v4,
and so on. The ordering is to ensure that the triangles are all
drawn with the same orientation so that the strip can correctly form
part of a surface.
Parameters
------------
strips: (n,) list of (m,) int
Vertex indices
Returns
------------
faces : (m, 3) int
Vertex indices representing triangles
type_bases(obj, depth=4)
Return the bases of the object passed.
type_named(obj, name)
Similar to the type() builtin, but looks in class bases
for named instance.
Parameters
------------
obj : any
Object to look for class of
name : str
Nnme of class
Returns
----------
class : Optional[Callable]
Camed class, or None
unique_id(length=12)
Generate a random alphaNumber unique identifier
using UUID logic.
Parameters
------------
length : int
Length of desired identifier
Returns
------------
unique : str
Unique alphaNumber identifier
unique_name(start: Optional[str], contains: Union[set, collections.abc.Mapping, collections.abc.Iterable], counts: Optional[dict] = None)
Deterministically generate a unique name not
contained in a dict, set or other grouping with
`__includes__` defined. Will create names of the
form "start_10" and increment accordingly.
Parameters
-----------
start : str
Initial guess for name.
contains : dict, set, or list
Bundle of existing names we can *not* use.
counts : None or dict
Maps name starts encountered before to increments in
order to speed up finding a unique name as otherwise
it potentially has to iterate through all of contains.
Should map to "how many times has this `start`
been attempted, i.e. `counts[start]: int`.
Note that this *will be mutated* in-place by this function!
Returns
---------
unique : str
A name that is not contained in `contains`
unitize(vectors, check_valid=False, threshold=None)
Unitize a vector or an array or row-vectors.
Parameters
------------
vectors : (n,m) or (j) float
Vector or vectors to be unitized
check_valid : bool
If set, will return mask of nonzero vectors
threshold : float
Cutoff for a value to be considered zero.
Returns
---------
unit : (n,m) or (j) float
Input vectors but unitized
valid : (n,) bool or bool
Mask of nonzero vectors returned if `check_valid`
vector_hemisphere(vectors, return_sign=False)
For a set of 3D vectors alter the sign so they are all in the
upper hemisphere.
If the vector lies on the plane all vectors with negative Y
will be reversed.
If the vector has a zero Z and Y value vectors with a
negative X value will be reversed.
Parameters
------------
vectors : (n, 3) float
Input vectors
return_sign : bool
Return the sign mask or not
Returns
----------
oriented: (n, 3) float
Vectors with same magnitude as source
but possibly reversed to ensure all vectors
are in the same hemisphere.
sign : (n,) float
[OPTIONAL] sign of original vectors
vector_to_spherical(cartesian)
Convert a set of cartesian points to (n, 2) spherical unit
vectors.
Parameters
------------
cartesian : (n, 3) float
Points in space
Returns
------------
spherical : (n, 2) float
Angles, in radians
vstack_empty(tup)
A thin wrapper for numpy.vstack that ignores empty lists.
Parameters
------------
tup : tuple or list of arrays
With the same number of columns
Returns
------------
stacked : (n, d) array
With same number of columns as
constituent arrays.
wrap_as_stream(item)
Wrap a string or bytes object as a file object.
Parameters
------------
item: str or bytes
Item to be wrapped
Returns
---------
wrapped : file-like object
Contains data from item
write_encoded(file_obj, stuff, encoding='utf-8')
If a file is open in binary mode and a
string is passed, encode and write.
If a file is open in text mode and bytes are
passed decode bytes to str and write.
Assumes binary mode if file_obj does not have
a 'mode' attribute (e.g. io.BufferedRandom).
Parameters
-----------
file_obj : file object
With 'write' and 'mode'
stuff : str or bytes
Stuff to be written
encoding : str
Encoding of text
zero_pad(data, count, right=True)
Parameters
------------
data : (n,)
1D array
count : int
Minimum length of result array
Returns
---------
padded : (m,)
1D array where m >= count
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
Integer = typing.Union[int, numpy.integer, numpy.unsignedinteger]
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
TOL_MERGE = 1e-08
TOL_ZERO = np.float64(1e-13)
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
log = <Logger trimesh.util (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\util.py
trimesh.version
Python Library Documentation: module trimesh.version in trimesh
NAME
trimesh.version - # version.py
DESCRIPTION
Get the current version from package metadata or pyproject.toml
if everything else fails.
DATA
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
VERSION
4.12.2
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\version.py
trimesh.visual
Python Library Documentation: package trimesh.visual in trimesh
NAME
trimesh.visual
DESCRIPTION
visual
-------------
Handle visual properties for meshes, including color and texture
PACKAGE CONTENTS
base
color
gloss
material
objects
texture
CLASSES
trimesh.visual.base.Visuals(abc.ABC)
trimesh.visual.color.ColorVisuals
trimesh.visual.texture.TextureVisuals
class ColorVisuals(trimesh.visual.base.Visuals)
| ColorVisuals(mesh=None, face_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None)
|
| Store color information about a mesh.
|
| Method resolution order:
| ColorVisuals
| trimesh.visual.base.Visuals
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, mesh=None, face_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None, vertex_colors: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None)
| Store color information about a mesh.
|
| Parameters
| ----------
| mesh : Trimesh
| Object that these visual properties
| are associated with
| face_ colors : (n,3|4) or (3,) or (4,) uint8
| Colors per-face
| vertex_colors : (n,3|4) or (3,) or (4,) uint8
| Colors per-vertex
|
| concatenate(self, other: Union[collections.abc.Iterable[trimesh.visual.base.Visuals], trimesh.visual.base.Visuals, collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], *args)
| Concatenate two or more ColorVisuals objects
| into a single object.
|
| Parameters
| -----------
| other : ColorVisuals
| Object to append
| *args: ColorVisuals objects
|
| Returns
| -----------
| result : ColorVisuals
| Containing information from current
| object and others in the order it was passed.
|
| copy(self) -> 'ColorVisuals'
| Return a copy of the current ColorVisuals object.
|
|
| Returns
| ----------
| copied : ColorVisuals
| Contains the same information as self
|
| face_subset(self, face_index: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Given a mask of face indices, return a sliced version.
|
| Parameters
| ----------
| face_index: (n,) int, mask for faces
| (n,) bool, mask for faces
|
| Returns
| ----------
| visual: ColorVisuals object containing a subset of faces.
|
| to_texture(self)
| Convert the current ColorVisuals object to a texture
| with a `SimpleMaterial` defined.
|
| Returns
| ------------
| visual : trimesh.visual.TextureVisuals
| Copy of the current visuals as a texture.
|
| update_faces(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Apply a mask to remove or duplicate face properties
|
| update_vertices(self, mask: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Apply a mask to remove or duplicate vertex properties.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| defined
| Are any colors defined for the current mesh.
|
| Returns
| ---------
| defined : bool
| Are colors defined or not.
|
| kind
| What color mode has been set.
|
| Returns
| ----------
| mode : str or None
| One of ('face', 'vertex', None)
|
| main_color
| What is the most commonly occurring color.
|
| Returns
| ------------
| color: (4,) uint8, most common color
|
| transparency
| Does the current object contain any transparency.
|
| Returns
| ----------
| transparency: bool, does the current visual contain transparency
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| face_colors
| Colors defined for each face of a mesh.
|
| If no colors are defined, defaults are returned.
|
| Returns
| ----------
| colors : (len(mesh.faces), 4) uint8
| RGBA color for each face
|
| vertex_colors
| Return the colors for each vertex of a mesh
|
| Returns
| ------------
| colors: (len(mesh.vertices), 4) uint8, color for each vertex
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.visual.base.Visuals:
|
| __add__(self, other)
| Concatenate two ColorVisuals objects into a single object.
|
| Parameters
| -----------
| other : Visuals
| Other visual to concatenate
|
| Returns
| -----------
| result : Visuals
| Object containing information from current
| object and other in the order (self, other)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.visual.base.Visuals:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class TextureVisuals(trimesh.visual.base.Visuals)
| TextureVisuals(uv=None, material=None, image=None, face_materials=None)
|
| Method resolution order:
| TextureVisuals
| trimesh.visual.base.Visuals
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __hash__(self)
| Get a CRC of the stored data.
|
| Returns
| --------------
| crc : int
| Hash of items in self.vertex_attributes
|
| __init__(self, uv=None, material=None, image=None, face_materials=None)
| Store a single material and per-vertex UV coordinates
| for a mesh.
|
| If passed UV coordinates and a single image it will
| create a SimpleMaterial for the image.
|
| Parameters
| --------------
| uv : (n, 2) float
| UV coordinates for the mesh
| material : Material
| Store images and properties
| image : PIL.Image
| Can be passed to automatically create material
|
| concatenate(self, others)
| Concatenate this TextureVisuals object with others
| and return the result without modifying this visual.
|
| Parameters
| -----------
| others : (n,) Visuals
| Other visual objects to concatenate
|
| Returns
| -----------
| concatenated : TextureVisuals
| Concatenated visual objects
|
| copy(self, uv=None)
| Return a copy of the current TextureVisuals object.
|
| Returns
| ----------
| copied : TextureVisuals
| Contains the same information in a new object
|
| face_subset(self, face_index)
| Get a copy of
|
| to_color(self)
| Convert textured visuals to a ColorVisuals with vertex
| color calculated from texture.
|
| Returns
| -----------
| vis : trimesh.visuals.ColorVisuals
| Contains vertex color from texture
|
| update_faces(self, mask)
| Apply a mask to remove or duplicate face properties,
| not applicable to texture visuals.
|
| update_vertices(self, mask)
| Apply a mask to remove or duplicate vertex properties.
|
| Parameters
| ------------
| mask : (len(vertices),) bool or (n,) int
| Mask which can be used like: `vertex_attribute[mask]`
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| defined
| Check if any data is stored
|
| Returns
| ----------
| defined : bool
| Are UV coordinates and images set?
|
| kind
| Return the type of visual data stored
|
| Returns
| ----------
| kind : str
| What type of visuals are defined
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| uv
| Get the stored UV coordinates.
|
| Returns
| ------------
| uv : (n, 2) float or None
| Pixel position per-vertex.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.visual.base.Visuals:
|
| __add__(self, other)
| Concatenate two ColorVisuals objects into a single object.
|
| Parameters
| -----------
| other : Visuals
| Other visual to concatenate
|
| Returns
| -----------
| result : Visuals
| Object containing information from current
| object and other in the order (self, other)
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.visual.base.Visuals:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
create_visual(**kwargs)
Create Visuals object from keyword arguments.
Parameters
-----------
face_colors : (n, 3|4) uint8
Face colors
vertex_colors : (n, 3|4) uint8
Vertex colors
mesh : trimesh.Trimesh
Mesh object
Returns
----------
visuals : ColorVisuals
Visual object created from arguments
interpolate(values: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], color_map: Union[NoneType, Literal['viridis', 'magma', 'inferno', 'plasma'], collections.abc.Callable] = None, dtype: Union[numpy.dtype[Any], NoneType, type[Any], numpy._typing._dtype_like._SupportsDType[numpy.dtype[Any]], str, tuple[Any, int], tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]], list[Any], numpy._typing._dtype_like._DTypeDict, tuple[Any, Any]] = <class 'numpy.uint8'>) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Given a 1D list of values, return interpolated colors
for the range.
Parameters
---------------
values : (n, ) float
Values to be interpolated over
color_map
One of the four included color maps:
("viridis", "inferno", "plasma", "magma")
Or a function, `matplotlib.pyplot.get_cmap
Returns
-------------
interpolated : (n, 4) dtype
Interpolated RGBA colors
linear_color_map(values: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], color_range: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes], NoneType] = None) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Linearly interpolate a color lookup table from normalized
values.
For example if `color_range` has two values [`a`, `b`]
`values` is `[0.0, 0.5, 1.0]`, this function will return
[`a`, `(a+b)/2`, `b`].
The default value for `color_range` is red-green, or you
can pass in a full lookup table for a color map, i.e. a
`(256, 3) float64` array of RGB colors such as our defaults:
`trimesh.resources.get_json('color_map.json.gzip')['viridis']`
Parameters
--------------
values : (n, ) float
Normalized to 0.0-1.0 values to interpolate
color_range : None or (n, 3|4)
Evenly spaced colors to interpolate through
where `n >= 2`.
Returns
---------------
colors : (n, 4) color_range.dtype
RGBA colors for interpolated values
random_color(dtype: Union[numpy.dtype[Any], NoneType, type[Any], numpy._typing._dtype_like._SupportsDType[numpy.dtype[Any]], str, tuple[Any, int], tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]], list[Any], numpy._typing._dtype_like._DTypeDict, tuple[Any, Any]] = <class 'numpy.uint8'>, count: Union[int, numpy.integer, numpy.unsignedinteger, NoneType] = None) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Return a random RGB color using datatype specified.
Parameters
----------
dtype
Color type of result.
count
If passed return (count, 4) colors instead of
a single (4,) color.
Returns
----------
color : (4,) or (count, 4)
Random color or colors that look "OK"
to_rgba(colors: Any, dtype: Union[numpy.dtype[Any], NoneType, type[Any], numpy._typing._dtype_like._SupportsDType[numpy.dtype[Any]], str, tuple[Any, int], tuple[Any, SupportsIndex | collections.abc.Sequence[SupportsIndex]], list[Any], numpy._typing._dtype_like._DTypeDict, tuple[Any, Any]] = <class 'numpy.uint8'>) -> numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
Convert a single or multiple RGB colors to RGBA colors.
Parameters
----------
colors : (n, 3) or (n, 4) array
RGB or RGBA colors or None
Returns
----------
colors : (n, 4) list of RGBA colors
(4,) single RGBA color
uv_to_color(uv, image) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.uint8]]
Get the color in a texture image.
Parameters
-------------
uv : (n, 2) float
UV coordinates on texture image
image : PIL.Image
Texture image
Returns
----------
colors : (n, 4) uint4
RGBA color at each of the UV coordinates
uv_to_interpolated_color(uv: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]], image) -> numpy.ndarray[typing.Any, numpy.dtype[numpy.uint8]]
Get the color from texture image using bilinear sampling.
Parameters
-------------
uv : (n, 2) float
UV coordinates on texture image
image : PIL.Image
Texture image
Returns
----------
colors : (n, 4) uint8
RGBA color at each of the UV coordinates.
DATA
DEFAULT_COLOR = array([102, 102, 102, 255], dtype=uint8)
__all__ = ['color', 'texture', 'resolvers', 'TextureVisuals', 'ColorVi...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\visual\__init__.py
trimesh.voxel
Python Library Documentation: package trimesh.voxel in trimesh
NAME
trimesh.voxel
PACKAGE CONTENTS
base
creation
encoding
morphology
ops
runlength
transforms
CLASSES
trimesh.parent.Geometry(abc.ABC)
trimesh.voxel.base.VoxelGrid
class VoxelGrid(trimesh.parent.Geometry)
| VoxelGrid(encoding, transform=None, metadata=None)
|
| Store 3D voxels.
|
| Method resolution order:
| VoxelGrid
| trimesh.parent.Geometry
| abc.ABC
| builtins.object
|
| Methods defined here:
|
| __add__(self, other)
|
| __hash__(self)
| Get the hash of the current transformation matrix.
|
| Returns
| ------------
| hash : str
| Hash of transformation matrix
|
| __init__(self, encoding, transform=None, metadata=None)
| Initialize self. See help(type(self)) for accurate signature.
|
| apply_transform(self, matrix)
|
| as_boxes(self, colors=None, **kwargs)
| A rough Trimesh representation of the voxels with a box
| for each filled voxel.
|
| Parameters
| ----------
| colors : None, (3,) or (4,) float or uint8
| (X, Y, Z, 3) or (X, Y, Z, 4) float or uint8
| Where matrix.shape == (X, Y, Z)
|
| Returns
| ---------
| mesh : trimesh.Trimesh
| Mesh with one box per filled cell.
|
| copy(self)
|
| export(self, file_obj=None, file_type=None, **kwargs)
| Export the current VoxelGrid.
|
| Parameters
| ------------
| file_obj : file-like or str
| File or file-name to export to.
| file_type : None or str
| Only 'binvox' currently supported.
|
| Returns
| ---------
| export : bytes
| Value of export.
|
| fill(self, method='holes', **kwargs)
| Mutates self by filling in the encoding according
| to `morphology.fill`.
|
| Parameters
| ----------
| method : hashable
| Implementation key, one of
| `trimesh.voxel.morphology.fill.fillers` keys
| **kwargs : dict
| Additional kwargs passed through to
| the keyed implementation.
|
| Returns
| ----------
| self : VoxelGrid
| After replacing encoding with a filled version.
|
| hollow(self)
| Mutates self by removing internal voxels
| leaving only surface elements.
|
| Surviving elements are those in encoding that are
| adjacent to an empty voxel where adjacency is
| controlled by `structure`.
|
| Returns
| ----------
| self : VoxelGrid
| After replacing encoding with a surface version.
|
| indices_to_points(self, indices)
|
| is_filled(self, point)
| Query points to see if the voxel cells they lie in are
| filled or not.
|
| Parameters
| ----------
| point : (n, 3) float
| Points in space
|
| Returns
| ---------
| is_filled : (n,) bool
| Is cell occupied or not for each point
|
| points_to_indices(self, points)
| Convert points to indices in the matrix array.
|
| Parameters
| ----------
| points: (n, 3) float, point in space
|
| Returns
| ---------
| indices: (n, 3) int array of indices into self.encoding
|
| revoxelized(self, shape)
| Create a new VoxelGrid without rotations, reflections
| or shearing.
|
| Parameters
| ----------
| shape : (3, int)
| The shape of the returned VoxelGrid.
|
| Returns
| ----------
| vox : VoxelGrid
| Of the given shape with possibly non-uniform
| scale and translation transformation matrix.
|
| show(self, *args, **kwargs)
| Convert the current set of voxels into a trimesh for visualization
| and show that via its built- in preview method.
|
| strip(self)
| Mutate self by stripping leading/trailing planes of zeros.
|
| Returns
| --------
| self after mutation occurs in-place
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| bounds
|
| element_volume
|
| extents
|
| filled_count
| int, number of occupied voxels in the grid.
|
| identifier_hash
|
| is_empty
|
| marching_cubes
| A marching cubes Trimesh representation of the voxels.
|
| No effort was made to clean or smooth the result in any way;
| it is merely the result of applying the scikit-image
| measure.marching_cubes function to self.encoding.dense.
|
| Returns
| ---------
| meshed : trimesh.Trimesh
| Representing the current voxel
| object as returned by marching cubes algorithm.
|
| matrix
| Return a DENSE matrix of the current voxel encoding.
|
| Returns
| -------------
| dense : (a, b, c) bool
| Numpy array of dense matrix
| Shortcut to voxel.encoding.dense
|
| pitch
| Uniform scaling factor representing the side length of
| each voxel.
|
| Returns
| -----------
| pitch : float
| Pitch of the voxels.
|
| Raises
| ------------
| `RuntimeError`
| If `self.transformation` has rotation or shear
| components of has non-uniform scaling.
|
| points
| The center of each filled cell as a list of points.
|
| Returns
| ----------
| points : (self.filled, 3) float
| Points in space.
|
| scale
| 3-element float representing per-axis scale.
|
| Raises a `RuntimeError` if `self.transform` has rotation or
| shear components.
|
| shape
| 3-tuple of ints denoting shape of occupancy grid.
|
| sparse_indices
| (n, 3) int array of sparse indices of occupied voxels.
|
| translation
| Location of voxel at [0, 0, 0].
|
| volume
| What is the volume of the filled cells in the current
| voxel object.
|
| Returns
| ---------
| volume : float
| Volume of filled cells.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| encoding
| `Encoding` object providing the occupancy grid.
|
| See `trimesh.voxel.encoding` for implementations.
|
| transform
| 4x4 homogeneous transformation matrix.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from trimesh.parent.Geometry:
|
| __radd__(self, other)
| Concatenate the geometry allowing concatenation with
| built in `sum()` function:
| `sum(Iterable[trimesh.Trimesh])`
|
| Parameters
| ------------
| other : Geometry
| Geometry or 0
|
| Returns
| ----------
| concat : Geometry
| Geometry of combined result
|
| __repr__(self) -> str
| Print quick summary of the current geometry without
| computing properties.
|
| Returns
| -----------
| repr : str
| Human readable quick look at the geometry.
|
| apply_scale(self, scaling)
| Scale the mesh.
|
| Parameters
| ----------
| scaling : float or (3,) float
| Scale factor to apply to the mesh
|
| apply_translation(self, translation: Union[collections.abc.Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], bool, int, float, complex, str, bytes, numpy._typing._nested_sequence._NestedSequence[bool | int | float | complex | str | bytes]])
| Translate the current mesh.
|
| Parameters
| ----------
| translation : (3,) float
| Translation in XYZ
|
| ----------------------------------------------------------------------
| Readonly properties inherited from trimesh.parent.Geometry:
|
| source
| Where and what was this current geometry loaded from?
|
| Returns
| --------
| source
| If loaded from a file, has the path, type, etc.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from trimesh.parent.Geometry:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| units
| Definition of units for the mesh.
|
| Returns
| ----------
| units : str
| Unit system mesh is in, or None if not defined
DATA
__all__ = ['VoxelGrid', 'creation']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\trimesh\voxel\__init__.py