trimesh package

Subpackages

Submodules

trimesh.base module

github.com/mikedh/trimesh

Library for importing, exporting and doing simple operations on triangular meshes.

class trimesh.base.Trimesh(vertices=None, faces=None, face_normals=None, vertex_normals=None, face_colors=None, vertex_colors=None, metadata=None, process=True, validate=False, use_embree=True, initial_cache={}, **kwargs)

Bases: trimesh.parent.Geometry

Attributes:
area

Summed area of all triangles in the current mesh.

area_faces

The area of each face in the mesh.

body_count

How many connected groups of vertices exist in this mesh.

bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

bounds

The axis aligned bounds of the mesh.

center_mass

The point in space which is the center of mass/volume.

centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

density

The density of the mesh.

edges

Edges of the mesh (derived from faces).

edges_face

Which face does each edge belong to.

edges_sorted

Edges sorted along axis 1

edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

edges_unique

The unique edges of the mesh.

edges_unique_length

How long is each unique edge.

euler_number

Return the Euler characteristic (a topological invariant) for the mesh

extents

The length, width, and height of the bounding box of the mesh.

face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

face_adjacency_angles

Return the angle between adjacent faces

face_adjacency_convex

Return faces which are adjacent and locally convex.

face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

face_adjacency_projections

The projection of the non- shared vertex of a triangle onto

face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

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.

face_adjacency_tree

An R-tree of face adjacencies.

face_adjacency_unshared

Return the vertex index of the two vertices not in the shared

face_angles

Returns the angle at each vertex of a face.

face_angles_sparse

A sparse matrix representation of the face angles.

face_normals

Return the unit normal vector for each face.

faces

The faces of the mesh.

faces_sparse

A sparse matrix representation of the faces.

faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

facets

Return a list of face indices for coplanar adjacent faces.

facets_area

Return an array containing the area of each facet.

facets_boundary

Return the edges which represent the boundary of each facet

facets_normal

Return the normal of each facet

facets_on_hull

Find which facets of the mesh are on the convex hull.

facets_origin

Return a point on the facet plane.

identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

identifier_md5

An MD5 of the rotation invariant identifier vector

is_convex

Check if a mesh is convex or not.

is_empty

Does the current mesh have data defined.

is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

is_winding_consistent

Does the mesh have consistent winding or not.

kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh.

mass

Mass of the current mesh, based on specified density and volume.

mass_properties

Returns the mass properties of the current mesh.

moment_inertia

Return the moment of inertia matrix of the current mesh.

principal_inertia_components

Return the 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.

principal_inertia_vectors

Return the principal axis of inertia.

scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

symmetry

Check whether a mesh has rotational symmetry.

symmetry_axis

If a mesh has rotational symmetry, return the axis.

symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

triangles

Actual triangles of the mesh (points, not indexes)

triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

triangles_cross

The cross product of two edges of each triangle.

triangles_tree

An R-tree containing each face of the mesh.

units

Definition of units for the mesh.

vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

vertex_normals

The vertex normals of the mesh.

vertices

The vertices of the mesh.

volume

Volume of the current mesh calculated using a surface integral.

Methods

apply_obb() Apply the oriented bounding box transform to the current mesh.
apply_scale(scaling) Scale the mesh equally on all axis.
apply_transform(matrix) Transform mesh by a homogenous transformation matrix.
apply_translation(translation) Translate the current mesh.
compute_stable_poses([center_mass, sigma, …]) Computes stable orientations of a mesh and their quasi-static probabilites.
contains(points) Given a set of points, determine whether or not they are inside the mesh.
convert_units(desired[, guess]) Convert the units of the mesh into a specified unit.
convex_decomposition([engine, maxhulls]) Compute an approximate convex decomposition of a mesh.
copy() Safely get a copy of the current mesh.
crc() A zlib.adler32 checksum for the current mesh data.
difference(other[, engine]) Boolean difference between this mesh and n other meshes
eval_cached(statement, *args) Evaluate a statement and cache the result before returning.
export([file_obj, file_type]) Export the current mesh to a file object.
fill_holes() Fill single triangle and single quad holes in the current mesh.
fix_normals(**kwargs) Find and fix problems with self.face_normals and self.faces winding direction.
intersection(other[, engine]) Boolean intersection between this mesh and n other meshes
invert() Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.
md5() An MD5 of the core geometry information for the mesh, faces and vertices.
merge_vertices([distance]) If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.
outline([face_ids]) Given a set of face ids, find the outline of the faces, and return it as a Path3D.
process() Do the bare minimum processing to make a mesh useful.
register(other, **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.
remove_degenerate_faces([height]) Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.
remove_duplicate_faces() On the current mesh remove any faces which are duplicates.
remove_infinite_values() Ensure that every vertex and face consists of finite numbers.
remove_unreferenced_vertices() Remove all vertices in the current mesh which are not referenced by a face.
rezero() Translate the mesh so that all vertex vertices are positive.
sample(count[, return_index]) Return random samples distributed normally across the surface of the mesh
scene(**kwargs) Get a Scene object containing the current mesh.
section(plane_normal, plane_origin) Returns a 3D cross section of the current mesh and a plane defined by origin and normal.
section_multiplane(plane_origin, …) Return multiple parallel cross sections of the current mesh in 2D.
show(**kwargs) Render the mesh in an opengl window.
slice_plane(plane_origin, plane_normal) Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.
smoothed(**kwargs) Return a version of the current mesh which will render nicely.
split(**kwargs) Returns a list of Trimesh objects, based on face connectivity.
subdivide([face_index]) Subdivide a mesh, with each subdivided face replaced with four smaller faces.
submesh(faces_sequence, **kwargs) Return a subset of the mesh.
to_dict() Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:
union(other[, engine]) Boolean union between this mesh and n other meshes
unmerge_vertices() Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.
update_faces(mask) In many cases, we will want to remove specific faces.
update_vertices(mask[, inverse]) Update vertices with a mask.
voxelized(pitch, **kwargs) Return a Voxel object representing the current mesh discretized into voxels at the specified pitch
apply_obb()

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.

Returns:
matrix : (4, 4) float

Transformation matrix that was applied to mesh to move it into OBB frame

apply_scale(scaling)

Scale the mesh equally on all axis.

Parameters:
scaling : float

Scale factor to apply to the mesh

apply_transform(matrix)

Transform mesh by a homogenous 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

Homogenous transformation matrix

apply_translation(translation)

Translate the current mesh.

Parameters:
translation : (3,) float

Translation in XYZ

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 mesh.

Returns:
bounds : (2, 3) float

Bounding box with [min, max] coordinates

center_mass

The point in space which is the center of mass/volume.

If the current mesh is not watertight, this is meaningless garbage unless it was explicitly set.

Returns:
center_mass : (3,) float

Volumetric center of mass of the mesh

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

compute_stable_poses(center_mass=None, sigma=0.0, n_samples=1, threshold=0.0)

Computes stable orientations of a mesh and their quasi-static probabilites.

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 evaulates the probabilities of landing in each pose if the object is dropped onto the table randomly.

This method returns the 4x4 homogenous 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 probabilties 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 homogenous 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(points)

Given a set of points, determine whether or not they are inside the mesh. This raises an error if called on a non- watertight mesh.

points : (n, 3) float
Points in cartesian space
Returns:
contains : (n, ) bool

Whether or not each point is inside the mesh

convert_units(desired, guess=False)

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?

convex_decomposition(engine=None, maxhulls=20, **kwargs)

Compute an approximate convex decomposition of a mesh.

testVHACD Parameters which can be passed as kwargs:

Parameters:
maxhulls : int

Maximum number of convex hulls to return

engine : string

Which backend to use. Valid choice is ‘vhacd’.

**kwargs : testVHACD keyword arguments
Returns:
meshes : list of trimesh.Trimesh

List of convex meshes that approximate the original

convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

Returns:
convex : trimesh.Trimesh

Mesh of convex hull of current mesh

copy()

Safely get a copy of the current mesh.

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.Trimesh

Copy of current mesh

crc()

A zlib.adler32 checksum for the current mesh data.

This is about 5x faster than an MD5, and the checksum is checked every time something is requested from the cache so it gets called a lot.

Returns:
crc : int

Checksum of current mesh data

density

The density of the mesh.

Returns:
density : float

The density of the mesh.

difference(other, engine=None)

Boolean difference between this mesh and n other meshes

other : trimesh.Trimesh, or list of trimesh.Trimesh objects
Meshes to difference
Returns:
difference : trimesh.Trimesh

Difference between self and other Trimesh objects

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_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_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

eval_cached(statement, *args)

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(file_obj=None, file_type=None, **kwargs)

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.

file_obj: open writeable file object
str, file name where to save the mesh 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
extents

The length, width, and height of the bounding box of the mesh.

Returns:
extents : (3,) float

Array containing axis aligned [length, width, height]

face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

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 angle between adjacent faces

Returns:
adjacency_angle : (n,) float

Angle between adjacent faces Each value corresponds 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_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: rtree.index

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 : (n, 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 with:

dtype: float shape: (len(self.vertices), len(self.faces))

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) np.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 if this is altered.

Returns:
faces : (n,3) int

Representing triangles which reference self.vertices

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[0:2] Out[0]: TrackedArray([[ 1, 6946, 24224],

[ 6946, 1727, 24225]])

In [1]: mesh.edges_unique[mesh.faces_unique_edges[0: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

fill_holes()

Fill single triangle and single quad holes in the current mesh.

Returns:
watertight : bool

Is the mesh watertight after the function completes

fix_normals(**kwargs)

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 if None automatically pick from body_count

identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

Returns:
identifier : (6,) float

Identifying properties of the current mesh

identifier_md5

An MD5 of the rotation invariant identifier vector

Returns:
hashed : str

MD5 hash of the identifier vector

intersection(other, engine=None)

Boolean intersection between this mesh and n other meshes

other : trimesh.Trimesh, or list of trimesh.Trimesh objects
Meshes to calculate intersections with
Returns:
intersection : trimesh.Trimesh

Mesh of the volume contained by all passed meshes

invert()

Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.

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 : bool

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

md5()

An MD5 of the core geometry information for the mesh, faces and vertices.

Generated from TrackedArray, which subclasses np.ndarray to monitor for changes and returns a correct, but lazily evaluated md5 so it only has to recalculate the hash occasionally, rather than on every call.

Returns:
md5 : string

MD5 of everything in the DataStore

merge_vertices(distance=None)

If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.

Parameters:
distance : float or None

If specified overrides tol.merge

moment_inertia

Return the moment of inertia matrix of the current mesh. If mesh isn’t watertight this is garbage.

Returns:
inertia : (3, 3) float

Moment of inertia of the current mesh

outline(face_ids=None, **kwargs)

Given a set of face ids, find the outline of the 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 section, and 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

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

Homogenous transformation matrix

principal_inertia_vectors

Return the principal axis of inertia.

Ordering corresponds to mesh.principal_inertia_components

Returns:
vectors : (3, 3) float

Three vectors pointing along the principal axis of inertia directions

process()

Do the bare minimum processing to make a mesh useful.

Does this by:
  1. removing NaN and Inf values
  2. merging duplicate vertices
If self._validate:
  1. Remove triangles which have one edge of their rectangular 2D oriented bounding box shorter than tol.merge
  2. remove duplicated triangles
Returns:
self: trimesh.Trimesh

Current mesh

register(other, **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

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_degenerate_faces(height=1e-08)

Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.

If a height is specified, it will remove any face with a 2D oriented bounding box with one edge shorter than that height.

If not specified, it will remove any face with a zero normal.

Parameters:
height : float

If specified removes faces with an oriented bounding box shorter than this on one side.

Returns:
nondegenerate : (len(self.faces),) bool

Mask used to remove faces

remove_duplicate_faces()

On the current mesh remove any faces which are duplicates.

remove_infinite_values()

Ensure that every vertex and face consists of finite numbers.

This will remove vertices or faces containing np.nan and np.inf

remove_unreferenced_vertices()

Remove all vertices in the current mesh which are not referenced by a face.

rezero()

Translate the mesh so that all vertex vertices are positive.

sample(count, return_index=False)

Return random samples distributed normally across the surface of the mesh

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.
Returns:
samples : (count, 3) float

Points on surface of mesh

face_index : (count, ) int

Index of self.faces

scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

Returns:
scale : float

The length of the meshes AABB diagonal

scene(**kwargs)

Get a Scene object containing the current mesh.

Returns:
scene : trimesh.scene.scene.Scene

Contains just the current mesh

section(plane_normal, plane_origin)

Returns a 3D cross section of the current mesh and a plane defined by origin and normal.

plane_normal: (3) vector for plane normal
Normal vector of section plane
plane_origin : (3,) float
Point on the cross section plane
Returns:
intersections: Path3D or None

Curve of intersection

section_multiplane(plane_origin, plane_normal, heights)

Return multiple parallel cross sections of the current mesh in 2D.

plane_normal: (3) vector for plane normal
Normal vector of section plane
plane_origin : (3,) float
Point on the cross 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(**kwargs)

Render the mesh in an opengl window. Requires pyglet.

Parameters:
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

slice_plane(plane_origin, plane_normal)

Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.

plane_normal: (3) vector for plane normal
Normal vector of slicing plane
plane_origin : (3,) float
Point on the slicing plane
Returns:
new_mesh: trimesh.Trimesh or None

Subset of current mesh sliced by plane

smoothed(**kwargs)

Return a version of the current mesh which will render nicely. Does not change current mesh in any way.

Parameters:
angle : float

Angle in radians, face pairs with angles smaller than this value will appear smoothed

Returns:
smoothed : trimesh.Trimesh

Non watertight version of current mesh which will render nicely with smooth shading

split(**kwargs)

Returns a list of Trimesh objects, based on face connectivity. Splits into individual components, sometimes referred to as ‘bodies’

only_watertight : bool
Only return watertight meshes and discard remainder
adjacency : None or (n, 2) int
Override face adjacency with custom values
Returns:
meshes : (n,) trimesh.Trimesh

Separate bodies from original mesh

subdivide(face_index=None)

Subdivide a mesh, with each subdivided face replaced with four smaller 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

submesh(faces_sequence, **kwargs)

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

append : bool

Return a single mesh which has the faces appended. if this flag is set, only_watertight is ignored

Returns:
if append : trimesh.Trimesh object
else : list of trimesh.Trimesh objects
symmetry

Check whether a mesh has rotational symmetry.

Returns:
symmetry: None No rotational symmetry

‘radial’ Symmetric around an axis ‘spherical’ Symmetric around a point

symmetry_axis

If a mesh has rotational symmetry, return the axis.

Returns:
axis: (3,) float

Axis around which a 2D profile was revolved to generate 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
to_dict()

Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:

a = Trimesh(**other_mesh.to_dict())

Returns:
result : dict

With keys that match trimesh constructor

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

union(other, engine=None)

Boolean union between this mesh and n other meshes

other : trimesh.Trimesh, or list of trimesh.Trimesh objects
Other meshes to union
Returns:
union : trimesh.Trimesh

Union of self and other Trimesh objects

units

Definition of units for the mesh.

Returns:
units : str

Unit system mesh is in, or None if not defined

unmerge_vertices()

Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.

update_faces(mask)

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.

valid : (m) int or (len(self.faces)) bool
Mask to remove faces
update_vertices(mask, inverse=None)

Update vertices with a mask.

Parameters:
vertex_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

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_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]
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

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

voxelized(pitch, **kwargs)

Return a Voxel object representing the current mesh discretized into voxels at the specified pitch

Parameters:
pitch : float

The edge length of a single voxel

Returns:
voxelized : Voxel object

Representing the current mesh

trimesh.boolean module

trimesh.boolean.boolean_automatic(meshes, operation)
trimesh.boolean.difference(meshes, engine=None)

Compute the boolean difference between a mesh an n other meshes.

Parameters:
meshes: list of Trimesh object
engine: string, which backend to use.

valid choices are ‘blender’ or ‘scad’

Returns:
difference: a - (other meshes), **kwargs for a Trimesh
trimesh.boolean.intersection(meshes, engine=None)

Compute the boolean intersection between a mesh an n other meshes.

Parameters:
meshes: list of Trimesh object
engine: string, which backend to use.

valid choices are ‘blender’ or ‘scad’

Returns:
intersection: **kwargs for a Trimesh object of the

volume that is contained by all meshes

trimesh.boolean.union(meshes, engine=None)

Compute the boolean union between a mesh an n other meshes.

Parameters:
meshes: list of Trimesh object
engine: string, which backend to use.

valid choices are ‘blender’ or ‘scad’

Returns:
union: a + (other meshes), **kwargs for a Trimesh

trimesh.bounds module

trimesh.bounds.contains(bounds, points)

Do an axis aligned bounding box check on a list 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

trimesh.bounds.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

trimesh.bounds.minimum_cylinder(obj, sample_count=10, 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

trimesh.bounds.oriented_bounds(obj, angle_digits=1, ordered=True)

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.

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

trimesh.bounds.oriented_bounds_2D(points, qhull_options='QbB')

Find an oriented bounding box for an array of 2D points.

Parameters:
points : (n,2) float

Points in 2D.

Returns:
transform : (3,3) float

Homogenous 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

trimesh.caching module

caching.py

Functions and classes that help with tracking changes in ndarrays and clearing cached values based on those changes.

class trimesh.caching.Cache(id_function)

Bases: object

Class to cache values which will be stored until the result of an ID function changes.

Methods

clear([exclude]) Remove all elements in the cache.
delete(key) Remove a key from the cache.
id_set() Set the current ID to the value of the ID function.
update(items) Update the cache with a set of key, value pairs without checking id_function.
verify() 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.
clear(exclude=None)

Remove all elements in the cache.

delete(key)

Remove a key from the cache.

id_set()

Set the current ID to the value of the ID function.

update(items)

Update the cache with a set of key, value pairs without checking id_function.

verify()

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.

class trimesh.caching.DataStore

Bases: object

A class to store multiple numpy arrays and track them all for changes.

Operates like a dict that only stores numpy.ndarray

Attributes:
mutable

Methods

clear() Remove all data from the DataStore.
crc() Get a CRC reflecting everything in the DataStore.
fast_hash() Get a CRC32 or xxhash.xxh64 reflecting the DataStore.
is_empty() Is the current DataStore empty or not.
md5() Get an MD5 reflecting everything in the DataStore.
update  
values  
clear()

Remove all data from the DataStore.

crc()

Get a CRC reflecting everything in the DataStore.

Returns:
crc: int, CRC of data
fast_hash()

Get a CRC32 or xxhash.xxh64 reflecting the DataStore.

Returns:
hashed: int, checksum of data
is_empty()

Is the current DataStore empty or not.

Returns:
empty: bool, False if there are items in the DataStore
md5()

Get an MD5 reflecting everything in the DataStore.

Returns:
md5: str, MD5 in hexadecimal
mutable
update(values)
values()
class trimesh.caching.TrackedArray

Bases: 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.

Attributes:
T

Same as self.transpose(), except that self is returned if self.ndim < 2.

base

Base object if memory is from some other object.

ctypes

An object to simplify the interaction of the array with the ctypes module.

data

Python buffer object pointing to the start of the array’s data.

dtype

Data-type of the array’s elements.

flags

Information about the memory layout of the array.

flat

A 1-D iterator over the array.

imag

The imaginary part of the array.

itemsize

Length of one array element in bytes.

nbytes

Total bytes consumed by the elements of the array.

ndim

Number of array dimensions.

real

The real part of the array.

shape

Tuple of array dimensions.

size

Number of elements in the array.

strides

Tuple of bytes to step in each dimension when traversing an array.

Methods

md5() Return an MD5 hash of the current array.
crc() A zlib.crc32 or zlib.adler32 checksum of the current data.
fast_hash() An xxhash.b64 hash of the array.
crc()

A zlib.crc32 or zlib.adler32 checksum of the current data.

Returns:
crc: int, checksum from zlib.crc32 or zlib.adler32
fast_hash()

An xxhash.b64 hash of the array.

Returns:
xx: int, xxhash.xxh64 hash of array.
md5()

Return an MD5 hash of the current array.

Returns:
md5: str, hexadecimal MD5 of the array
trimesh.caching.cache_decorator(function)

A decorator for class methods, replaces @property but will store and retrieve function return values in object cache.

Parameters:
function : class method
This is used as a decorator:

@cache_decorator def foo(self, things):

return ‘happy days’

trimesh.caching.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: which dtype to use for the array
Returns:
tracked: TrackedArray, of input array data

trimesh.collision module

class trimesh.collision.CollisionManager

Bases: object

A mesh-mesh collision manager.

Methods

add_object(name, mesh[, transform]) Add an object to the collision manager.
in_collision_internal([return_names, …]) Check if any pair of objects in the manager collide with one another.
in_collision_other(other_manager[, …]) Check if any object from this manager collides with any object from another manager.
in_collision_single(mesh[, transform, …]) Check a single object for collisions against all objects in the manager.
min_distance_internal([return_names, …]) Get the minimum distance between any pair of objects in the manager.
min_distance_other(other_manager[, …]) Get the minimum distance between any pair of objects, one in each manager.
min_distance_single(mesh[, transform, …]) Get the minimum distance between a single object and any object in the manager.
remove_object(name) Delete an object from the collision manager.
set_transform(name, transform) Set the transform for one of the manager’s objects.
add_object(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

Homogenous transform matrix for the object

in_collision_internal(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(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(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

Homogenous 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

The set of names of objects that collided with the provided one

contacts : list of ContactData

All contacts detected

min_distance_internal(return_names=False, return_data=False)

Get the minimum distance between any pair of objects in the manager.

Parameters:
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 any two managed objects

names : (2,) str

The names of the closest objects

data : DistanceData

Extra data about the distance query

min_distance_other(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(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

Homogenous 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(name)

Delete an object from the collision manager.

Parameters:
name : str

The identifier for the object

set_transform(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 homogenous transform matrix for the object

class trimesh.collision.ContactData(names, contact)

Bases: object

Data structure for holding information about a collision contact.

Attributes:
point

The 3D point of intersection for this contact.

Methods

index(name) Returns the index of the face in contact for the mesh with the given name.
index(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 collison

point

The 3D point of intersection for this contact.

Returns:
point : (3,) float

The intersection point.

class trimesh.collision.DistanceData(names, result)

Bases: object

Data structure for holding information about a distance query.

Attributes:
distance

Returns the distance between the two objects.

Methods

index(name) Returns the index of the closest face for the mesh with the given name.
point(name) The 3D point of closest distance on the mesh with the given name.
distance

Returns the distance between the two objects.

Returns:
distance : float

The euclidean distance between the objects.

index(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(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.

trimesh.collision.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

trimesh.collision.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

trimesh.comparison module

comparison.py

Provide methods for quickly hashing and comparing meshes.

trimesh.comparison.identifier_hash(identifier, sigfig=None)

Hash an identifier array to a specified number of significant figures.

Parameters:
identifier: (n,) float
sigfig: (n,) int
Returns:
md5: str, MD5 hash of identifier
trimesh.comparison.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 tesselations.

Parameters:
mesh: Trimesh object
Returns:
identifier: (6,) float, identifying values of the mesh

trimesh.constants module

class trimesh.constants.NumericalResolutionPath(**kwargs)

Bases: object

res.seg_frac: when discretizing curves, what percentage of the drawing
scale should we aim to make a single segment

res.seg_angle: when discretizing curves, what angle should a section span res.max_sections: when discretizing splines, what is the maximum number

of segments per control point
res.min_sections: when discretizing splines, what is the minimum number
of segments per control point

res.export: format string to use when exporting floating point vertices

class trimesh.constants.NumericalToleranceMesh(**kwargs)

Bases: object

tol.zero: consider floating point numbers less than this zero

tol.merge: 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: the maximum distance from a plane a point can be and
still be considered to be on the plane

tol.facet_threshold: threshold for two facets to be considered coplanar

class trimesh.constants.NumericalTolerancePath(**kwargs)

Bases: object

tol.zero: consider floating point numbers less than this zero tol.merge: when merging vertices, consider vertices closer than this

to be the same vertex
tol.planar: the maximum distance from a plane a point can be and
still be considered to be on the plane
tol.seg_frac: when simplifying line segments what percentage of the drawing
scale can a segment be and have a curve fitted
tol.seg_angle: when simplifying line segments to arcs, what angle
can a segment span to be acceptable.
tol.aspect_frac: 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: 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.

trimesh.convex module

convex.py

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

trimesh.convex.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

trimesh.convex.convex_hull(obj, qhull_options='QbB Pp QJn')

Get a new Trimesh object representing the convex hull of the current mesh, with proper normals and watertight. Requires scipy >.12.

obj : Trimesh, or (n,3) float
Mesh or cartesian points
Returns:
convex : Trimesh

Mesh of convex hull

trimesh.convex.hull_points(obj, qhull_options='QbB Pp')

Try to extract a convex set of points from multiple input formats.

obj: Trimesh object
(n,d) points (m,) Trimesh objects
Returns:
points: (o,d) convex set of points
trimesh.convex.is_convex(mesh)

Check if a mesh is convex.

Parameters:
mesh : Trimesh

Input geometry

Returns:
convex : bool

Was passed mesh convex or not

trimesh.creation module

creation.py

Create meshes from primitives, or with operations.

trimesh.creation.annulus(r_min=1.0, r_max=2.0, height=1.0, sections=32, transform=None)

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

How many pie wedges should the annular cylinder have

Returns:
annulus : trimesh.Trimesh

Mesh of annular cylinder

trimesh.creation.box(extents=None, transform=None)

Return a cuboid.

Parameters:
extents: float, or (3,) float edge length
transform: (4, 4) float, transformation matrix
Returns:
box: Trimesh object
trimesh.creation.capsule(height=1.0, radius=1.0, count=[32, 32])

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
Returns:
capsule: Trimesh of capsule with given properties
  • cylinder axis is along Z
  • one hemisphere is centered at the origin
  • other hemisphere is centered along the Z axis at specified height
trimesh.creation.cylinder(radius=1.0, height=1.0, sections=32, transform=None)

Create a mesh of a cylinder along Z centered at the origin.

Parameters:
radius : float

The radius of the cylinder

height : float

The height of the cylinder

sections : int

How many pie wedges should the cylinder have

Returns:
cylinder: Trimesh, resulting mesh
trimesh.creation.extrude_polygon(polygon, height, **kwargs)

Extrude a 2D shapely polygon into a 3D mesh

Parameters:
polygon: shapely.geometry.Polygon object
height: float, distance to extrude polygon along Z
Returns:
mesh: Trimesh object of result
trimesh.creation.extrude_triangulation(vertices, faces, height, **kwargs)

Turn a 2D triangulation into a watertight Trimesh.

Parameters:
vertices : (n, 2) float

2D vertices

faces : (m, 3) int

Triangle indexes of vertices

height : float

Distance to extrude triangulation

Returns:
mesh : trimesh.Trimesh

Mesh created from extrusion

trimesh.creation.icosahedron()

Create an icosahedron, a 20 faced polyhedron.

trimesh.creation.icosphere(subdivisions=3, radius=1.0)

Create an isophere 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

Returns:
ico : trimesh.Trimesh

Meshed sphere

trimesh.creation.random_soup(face_count=100)

Return a random set of triangles as a Trimesh

Parameters:
face_count: int, number of faces in resultant mesh
Returns:
soup: Trimesh object with face_count random faces
trimesh.creation.sweep_polygon(polygon, path, angles=None, **kwargs)

Extrude a 2D shapely polygon into a watertight 3D mesh along an arbitrary 3D path.

Parameters:
polygon: shapely.geometry.Polygon object
path: (n,3) float, a path in 3D
angles: (n,) float, optional rotation angle relative to prior vertex

at each vertex

Returns:
mesh : Trimesh object of result
trimesh.creation.triangulate_polygon(polygon, triangle_args='pq0D', engine='auto', **kwargs)

Given a shapely polygon create a triangulation using one of the python interfaces to triangle.c: pip install meshpy pip install triangle

polygon : Shapely.geometry.Polygon
Polygon object to be triangulated
triangle_args : str
Passed to triangle.triangulate
engine : str
‘meshpy’, ‘triangle’, or ‘auto’
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)
vertices : (n, 2) float
Points in space
faces : (n, 3) int
Index of vertices that make up triangles
trimesh.creation.uv_sphere(radius=1.0, count=[32, 32], theta=None, phi=None)

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

theta : (n,) float

Optional theta angles in radians

phi : (n,) float

Optional phi angles in radians

Returns:
mesh : trimesh.Trimesh

Mesh of UV sphere with specified parameters

trimesh.creation.validate_polygon(obj)

trimesh.curvature module

curvature.py

Query mesh curvature.

trimesh.curvature.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.

Parameters:
points : (n,3) float, list of points in space
radius : float, the sphere radius
Returns:
gaussian_curvature: (n,) float, discrete gaussian curvature measure.
trimesh.curvature.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.

Parameters:
points : (n,3) float, list of points in space
radius : float, the sphere radius
Returns:
mean_curvature: (n,) float, discrete mean curvature measure.
trimesh.curvature.face_angles(mesh)

Returns the angle at each vertex of a face.

Returns:
angles: (n, 3) float, angle at each vertex of a face.
trimesh.curvature.face_angles_sparse(mesh)

A sparse matrix representation of the face angles.

Returns:
sparse: scipy.sparse.coo_matrix with:

dtype: float shape: (len(mesh.vertices), len(mesh.faces))

trimesh.curvature.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.
trimesh.curvature.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.
trimesh.curvature.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

trimesh.decomposition module

trimesh.decomposition.convex_decomposition(mesh, engine=None, **kwargs)

Compute an approximate convex decomposition of a mesh.

Parameters:
mesh: Trimesh object
engine: string, which backend to use. Valid choice is ‘vhacd’.
Returns:
mesh_args: list, list of **kwargs for Trimeshes that are nearly

convex and approximate the original.

trimesh.decomposition.decomposition_automatic(mesh, **kwargs)

trimesh.geometry module

trimesh.geometry.align_vectors(vector_start, vector_end, return_angle=False)

Returns the 4x4 transformation matrix which will rotate from vector_start to vector_end, eg:

vector_end == np.dot(T, np.append(vector_start, 1))[0:3]

Parameters:
vector_start: (3,) float, vector in space
vector_end: (3,) float, vector in space
return_angle: bool, return angle between vectors or not
Returns:
transform: (4,4) float, transformation matrix
angle: float, angle in radians (only returned if flag set)
trimesh.geometry.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
trimesh.geometry.index_sparse(column_count, indices)

Return a sparse matrix for which vertices are contained in which faces.

Returns:
sparse: scipy.sparse.coo_matrix of shape (column_count, 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])

trimesh.geometry.mean_vertex_normals(vertex_count, faces, face_normals, **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

Uncontained vertices will be zero.

trimesh.geometry.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

trimesh.geometry.triangulate_quads(quads)

Given a set of quad faces, return them as triangle faces.

Parameters:
quads: (n,4) int, vertex indices of quad faces
Returns:
faces: (m,3) int, vertex indices of triangular faces
trimesh.geometry.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

trimesh.graph module

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, scipy.sparse.csgraph, or graph_tool backends.

trimesh.graph.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

trimesh.graph.connected_components(edges, min_len=1, nodes=None, engine=None)

Find groups of connected nodes from an edge list.

Parameters:
edges: (n,2) int, edges between nodes
nodes: (m, ) int, list of nodes that exist
min_len: int, minimum length of a component group to return
engine: str, which graph engine to use.

(‘networkx’, ‘scipy’, or ‘graphtool’) If None, will automatically choose fastest available.

Returns:
components: (n,) sequence of lists, nodes which are connected
trimesh.graph.connected_edges(G, nodes)

Given graph G and list of nodes, return the list of edges that are connected to nodes

trimesh.graph.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

trimesh.graph.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

List of vertex indices representing triangles

mesh : Trimesh object

If passed will used cached edges instead of 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: >>> graph = nx.Graph() >>> graph.add_edges_from(mesh.face_adjacency) >>> groups = nx.connected_components(graph_connected)

trimesh.graph.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

trimesh.graph.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
Returns:
vid_unshared : (len(mesh.face_adjacency), 2) int

Indexes of mesh.vertices

trimesh.graph.facets(mesh, engine=None)

Find the list of parallel adjacent faces.

mesh : trimesh.Trimesh engine : str

Which graph engine to use: (‘scipy’, ‘networkx’, ‘graphtool’)
Returns:
facets : sequence of (n,) int

Groups of face indexes of parallel adjacent faces.

trimesh.graph.fill_traversals(traversals, edges, edges_hash=None)

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

edges_hash : None, or (n,) int

Edges sorted along axis 1 then hashed using grouping.hashable_rows

Returns:
splits : sequence of (p,) int

Node indexes of connected traversals

trimesh.graph.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
trimesh.graph.is_watertight(edges, edges_sorted=None)

edges: (n, 2) int, set of vertex indices edges_sorted: (n, 2) int, vertex indices sorted on axis 1

Returns:
watertight: boolean, whether every edge is shared by an even

number of faces

winding: boolean, whether every shared edge is reversed
trimesh.graph.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
trimesh.graph.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
source: str, node to start off
cutoff: int, number of nodes to visit

if None, will

Returns:
traversals: (n,) list of [(node, edge instance index), ] paths
trimesh.graph.shared_edges(faces_a, faces_b)

Given two sets of faces, find the edges which are in both sets.

faces_a: (n,3) int, set of faces faces_b: (m,3) int, set of faces

Returns:
shared: (p, 2) int, set of edges
trimesh.graph.smoothed(mesh, angle)

Return a non- watertight version of the mesh which will render nicely with smooth shading.

mesh: Trimesh object angle: float, angle in radians, adjacent faces which have normals

below this angle will be smoothed.
Returns:
smooth: Trimesh object
trimesh.graph.split(mesh, only_watertight=True, adjacency=None, engine=None)

Split a mesh into multiple meshes from face connectivity.

If only_watertight is true, it will only return watertight meshes and will attempt single triangle/quad repairs.

Parameters:
mesh: Trimesh
only_watertight: if True, only return watertight components
adjacency: (n,2) list of face adjacency to override using the plain

adjacency calculated automatically.

engine: str, which engine to use. (‘networkx’, ‘scipy’, or ‘graphtool’)
Returns:
meshes: list of Trimesh objects
trimesh.graph.split_traversal(traversal, edges, edges_hash=None)

Given a traversal as a list of nodes, split the traversal if a sequential index pair is not in the given edges.

Parameters:
edges : (n, 2) int

Graph edge indexes

traversal : (m,) int

Traversal through edges

edge_hash : (n,)

Edges sorted on axis=1 and passed to grouping.hashable_rows

Returns:
split : sequence of (p,) int
trimesh.graph.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, ‘bfs’, or ‘dfs’
Returns:
traversals: (m,) sequence of (p,) int,

ordered DFS or BFS traversals of the graph.

trimesh.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]

trimesh.grouping module

grouping.py

Functions for grouping values and rows.

trimesh.grouping.blocks(data, min_len=2, max_len=inf, digits=None, only_nonzero=False)

Given an array, find the indices of contiguous blocks of equal values.

data: (n) array min_len: int, the minimum length group to be returned max_len: int, the maximum length group to be retuurned digits: if dealing with floats, how many digits to use only_nonzero: bool, only return blocks of non- zero values

Returns:
blocks: (m) sequence of indices referencing data
trimesh.grouping.boolean_rows(a, b, operation=<function intersect1d>)

Find the rows in two arrays which occur in both rows.

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) array containing rows in both a and b
trimesh.grouping.clusters(points, radius)

Find clusters of points which have neighbours closer than radius

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

trimesh.grouping.float_to_int(data, digits=None, dtype=<class 'numpy.int32'>)

Given a numpy array of float/bool/int, return as integers.

Parameters:
data: (n, d) float, int, or bool data
digits: float/int precision for float conversion
dtype: numpy dtype for result
Returns:
as_int: data, as integers
trimesh.grouping.group(values, min_len=0, max_len=inf)

Return the indices of values that are identical

Parameters:
values: 1D array
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 of indices to form groups

IE [0,1,0,1] returns [[0,2], [1,3]]

trimesh.grouping.group_distance(values, distance)

Find groups of points which have neighbours closer than radius, where no two points in a group are farther than distance apart.

points : (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

trimesh.grouping.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

trimesh.grouping.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]]

Parameters:
data: (n,m) array
require_count: only returns groups of a specified length, eg:

require_count = 2 [[1,2], [3,4], [1,2]] will return [[0,2]]

Note that using require_count allows numpy advanced indexing to be used in place of looping and checking hashes, and as a consequence is ~10x faster.

digits: If data is floating point, how many decimals to look at.

If this is None, the value in TOL_MERGE will be turned into a digit count and used.

Returns:
groups: List or sequence of indices from data indicating identical rows.

If require_count != None, shape will be (j, require_count) If require_count is None, shape will be irregular (AKA a sequence)

trimesh.grouping.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

trimesh.grouping.hashable_rows(data, digits=None)

We turn our array into integers based on the precision given by digits and then put them in a hashable format.

data: (n,m) input array digits: how many digits to add to hash, if data is floating point

If none, TOL_MERGE will be turned into a digit count and used.
Returns:
hashable: (n) length array of custom data which can be sorted

or used as hash keys

trimesh.grouping.merge_runs(data, digits=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])

trimesh.grouping.merge_vertices_hash(mesh, distance=None)

Removes duplicate vertices, based on integer hashes of each row.

Parameters:
mesh : Trimesh object

Mesh to merge vertices of

distance : float, or None

If not specified uses tol.merge

trimesh.grouping.unique_float(data, return_index=False, return_inverse=False, digits=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.

trimesh.grouping.unique_ordered(data)

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])

trimesh.grouping.unique_rows(data, digits=None)

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]

data: (n,m) set of floating point data digits: how many digits to consider for the purposes of uniqueness

Returns:
unique: (j) array, index in data which is a unique row
inverse: (n) length array to reconstruct original

example: unique[inverse] == data

trimesh.grouping.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
unique: (m) int, list of unique values contained in data.

speedup purposes only, 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)

trimesh.inertia module

inertia.py

Functions for dealing with inertia tensors.

Results validated against known geometries and for internal consistency.

trimesh.inertia.cylinder_inertia(mass, radius, height, transform=None)

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
trimesh.inertia.principal_axis(inertia)

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

trimesh.inertia.radial_symmetry(mesh)

Check whether a mesh has rotational symmetry.

Returns:
symmetry: None No rotational symmetry

‘radial’ Symmetric around an axis ‘spherical’ Symmetric around a point

axis: None, or (3,) float
section: None, or (3, 2) float
trimesh.inertia.sphere_inertia(mass, radius)

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
trimesh.inertia.transform_inertia(transform, inertia_tensor)

Transform an inertia tensor to a new frame.

More details in OCW PDF: MIT16_07F09_Lec26.pdf

Parameters:
transform: (3,3) or (4,4) float, transformation matrix
inertia_tensor: (3,3) float, inertia tensor
Returns:
transformed: (3,3) float, inertia tensor in new frame

trimesh.integrate module

integrate.py

Utilities for integrating functions over meshes surfaces.

trimesh.integrate.substitute_barycentric(function)
trimesh.integrate.symbolic_barycentric(function)

Symbolically integrate a function(x,y,z) across a triangle or mesh.

Parameters:
function: string or sympy expression

x, y, z will be replaced with a barycentric representation and the the function is integrated across the triangle.

Returns:
evaluator: numpy lambda function of result which takes a mesh
expr: sympy expression of result

Examples

In [1]: function = ‘1’

In [2]: integrator, expr = integrate_barycentric(function)

In [3]: integrator Out[3]: <__main__.evaluator instance at 0x7f66cd2a6200>

In [4]: expr Out[4]: 1/2

In [5]: result = integrator(mesh)

In [6]: mesh.area Out[6]: 34.641016151377542

In [7]: result.sum() Out[7]: 34.641016151377542

trimesh.intersections module

intersections.py

Primarily mesh-plane intersections (slicing).

trimesh.intersections.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_normal : (3,) float

Normal vector of plane

plane_origin : (3,) float

Point on a plane

heights : (m,) float

Offset distances from plane to slice at

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

trimesh.intersections.mesh_plane(mesh, plane_normal, plane_origin, return_faces=False, cached_dots=None)

Find a the intersections between a mesh and a plane, returning a set of line segments on that plane.

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
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

trimesh.intersections.plane_lines(plane_origin, plane_normal, endpoints, line_segments=True)

Calculate plane-line intersections

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

trimesh.intersections.planes_lines(plane_origins, plane_normals, line_origins, line_directions)

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

Returns:
on_plane : (n,3) float

Points on specified planes

valid : (n,) bool

Did plane intersect line or not

trimesh.intersections.slice_mesh_plane(mesh, plane_normal, plane_origin, cached_dots=None)

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

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
cached_dots : (n, 3) float
If an external function has stored dot products pass them here to avoid recomputing
new_mesh : Trimesh object
Sliced mesh

trimesh.nsphere module

nsphere.py

Functions for fitting and minimizing nspheres: circles, spheres, hyperspheres, etc.

trimesh.nsphere.fit_nsphere(points, prior=None)

Fit an n-sphere to a set of points using least squares.

points: (n,d) set of points prior: (d,) float, best guess for center of nsphere

Returns:
center: (d), location of center
radius: float, mean radius across circle
error: float, peak to peak value of deviation from mean radius
trimesh.nsphere.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
trimesh.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: Trimesh object OR

(n,d) float, set of points

Returns:
center: (d) float, center of n- sphere
radius: float, radius of n-sphere

trimesh.parent module

parent.py

The base class for Trimesh, PointCloud, and Scene objects

class trimesh.parent.Geometry

Bases: object

Attributes:
bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

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 : trimesh.primitives.Sphere

trimesh.primitives.Box trimesh.primitives.Cylinder

Primitive which bounds the mesh with the smallest volume

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

trimesh.permutate module

permutate.py

Randomly deform meshes in different ways.

class trimesh.permutate.Permutator(mesh)

Bases: object

Methods

noise([magnitude]) Add gaussian noise to every vertex of a mesh.
tessellation() Subdivide each face of a mesh into three faces with the new vertex randomly placed inside the old face.
transform() Return a permutated variant of a mesh by randomly reording faces and rotatating + translating a mesh by a random matrix.
noise(magnitude=None)

Add gaussian noise to every vertex of a mesh. Makes no effort to maintain topology or sanity.

Parameters:
mesh: Trimesh object (will not be mutated)
magnitude: float, what is the maximum distance per axis we can displace a vertex.

Default value is mesh.scale/100.0

Returns:
permutated: Trimesh object, input mesh with noise applied
tessellation()

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 object
Returns:
permutated: Trimesh object with remeshed facets
transform()

Return a permutated variant of a mesh by randomly reording faces and rotatating + translating a mesh by a random matrix.

Parameters:
mesh: Trimesh object (input will not be altered by this function)
Returns:
permutated: Trimesh object, same faces as input mesh but

rotated and reordered.

trimesh.permutate.noise(mesh, magnitude=None)

Add gaussian noise to every vertex of a mesh. Makes no effort to maintain topology or sanity.

Parameters:
mesh: Trimesh object (will not be mutated)
magnitude: float, what is the maximum distance per axis we can displace a vertex.

Default value is mesh.scale/100.0

Returns:
permutated: Trimesh object, input mesh with noise applied
trimesh.permutate.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 object
Returns:
permutated: Trimesh object with remeshed facets
trimesh.permutate.transform(mesh, translation_scale=1000.0)

Return a permutated variant of a mesh by randomly reording faces and rotatating + translating a mesh by a random matrix.

Parameters:
mesh: Trimesh object (input will not be altered by this function)
Returns:
permutated: Trimesh object, same faces as input mesh but

rotated and reordered.

trimesh.points module

points.py

Functions dealing with (n, d) points.

class trimesh.points.PointCloud(*args, **kwargs)

Bases: trimesh.parent.Geometry

Hold 3D points in an object which can be visualized in a scene.

Attributes:
bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

bounds

The axis aligned bounds of the PointCloud

centroid

The mean vertex position

colors

Stored per- point color

convex_hull

A convex hull of every point.

extents

The size of the axis aligned bounds

shape

Get the shape of the pointcloud

vertices

Vertices of the PointCloud

Methods

apply_transform(transform) Apply a homogenous transformation to the PointCloud object in- place.
md5() Get an MD5 hash of the current vertices.
merge_vertices() Merge vertices closer than tol.merge (default: 1e-8)
scene() A scene containing just the PointCloud
show() Open a viewer window displaying the current PointCloud
apply_transform(transform)

Apply a homogenous transformation to the PointCloud object in- place.

Parameters:
transform : (4, 4) float

Homogenous transformation to apply to PointCloud

bounds

The axis aligned bounds of the PointCloud

Returns:
bounds : (2, 3) float

Miniumum, Maximum verteex

centroid

The mean vertex position

Returns:
centroid : (3,) float

Mean vertex position

colors

Stored per- point color

Returns:
colors : (len(self.vertices), 4) np.uint8

Per- point RGBA color

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

md5()

Get an MD5 hash of the current vertices.

Returns:
md5 : str

Hash of self.vertices

merge_vertices()

Merge vertices closer than tol.merge (default: 1e-8)

scene()

A scene containing just the PointCloud

Returns:
scene : trimesh.Scene

Scene object containing this PointCloud

shape

Get the shape of the pointcloud

Returns:
shape : (2,) int

Shape of vertex array

show()

Open a viewer window displaying the current PointCloud

vertices

Vertices of the PointCloud

Returns:
vertices : (n, 3) float

Points in the PointCloud

trimesh.points.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 a 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

trimesh.points.major_axis(points)

Returns an approximate vector representing the major axis of points

Parameters:
points: (n, dimension) float, points in space
Returns:
axis: (dimension,) float, vector along approximate major axis
trimesh.points.plane_fit(points)

Given a set of points, find an origin and normal using SVD.

points : (n,3) float
Points in 3D space
Returns:
C : (3,) float

Point on the plane

N : (3,) float

Normal vector of plane

trimesh.points.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

trimesh.points.point_plane_distance(points, plane_normal, plane_origin=[0.0, 0.0, 0.0])

The minimum perpendicular distance of a point to a plane.

Parameters:
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vector
plane_origin: (3,) float, plane origin in space
Returns:
distances: (n,) float, distance from point to plane
trimesh.points.project_to_plane(points, plane_normal=[0, 0, 1], plane_origin=[0, 0, 0], transform=None, return_transform=False, return_planar=True)

Projects a set of (n,3) points onto a plane.

points: (n,3) array of points plane_normal: (3) normal vector of plane plane_origin: (3) point on plane transform: None or (4,4) matrix. If specified, normal/origin are ignored return_transform: bool, if true returns the (4,4) matrix used to project points

onto a plane
return_planar: bool, if True, returns (n,2) points. If False, returns
(n,3), where the Z column consists of zeros
trimesh.points.radial_sort(points, origin, normal)

Sorts a set of points radially (by angle) around an origin/normal.

Parameters:
points: (n,3) float, points in space
origin: (3,) float, origin to sort around
normal: (3,) float, vector to sort around
Returns:
ordered: (n,3) flot, re- ordered points in space
trimesh.points.remove_close(points, radius)

Given an (n, m) set of points where n=(2|3) return a list 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 set were returned

trimesh.points.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.

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

trimesh.poses module

poses.py

Find stable orientations of meshes.

trimesh.poses.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 probabilites.

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 evaulates the probabilities of landing in each pose if the object is dropped onto the table randomly.

This method returns the 4x4 homogenous 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 probabilties that are returned are sorted, with the most probable pose first.

Parameters:
mesh: Trimesh object, the target mesh
com: (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 loc
threshold: float, the probability value at which to threshold

returned stable poses

Returns:
transforms: list of (4,4) floats, the homogenous 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: list of floats, a probability in (0, 1) for each pose

trimesh.primitives module

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.

class trimesh.primitives.Box(*args, **kwargs)

Bases: trimesh.primitives._Primitive

Attributes:
area

Summed area of all triangles in the current mesh.

area_faces

The area of each face in the mesh.

body_count

How many connected groups of vertices exist in this mesh.

bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

bounds

The axis aligned bounds of the mesh.

center_mass

The point in space which is the center of mass/volume.

centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

density

The density of the mesh.

edges

Edges of the mesh (derived from faces).

edges_face

Which face does each edge belong to.

edges_sorted

Edges sorted along axis 1

edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

edges_unique

The unique edges of the mesh.

edges_unique_length

How long is each unique edge.

euler_number

Return the Euler characteristic (a topological invariant) for the mesh

extents

The length, width, and height of the bounding box of the mesh.

face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

face_adjacency_angles

Return the angle between adjacent faces

face_adjacency_convex

Return faces which are adjacent and locally convex.

face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

face_adjacency_projections

The projection of the non- shared vertex of a triangle onto

face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

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.

face_adjacency_tree

An R-tree of face adjacencies.

face_adjacency_unshared

Return the vertex index of the two vertices not in the shared

face_angles

Returns the angle at each vertex of a face.

face_angles_sparse

A sparse matrix representation of the face angles.

face_normals

Return the unit normal vector for each face.

faces

The faces of the mesh.

faces_sparse

A sparse matrix representation of the faces.

faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

facets

Return a list of face indices for coplanar adjacent faces.

facets_area

Return an array containing the area of each facet.

facets_boundary

Return the edges which represent the boundary of each facet

facets_normal

Return the normal of each facet

facets_on_hull

Find which facets of the mesh are on the convex hull.

facets_origin

Return a point on the facet plane.

identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

identifier_md5

An MD5 of the rotation invariant identifier vector

is_convex

Check if a mesh is convex or not.

is_empty

Does the current mesh have data defined.

is_oriented

Returns whether or not the current box is rotated at all.

is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

is_winding_consistent

Does the mesh have consistent winding or not.

kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh.

mass

Mass of the current mesh, based on specified density and volume.

mass_properties

Returns the mass properties of the current mesh.

moment_inertia

Return the moment of inertia matrix of the current mesh.

principal_inertia_components

Return the 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.

principal_inertia_vectors

Return the principal axis of inertia.

scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

symmetry

Check whether a mesh has rotational symmetry.

symmetry_axis

If a mesh has rotational symmetry, return the axis.

symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

triangles

Actual triangles of the mesh (points, not indexes)

triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

triangles_cross

The cross product of two edges of each triangle.

triangles_tree

An R-tree containing each face of the mesh.

units

Definition of units for the mesh.

vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

vertex_normals

The vertex normals of the mesh.

vertices

The vertices of the mesh.

volume

Volume of the box Primitive.

Methods

apply_obb() Apply the oriented bounding box transform to the current mesh.
apply_scale(scaling) Scale the mesh equally on all axis.
apply_transform(matrix) Apply a transform to the current primitive (sets self.transform)
apply_translation(translation) Translate the current mesh.
compute_stable_poses([center_mass, sigma, …]) Computes stable orientations of a mesh and their quasi-static probabilites.
contains(points) Given a set of points, determine whether or not they are inside the mesh.
convert_units(desired[, guess]) Convert the units of the mesh into a specified unit.
convex_decomposition([engine, maxhulls]) Compute an approximate convex decomposition of a mesh.
copy() Return a copy of the Primitive object.
crc() A zlib.adler32 checksum for the current mesh data.
difference(other[, engine]) Boolean difference between this mesh and n other meshes
eval_cached(statement, *args) Evaluate a statement and cache the result before returning.
export([file_obj, file_type]) Export the current mesh to a file object.
fill_holes() Fill single triangle and single quad holes in the current mesh.
fix_normals(**kwargs) Find and fix problems with self.face_normals and self.faces winding direction.
intersection(other[, engine]) Boolean intersection between this mesh and n other meshes
invert() Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.
md5() An MD5 of the core geometry information for the mesh, faces and vertices.
merge_vertices([distance]) If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.
outline([face_ids]) Given a set of face ids, find the outline of the faces, and return it as a Path3D.
process() Do the bare minimum processing to make a mesh useful.
register(other, **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.
remove_degenerate_faces([height]) Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.
remove_duplicate_faces() On the current mesh remove any faces which are duplicates.
remove_infinite_values() Ensure that every vertex and face consists of finite numbers.
remove_unreferenced_vertices() Remove all vertices in the current mesh which are not referenced by a face.
rezero() Translate the mesh so that all vertex vertices are positive.
sample(count[, return_index]) Return random samples distributed normally across the surface of the mesh
sample_grid([count, step]) Return a 3D grid which is contained by the box.
sample_volume(count) Return random samples from inside the volume of the box.
scene(**kwargs) Get a Scene object containing the current mesh.
section(plane_normal, plane_origin) Returns a 3D cross section of the current mesh and a plane defined by origin and normal.
section_multiplane(plane_origin, …) Return multiple parallel cross sections of the current mesh in 2D.
show(**kwargs) Render the mesh in an opengl window.
slice_plane(plane_origin, plane_normal) Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.
smoothed(**kwargs) Return a version of the current mesh which will render nicely.
split(**kwargs) Returns a list of Trimesh objects, based on face connectivity.
subdivide([face_index]) Subdivide a mesh, with each subdivided face replaced with four smaller faces.
submesh(faces_sequence, **kwargs) Return a subset of the mesh.
to_dict() Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:
to_mesh() Return a copy of the Primitive object as a Trimesh object.
union(other[, engine]) Boolean union between this mesh and n other meshes
unmerge_vertices() Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.
update_faces(mask) In many cases, we will want to remove specific faces.
update_vertices(mask[, inverse]) Update vertices with a mask.
voxelized(pitch, **kwargs) Return a Voxel object representing the current mesh discretized into voxels at the specified pitch
is_oriented

Returns whether or not the current box is rotated at all.

sample_grid(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(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
volume

Volume of the box Primitive.

Returns:
volume: float, volume of box
class trimesh.primitives.Capsule(*args, **kwargs)

Bases: trimesh.primitives._Primitive

Attributes:
area

Summed area of all triangles in the current mesh.

area_faces

The area of each face in the mesh.

body_count

How many connected groups of vertices exist in this mesh.

bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

bounds

The axis aligned bounds of the mesh.

center_mass

The point in space which is the center of mass/volume.

centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

density

The density of the mesh.

direction

The direction of the capsule’s axis.

edges

Edges of the mesh (derived from faces).

edges_face

Which face does each edge belong to.

edges_sorted

Edges sorted along axis 1

edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

edges_unique

The unique edges of the mesh.

edges_unique_length

How long is each unique edge.

euler_number

Return the Euler characteristic (a topological invariant) for the mesh

extents

The length, width, and height of the bounding box of the mesh.

face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

face_adjacency_angles

Return the angle between adjacent faces

face_adjacency_convex

Return faces which are adjacent and locally convex.

face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

face_adjacency_projections

The projection of the non- shared vertex of a triangle onto

face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

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.

face_adjacency_tree

An R-tree of face adjacencies.

face_adjacency_unshared

Return the vertex index of the two vertices not in the shared

face_angles

Returns the angle at each vertex of a face.

face_angles_sparse

A sparse matrix representation of the face angles.

face_normals

Return the unit normal vector for each face.

faces

The faces of the mesh.

faces_sparse

A sparse matrix representation of the faces.

faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

facets

Return a list of face indices for coplanar adjacent faces.

facets_area

Return an array containing the area of each facet.

facets_boundary

Return the edges which represent the boundary of each facet

facets_normal

Return the normal of each facet

facets_on_hull

Find which facets of the mesh are on the convex hull.

facets_origin

Return a point on the facet plane.

identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

identifier_md5

An MD5 of the rotation invariant identifier vector

is_convex

Check if a mesh is convex or not.

is_empty

Does the current mesh have data defined.

is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

is_winding_consistent

Does the mesh have consistent winding or not.

kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh.

mass

Mass of the current mesh, based on specified density and volume.

mass_properties

Returns the mass properties of the current mesh.

moment_inertia

Return the moment of inertia matrix of the current mesh.

principal_inertia_components

Return the 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.

principal_inertia_vectors

Return the principal axis of inertia.

scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

symmetry

Check whether a mesh has rotational symmetry.

symmetry_axis

If a mesh has rotational symmetry, return the axis.

symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

triangles

Actual triangles of the mesh (points, not indexes)

triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

triangles_cross

The cross product of two edges of each triangle.

triangles_tree

An R-tree containing each face of the mesh.

units

Definition of units for the mesh.

vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

vertex_normals

The vertex normals of the mesh.

vertices

The vertices of the mesh.

volume

Volume of the current mesh calculated using a surface integral.

Methods

apply_obb() Apply the oriented bounding box transform to the current mesh.
apply_scale(scaling) Scale the mesh equally on all axis.
apply_transform(matrix) Apply a transform to the current primitive (sets self.transform)
apply_translation(translation) Translate the current mesh.
compute_stable_poses([center_mass, sigma, …]) Computes stable orientations of a mesh and their quasi-static probabilites.
contains(points) Given a set of points, determine whether or not they are inside the mesh.
convert_units(desired[, guess]) Convert the units of the mesh into a specified unit.
convex_decomposition([engine, maxhulls]) Compute an approximate convex decomposition of a mesh.
copy() Return a copy of the Primitive object.
crc() A zlib.adler32 checksum for the current mesh data.
difference(other[, engine]) Boolean difference between this mesh and n other meshes
eval_cached(statement, *args) Evaluate a statement and cache the result before returning.
export([file_obj, file_type]) Export the current mesh to a file object.
fill_holes() Fill single triangle and single quad holes in the current mesh.
fix_normals(**kwargs) Find and fix problems with self.face_normals and self.faces winding direction.
intersection(other[, engine]) Boolean intersection between this mesh and n other meshes
invert() Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.
md5() An MD5 of the core geometry information for the mesh, faces and vertices.
merge_vertices([distance]) If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.
outline([face_ids]) Given a set of face ids, find the outline of the faces, and return it as a Path3D.
process() Do the bare minimum processing to make a mesh useful.
register(other, **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.
remove_degenerate_faces([height]) Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.
remove_duplicate_faces() On the current mesh remove any faces which are duplicates.
remove_infinite_values() Ensure that every vertex and face consists of finite numbers.
remove_unreferenced_vertices() Remove all vertices in the current mesh which are not referenced by a face.
rezero() Translate the mesh so that all vertex vertices are positive.
sample(count[, return_index]) Return random samples distributed normally across the surface of the mesh
scene(**kwargs) Get a Scene object containing the current mesh.
section(plane_normal, plane_origin) Returns a 3D cross section of the current mesh and a plane defined by origin and normal.
section_multiplane(plane_origin, …) Return multiple parallel cross sections of the current mesh in 2D.
show(**kwargs) Render the mesh in an opengl window.
slice_plane(plane_origin, plane_normal) Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.
smoothed(**kwargs) Return a version of the current mesh which will render nicely.
split(**kwargs) Returns a list of Trimesh objects, based on face connectivity.
subdivide([face_index]) Subdivide a mesh, with each subdivided face replaced with four smaller faces.
submesh(faces_sequence, **kwargs) Return a subset of the mesh.
to_dict() Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:
to_mesh() Return a copy of the Primitive object as a Trimesh object.
union(other[, engine]) Boolean union between this mesh and n other meshes
unmerge_vertices() Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.
update_faces(mask) In many cases, we will want to remove specific faces.
update_vertices(mask[, inverse]) Update vertices with a mask.
voxelized(pitch, **kwargs) Return a Voxel object representing the current mesh discretized into voxels at the specified pitch
direction

The direction of the capsule’s axis.

Returns:
axis: (3,) float, vector along the cylinder axis
class trimesh.primitives.Cylinder(*args, **kwargs)

Bases: trimesh.primitives._Primitive

Attributes:
area

Summed area of all triangles in the current mesh.

area_faces

The area of each face in the mesh.

body_count

How many connected groups of vertices exist in this mesh.

bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

bounds

The axis aligned bounds of the mesh.

center_mass

The point in space which is the center of mass/volume.

centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

density

The density of the mesh.

direction

The direction of the cylinder’s axis.

edges

Edges of the mesh (derived from faces).

edges_face

Which face does each edge belong to.

edges_sorted

Edges sorted along axis 1

edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

edges_unique

The unique edges of the mesh.

edges_unique_length

How long is each unique edge.

euler_number

Return the Euler characteristic (a topological invariant) for the mesh

extents

The length, width, and height of the bounding box of the mesh.

face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

face_adjacency_angles

Return the angle between adjacent faces

face_adjacency_convex

Return faces which are adjacent and locally convex.

face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

face_adjacency_projections

The projection of the non- shared vertex of a triangle onto

face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

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.

face_adjacency_tree

An R-tree of face adjacencies.

face_adjacency_unshared

Return the vertex index of the two vertices not in the shared

face_angles

Returns the angle at each vertex of a face.

face_angles_sparse

A sparse matrix representation of the face angles.

face_normals

Return the unit normal vector for each face.

faces

The faces of the mesh.

faces_sparse

A sparse matrix representation of the faces.

faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

facets

Return a list of face indices for coplanar adjacent faces.

facets_area

Return an array containing the area of each facet.

facets_boundary

Return the edges which represent the boundary of each facet

facets_normal

Return the normal of each facet

facets_on_hull

Find which facets of the mesh are on the convex hull.

facets_origin

Return a point on the facet plane.

identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

identifier_md5

An MD5 of the rotation invariant identifier vector

is_convex

Check if a mesh is convex or not.

is_empty

Does the current mesh have data defined.

is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

is_winding_consistent

Does the mesh have consistent winding or not.

kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh.

mass

Mass of the current mesh, based on specified density and volume.

mass_properties

Returns the mass properties of the current mesh.

moment_inertia

The analytic inertia tensor of the cylinder primitive.

principal_inertia_components

Return the 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.

principal_inertia_vectors

Return the principal axis of inertia.

scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

symmetry

Check whether a mesh has rotational symmetry.

symmetry_axis

If a mesh has rotational symmetry, return the axis.

symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

triangles

Actual triangles of the mesh (points, not indexes)

triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

triangles_cross

The cross product of two edges of each triangle.

triangles_tree

An R-tree containing each face of the mesh.

units

Definition of units for the mesh.

vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

vertex_normals

The vertex normals of the mesh.

vertices

The vertices of the mesh.

volume

The analytic volume of the cylinder primitive.

Methods

apply_obb() Apply the oriented bounding box transform to the current mesh.
apply_scale(scaling) Scale the mesh equally on all axis.
apply_transform(matrix) Apply a transform to the current primitive (sets self.transform)
apply_translation(translation) Translate the current mesh.
compute_stable_poses([center_mass, sigma, …]) Computes stable orientations of a mesh and their quasi-static probabilites.
contains(points) Given a set of points, determine whether or not they are inside the mesh.
convert_units(desired[, guess]) Convert the units of the mesh into a specified unit.
convex_decomposition([engine, maxhulls]) Compute an approximate convex decomposition of a mesh.
copy() Return a copy of the Primitive object.
crc() A zlib.adler32 checksum for the current mesh data.
difference(other[, engine]) Boolean difference between this mesh and n other meshes
eval_cached(statement, *args) Evaluate a statement and cache the result before returning.
export([file_obj, file_type]) Export the current mesh to a file object.
fill_holes() Fill single triangle and single quad holes in the current mesh.
fix_normals(**kwargs) Find and fix problems with self.face_normals and self.faces winding direction.
intersection(other[, engine]) Boolean intersection between this mesh and n other meshes
invert() Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.
md5() An MD5 of the core geometry information for the mesh, faces and vertices.
merge_vertices([distance]) If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.
outline([face_ids]) Given a set of face ids, find the outline of the faces, and return it as a Path3D.
process() Do the bare minimum processing to make a mesh useful.
register(other, **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.
remove_degenerate_faces([height]) Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.
remove_duplicate_faces() On the current mesh remove any faces which are duplicates.
remove_infinite_values() Ensure that every vertex and face consists of finite numbers.
remove_unreferenced_vertices() Remove all vertices in the current mesh which are not referenced by a face.
rezero() Translate the mesh so that all vertex vertices are positive.
sample(count[, return_index]) Return random samples distributed normally across the surface of the mesh
scene(**kwargs) Get a Scene object containing the current mesh.
section(plane_normal, plane_origin) Returns a 3D cross section of the current mesh and a plane defined by origin and normal.
section_multiplane(plane_origin, …) Return multiple parallel cross sections of the current mesh in 2D.
show(**kwargs) Render the mesh in an opengl window.
slice_plane(plane_origin, plane_normal) Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.
smoothed(**kwargs) Return a version of the current mesh which will render nicely.
split(**kwargs) Returns a list of Trimesh objects, based on face connectivity.
subdivide([face_index]) Subdivide a mesh, with each subdivided face replaced with four smaller faces.
submesh(faces_sequence, **kwargs) Return a subset of the mesh.
to_dict() Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:
to_mesh() Return a copy of the Primitive object as a Trimesh object.
union(other[, engine]) Boolean union between this mesh and n other meshes
unmerge_vertices() Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.
update_faces(mask) In many cases, we will want to remove specific faces.
update_vertices(mask[, inverse]) Update vertices with a mask.
voxelized(pitch, **kwargs) Return a Voxel object representing the current mesh discretized into voxels at the specified pitch
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
volume

The analytic volume of the cylinder primitive.

Returns:
volume: float, volume of the cylinder
class trimesh.primitives.Extrusion(*args, **kwargs)

Bases: trimesh.primitives._Primitive

Attributes:
area

The surface area of the primitive extrusion.

area_faces

The area of each face in the mesh.

body_count

How many connected groups of vertices exist in this mesh.

bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

bounds

The axis aligned bounds of the mesh.

center_mass

The point in space which is the center of mass/volume.

centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

density

The density of the mesh.

direction

Based on the extrudes transform, what is the vector along

edges

Edges of the mesh (derived from faces).

edges_face

Which face does each edge belong to.

edges_sorted

Edges sorted along axis 1

edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

edges_unique

The unique edges of the mesh.

edges_unique_length

How long is each unique edge.

euler_number

Return the Euler characteristic (a topological invariant) for the mesh

extents

The length, width, and height of the bounding box of the mesh.

face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

face_adjacency_angles

Return the angle between adjacent faces

face_adjacency_convex

Return faces which are adjacent and locally convex.

face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

face_adjacency_projections

The projection of the non- shared vertex of a triangle onto

face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

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.

face_adjacency_tree

An R-tree of face adjacencies.

face_adjacency_unshared

Return the vertex index of the two vertices not in the shared

face_angles

Returns the angle at each vertex of a face.

face_angles_sparse

A sparse matrix representation of the face angles.

face_normals

Return the unit normal vector for each face.

faces

The faces of the mesh.

faces_sparse

A sparse matrix representation of the faces.

faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

facets

Return a list of face indices for coplanar adjacent faces.

facets_area

Return an array containing the area of each facet.

facets_boundary

Return the edges which represent the boundary of each facet

facets_normal

Return the normal of each facet

facets_on_hull

Find which facets of the mesh are on the convex hull.

facets_origin

Return a point on the facet plane.

identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

identifier_md5

An MD5 of the rotation invariant identifier vector

is_convex

Check if a mesh is convex or not.

is_empty

Does the current mesh have data defined.

is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

is_winding_consistent

Does the mesh have consistent winding or not.

kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh.

mass

Mass of the current mesh, based on specified density and volume.

mass_properties

Returns the mass properties of the current mesh.

moment_inertia

Return the moment of inertia matrix of the current mesh.

principal_inertia_components

Return the 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.

principal_inertia_vectors

Return the principal axis of inertia.

scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

symmetry

Check whether a mesh has rotational symmetry.

symmetry_axis

If a mesh has rotational symmetry, return the axis.

symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

triangles

Actual triangles of the mesh (points, not indexes)

triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

triangles_cross

The cross product of two edges of each triangle.

triangles_tree

An R-tree containing each face of the mesh.

units

Definition of units for the mesh.

vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

vertex_normals

The vertex normals of the mesh.

vertices

The vertices of the mesh.

volume

The volume of the primitive extrusion.

Methods

apply_obb() Apply the oriented bounding box transform to the current mesh.
apply_scale(scaling) Scale the mesh equally on all axis.
apply_transform(matrix) Apply a transform to the current primitive (sets self.transform)
apply_translation(translation) Translate the current mesh.
buffer(distance) Return a new Extrusion object which is expanded in profile and in height by a specified distance.
compute_stable_poses([center_mass, sigma, …]) Computes stable orientations of a mesh and their quasi-static probabilites.
contains(points) Given a set of points, determine whether or not they are inside the mesh.
convert_units(desired[, guess]) Convert the units of the mesh into a specified unit.
convex_decomposition([engine, maxhulls]) Compute an approximate convex decomposition of a mesh.
copy() Return a copy of the Primitive object.
crc() A zlib.adler32 checksum for the current mesh data.
difference(other[, engine]) Boolean difference between this mesh and n other meshes
eval_cached(statement, *args) Evaluate a statement and cache the result before returning.
export([file_obj, file_type]) Export the current mesh to a file object.
fill_holes() Fill single triangle and single quad holes in the current mesh.
fix_normals(**kwargs) Find and fix problems with self.face_normals and self.faces winding direction.
intersection(other[, engine]) Boolean intersection between this mesh and n other meshes
invert() Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.
md5() An MD5 of the core geometry information for the mesh, faces and vertices.
merge_vertices([distance]) If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.
outline([face_ids]) Given a set of face ids, find the outline of the faces, and return it as a Path3D.
process() Do the bare minimum processing to make a mesh useful.
register(other, **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.
remove_degenerate_faces([height]) Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.
remove_duplicate_faces() On the current mesh remove any faces which are duplicates.
remove_infinite_values() Ensure that every vertex and face consists of finite numbers.
remove_unreferenced_vertices() Remove all vertices in the current mesh which are not referenced by a face.
rezero() Translate the mesh so that all vertex vertices are positive.
sample(count[, return_index]) Return random samples distributed normally across the surface of the mesh
scene(**kwargs) Get a Scene object containing the current mesh.
section(plane_normal, plane_origin) Returns a 3D cross section of the current mesh and a plane defined by origin and normal.
section_multiplane(plane_origin, …) Return multiple parallel cross sections of the current mesh in 2D.
show(**kwargs) Render the mesh in an opengl window.
slice_plane(plane_origin, plane_normal) Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.
slide(distance) Alter the transform of the current extrusion to slide it along its extrude_direction vector
smoothed(**kwargs) Return a version of the current mesh which will render nicely.
split(**kwargs) Returns a list of Trimesh objects, based on face connectivity.
subdivide([face_index]) Subdivide a mesh, with each subdivided face replaced with four smaller faces.
submesh(faces_sequence, **kwargs) Return a subset of the mesh.
to_dict() Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:
to_mesh() Return a copy of the Primitive object as a Trimesh object.
union(other[, engine]) Boolean union between this mesh and n other meshes
unmerge_vertices() Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.
update_faces(mask) In many cases, we will want to remove specific faces.
update_vertices(mask[, inverse]) Update vertices with a mask.
voxelized(pitch, **kwargs) Return a Voxel object representing the current mesh discretized into voxels at the specified pitch
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
buffer(distance)

Return a new Extrusion object which is expanded in profile and in height by a specified distance.

Returns:
buffered: Extrusion object
direction

Based on the extrudes transform, what is the vector along which the polygon will be extruded

Returns:
direction: (3,) float vector. If self.primitive.transform is an

identity matrix this will be [0.0, 0.0, 1.0]

slide(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
volume

The volume of the primitive extrusion.

Calculated from polygon and height to avoid mesh creation.

Returns:
volume: float, volume of 3D extrusion
class trimesh.primitives.Sphere(*args, **kwargs)

Bases: trimesh.primitives._Primitive

Attributes:
area

Surface area of the current sphere primitive.

area_faces

The area of each face in the mesh.

body_count

How many connected groups of vertices exist in this mesh.

bounding_box

An axis aligned bounding box for the current mesh.

bounding_box_oriented

An oriented bounding box for the current mesh.

bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

bounding_primitive

The minimum volume primitive (box, sphere, or cylinder) that bounds the mesh.

bounding_sphere

A minimum volume bounding sphere for the current mesh.

bounds

The axis aligned bounds of the mesh.

center_mass

The point in space which is the center of mass/volume.

centroid

The point in space which is the average of the triangle centroids weighted by the area of each triangle.

convex_hull

Get a new Trimesh object representing the convex hull of the current mesh.

density

The density of the mesh.

edges

Edges of the mesh (derived from faces).

edges_face

Which face does each edge belong to.

edges_sorted

Edges sorted along axis 1

edges_sparse

Edges in sparse bool COO graph format where connected vertices are True.

edges_unique

The unique edges of the mesh.

edges_unique_length

How long is each unique edge.

euler_number

Return the Euler characteristic (a topological invariant) for the mesh

extents

The length, width, and height of the bounding box of the mesh.

face_adjacency

Find faces that share an edge, which we call here ‘adjacent’.

face_adjacency_angles

Return the angle between adjacent faces

face_adjacency_convex

Return faces which are adjacent and locally convex.

face_adjacency_edges

Returns the edges that are shared by the adjacent faces.

face_adjacency_projections

The projection of the non- shared vertex of a triangle onto

face_adjacency_radius

The approximate radius of a cylinder that fits inside adjacent faces.

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.

face_adjacency_tree

An R-tree of face adjacencies.

face_adjacency_unshared

Return the vertex index of the two vertices not in the shared

face_angles

Returns the angle at each vertex of a face.

face_angles_sparse

A sparse matrix representation of the face angles.

face_normals

Return the unit normal vector for each face.

faces

The faces of the mesh.

faces_sparse

A sparse matrix representation of the faces.

faces_unique_edges

For each face return which indexes in mesh.unique_edges constructs that face.

facets

Return a list of face indices for coplanar adjacent faces.

facets_area

Return an array containing the area of each facet.

facets_boundary

Return the edges which represent the boundary of each facet

facets_normal

Return the normal of each facet

facets_on_hull

Find which facets of the mesh are on the convex hull.

facets_origin

Return a point on the facet plane.

identifier

Return a float vector which is unique to the mesh and is robust to rotation and translation.

identifier_md5

An MD5 of the rotation invariant identifier vector

is_convex

Check if a mesh is convex or not.

is_empty

Does the current mesh have data defined.

is_volume

Check if a mesh has all the properties required to represent a valid volume, rather than just a surface.

is_watertight

Check if a mesh is watertight by making sure every edge is included in two faces.

is_winding_consistent

Does the mesh have consistent winding or not.

kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh.

mass

Mass of the current mesh, based on specified density and volume.

mass_properties

Returns the mass properties of the current mesh.

moment_inertia

The analytic inertia tensor of the sphere primitive.

principal_inertia_components

Return the 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.

principal_inertia_vectors

Return the principal axis of inertia.

scale

A metric for the overall scale of the mesh, the length of the diagonal of the axis aligned bounding box of the mesh.

symmetry

Check whether a mesh has rotational symmetry.

symmetry_axis

If a mesh has rotational symmetry, return the axis.

symmetry_section

If a mesh has rotational symmetry, return the two vectors which make up a section coordinate frame.

triangles

Actual triangles of the mesh (points, not indexes)

triangles_center

The center of each triangle (barycentric [1/3, 1/3, 1/3])

triangles_cross

The cross product of two edges of each triangle.

triangles_tree

An R-tree containing each face of the mesh.

units

Definition of units for the mesh.

vertex_adjacency_graph

Returns a networkx graph representing the vertices and their connections in the mesh.

vertex_defects

Return the vertex defects, or (2*pi) minus the sum of the angles of every face that includes that vertex.

vertex_neighbors

The vertex neighbors of each vertex of the mesh, determined from the cached vertex_adjacency_graph, if already existent.

vertex_normals

The vertex normals of the mesh.

vertices

The vertices of the mesh.

volume

Volume of the current sphere primitive.

Methods

apply_obb() Apply the oriented bounding box transform to the current mesh.
apply_scale(scaling) Scale the mesh equally on all axis.
apply_transform(matrix) Apply a transform to the sphere primitive
apply_translation(translation) Translate the current mesh.
compute_stable_poses([center_mass, sigma, …]) Computes stable orientations of a mesh and their quasi-static probabilites.
contains(points) Given a set of points, determine whether or not they are inside the mesh.
convert_units(desired[, guess]) Convert the units of the mesh into a specified unit.
convex_decomposition([engine, maxhulls]) Compute an approximate convex decomposition of a mesh.
copy() Return a copy of the Primitive object.
crc() A zlib.adler32 checksum for the current mesh data.
difference(other[, engine]) Boolean difference between this mesh and n other meshes
eval_cached(statement, *args) Evaluate a statement and cache the result before returning.
export([file_obj, file_type]) Export the current mesh to a file object.
fill_holes() Fill single triangle and single quad holes in the current mesh.
fix_normals(**kwargs) Find and fix problems with self.face_normals and self.faces winding direction.
intersection(other[, engine]) Boolean intersection between this mesh and n other meshes
invert() Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache.
md5() An MD5 of the core geometry information for the mesh, faces and vertices.
merge_vertices([distance]) If a mesh has vertices that are closer than trimesh.constants.tol.merge reindex faces to reference the same index for both vertices.
outline([face_ids]) Given a set of face ids, find the outline of the faces, and return it as a Path3D.
process() Do the bare minimum processing to make a mesh useful.
register(other, **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.
remove_degenerate_faces([height]) Remove degenerate faces (faces without 3 unique vertex indices) from the current mesh.
remove_duplicate_faces() On the current mesh remove any faces which are duplicates.
remove_infinite_values() Ensure that every vertex and face consists of finite numbers.
remove_unreferenced_vertices() Remove all vertices in the current mesh which are not referenced by a face.
rezero() Translate the mesh so that all vertex vertices are positive.
sample(count[, return_index]) Return random samples distributed normally across the surface of the mesh
scene(**kwargs) Get a Scene object containing the current mesh.
section(plane_normal, plane_origin) Returns a 3D cross section of the current mesh and a plane defined by origin and normal.
section_multiplane(plane_origin, …) Return multiple parallel cross sections of the current mesh in 2D.
show(**kwargs) Render the mesh in an opengl window.
slice_plane(plane_origin, plane_normal) Returns another mesh that is the current mesh sliced by the plane defined by origin and normal.
smoothed(**kwargs) Return a version of the current mesh which will render nicely.
split(**kwargs) Returns a list of Trimesh objects, based on face connectivity.
subdivide([face_index]) Subdivide a mesh, with each subdivided face replaced with four smaller faces.
submesh(faces_sequence, **kwargs) Return a subset of the mesh.
to_dict() Return a dictionary representation of the current mesh, with keys that can be used as the kwargs for the Trimesh constructor, eg:
to_mesh() Return a copy of the Primitive object as a Trimesh object.
union(other[, engine]) Boolean union between this mesh and n other meshes
unmerge_vertices() Removes all face references so that every face contains three unique vertex indices and no faces are adjacent.
update_faces(mask) In many cases, we will want to remove specific faces.
update_vertices(mask[, inverse]) Update vertices with a mask.
voxelized(pitch, **kwargs) Return a Voxel object representing the current mesh discretized into voxels at the specified pitch
apply_transform(matrix)

Apply a transform to the sphere primitive

Parameters:
matrix: (4,4) float, homogenous transformation
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 mesh.

Returns:
bounds : (2, 3) float

Bounding box with [min, max] coordinates

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

trimesh.proximity module

proximity.py

Query mesh- point proximity.

class trimesh.proximity.ProximityQuery(mesh)

Bases: object

Proximity queries for the current mesh.

Methods

on_surface(**kwargs) Given list of points, for each point find the closest point on any triangle of the mesh.
signed_distance(points) Find the signed distance from a mesh to a list of points.
vertex(points) Given a set of points, return the closest vertex index to each point
on_surface(**kwargs)

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
triangle_id : (m,) int, index of closest triangle for each point
signed_distance(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, list of points in space
Returns:
signed_distance : (n,3) float, signed distance from point to mesh
vertex(points)

Given a set of points, return the closest vertex index to each point

Parameters:
points : (n,3) float, list of points in space
Returns:
distance : (n,) float, distance from source point to vertex
vertex_id : (n,) int, index of mesh.vertices which is closest
trimesh.proximity.closest_point(mesh, points)

Given a mesh and a list of points, find the closest point on any triangle.

Parameters:
mesh : Trimesh object
points : (m,3) float, points in space
Returns:
closest : (m,3) float, closest point on triangles for each point
distance : (m,) float, distance
triangle_id : (m,) int, index of triangle containing closest point
trimesh.proximity.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:
triangles : (n,3,3) float, triangles in space
points : (m,3) float, points in space
Returns:
closest : (m,3) float, closest point on triangles for each point
distance : (m,) float, distance
triangle_id : (m,) int, index of triangle containing closest point
trimesh.proximity.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, list of points in space
directions : (n,3) float, directions of rays
Returns:
signed_distance : (n,) float, length of rays
trimesh.proximity.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, list of points in space
inwards : bool, whether to have the sphere inside or outside the mesh
normals : (n,3) float, normals of the mesh at the given points

None, compute this automatically.

Returns:
centers : (n,3) float, centers of spheres
radii : (n,) float, radii of spheres
trimesh.proximity.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 object
points : (n,3) float , points in space
Returns:
candidates : (points,) int, sequence of indexes for mesh.faces
trimesh.proximity.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 object
points : (n,3) float, list of points in space
Returns:
signed_distance : (n,3) float, signed distance from point to mesh
trimesh.proximity.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, list of 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

None, compute this automatically.

method : string, one of ‘max_sphere’ or ‘ray’
Returns:
thickness : (n,) float, thickness

trimesh.registration module

registration.py

Functions for registering (aligning) point clouds with meshes.

trimesh.registration.icp(a, b, initial=array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]), 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

trimesh.registration.mesh_other(mesh, other, samples=500, scale=False, icp_first=10, icp_final=50)

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

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 squared distance per point

trimesh.registration.procrustes(a, b, reflection=True, translation=True, scale=True, return_cost=True)

Perform Procrustes’ analysis subject to constraints. Finds the transformation T mapping a to b which minimizes the square sum distances between Ta and b, also called the cost.

Parameters:
a : (n,3) float

List of points in space

b : (n,3) float

List of points in space

reflection : bool

If the transformation is allowed reflections

translation : bool

If the transformation is allowed translations

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

trimesh.remesh module

remesh.py

Deal with re- triangulation of existing meshes.

trimesh.remesh.subdivide(vertices, faces, face_index=None)

Subdivide a mesh into smaller triangles.

Parameters:
vertices: (n,3) float, vertices
faces: (n,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 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

Returns:
new_vertices: (n,3) float, vertices
new_faces: (n,3) int, remeshed faces
trimesh.remesh.subdivide_to_size(vertices, faces, max_edge, max_iter=10)

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 subdivisions
Returns:
vertices: (j,3) float, vertices in space
faces: (q,3) int, indices of vertices

trimesh.rendering module

rendering.py

Functions to convert trimesh objects to pyglet/opengl objects.

trimesh.rendering.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

trimesh.rendering.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.

trimesh.rendering.matrix_to_gl(matrix)

Convert a numpy row- major homogenous transformation matrix to a flat column- major GLfloat transformation.

Parameters:
matrix : (4,4) float

Row- major homogenous transform

Returns:
glmatrix : (16,) pyglet.gl.GLfloat

Transform in pyglet format

trimesh.rendering.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

trimesh.rendering.path_to_vertexlist(path, group=None, colors=None, **kwargs)

Convert a Path3D object to arguments for an 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

trimesh.rendering.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

trimesh.rendering.vector_to_gl(array, *args)

Convert an array and an optional set of args into a flat vector of pyglet.gl.GLfloat

trimesh.repair module

repair.py

Fill holes and fix winding and normals of meshes.

trimesh.repair.broken_faces(mesh, color=None)

Return the index of faces in the mesh which break the watertight status of the mesh.

Parameters:
mesh: Trimesh object
color: (4,) uint8, will set broken faces to this color

None, will not alter mesh colors

Returns:
broken: (n, ) int, indexes of mesh.faces
trimesh.repair.fill_holes(mesh)

Fill single- triangle holes on triangular meshes by adding new triangles to fill the holes. New triangles will have proper winding and normals, and if face colors exist the color of the last face will be assigned to the new triangles.

mesh: Trimesh object

trimesh.repair.fix_inversion(mesh, multibody=False)

Check to see if a mesh has normals pointing “out.”

Parameters:
mesh: Trimesh object
multibody: bool, if True will try to fix normals on every body
trimesh.repair.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 object
multibody: bool, if True try to correct normals direction

on every body.

trimesh.repair.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 object

trimesh.sample module

sample.py

Randomly sample surface and volume of meshes.

trimesh.sample.sample_surface(mesh, count)

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

mesh: Trimesh object count: number of points to return

Returns:
samples: (count,3) points in space on the surface of mesh
face_index: (count,) indices of faces for each sampled point
trimesh.sample.sample_surface_even(mesh, count)

Sample the surface of a mesh, returning samples which are approximately evenly spaced.

mesh: Trimesh object count: number of points to return

Returns:
samples: (count,3) points in space on the surface of mesh
face_index: (count,) indices of faces for each sampled point
trimesh.sample.sample_surface_sphere(count)

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, list of random points on a unit sphere
trimesh.sample.volume_mesh(mesh, count)

Use rejection sampling to produce points randomly distributed in the volume of a mesh.

Parameters:
mesh: Trimesh object
count: int, number of samples desired
Returns:
samples: (n,3) float, points in the volume of the mesh.

where: n <= count

trimesh.sample.volume_rectangular(extents, count, transform=None)

Return random samples inside a rectangular volume.

Parameters:
extents: (3,) float, side lengths of rectangular solid
count: int, number of points to return
transform: (4,4) float, transformation matrix
Returns:
samples: (count, 3) float, points in volume

trimesh.transformations module

Homogeneous Transformation Matrices and Quaternions.

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
Organization:Laboratory for Fluorescence Dynamics, University of California, Irvine
Version:2017.02.17

Requirements

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:

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, math.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

trimesh.triangles module

triangles.py

Functions for dealing with triangle soups in (n, 3, 3) float form.

trimesh.triangles.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
trimesh.triangles.any_coplanar(triangles)

Given a list of triangles, if the FIRST triangle is coplanar with ANY of the following triangles, return True. Otherwise, return False.

trimesh.triangles.area(triangles=None, crosses=None, sum=False)

Calculates the sum area of input triangles

Parameters:
triangles: vertices of triangles (n,3,3)
sum: bool, return summed area or individual triangle area
Returns:
area:

if sum: float, sum area of triangles else: (n,) float, individual area of triangles

trimesh.triangles.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, list of triangles in space
barycentric: (n,2) float, barycentric coordinates
Returns:
points: (m,3) float, points in space
trimesh.triangles.bounds_tree(triangles)

Given a list of triangles, create an r-tree for broad- phase collision detection

triangles: (n, 3, 3) list of vertices

Returns:
tree: Rtree object
trimesh.triangles.closest_point(triangles, points)

Return the closest point on the surface of each triangle for a list of corresponding points.

Parameters:
triangles: (n,3,3) float, triangles in space
points: (n,3) float, points in space
Returns:
closest: (n,3) float, point on each triangle closest to each point
trimesh.triangles.cross(triangles)

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
trimesh.triangles.extents(triangles, areas=None)

Return the 2D bounding box size of each triangle.

Parameters:
triangles: (n, 3, 3) float, list of triangles
areas: (n,) float, list of triangles area
Returns:
box: (n,2) float, the size of the 2D oriented bounding box.
trimesh.triangles.mass_properties(triangles, crosses=None, density=1.0, center_mass=None, skip_inertia=False)

Calculate the mass properties of a group of triangles.

Implemented from: http://www.geometrictools.com/Documentation/PolyhedralMassProperties.pdf

Parameters:
triangles: (n,3,3) float, triangles in space
crosses: (n,) float, 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
trimesh.triangles.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, list of triangles
height: float, minimum edge of a triangle to be kept
Returns:
nondegenerate: (n,) bool array of triangles that have area
trimesh.triangles.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, valid
trimesh.triangles.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,3) float, triangles in space
points: (n,3) float, point in space associated with a triangle
method: str, which method to compute the barycentric coordinates with. Options:
-‘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
trimesh.triangles.to_kwargs(triangles)

Convert a list of triangles to the kwargs for the Trimesh constructor.

triangles: (n,3,3) float, triangles in space

Returns:
kwargs: dict, with keys:

‘vertices’ : (n,3) float ‘faces’ : (m,3) int

Examples

mesh = trimesh.Trimesh(**trimesh.triangles.to_kwargs(triangles))

trimesh.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) list of vertex locations
normals_compare: (n,3) list of normals
Returns:
aligned: (n) bool list, are normals aligned with triangles

trimesh.units module

units.py

Deal with physical unit systems (i.e. inches, mm)

Very basic conversions, and no requirement for sympy.physics.units or pint.

trimesh.units.unit_conversion(current, desired)

Calculate the conversion from one set of units to another.

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

trimesh.units.units_from_metadata(obj, guess=True)

Try to extract hints from metadata and if that fails guess based on the object scale.

Parameters:
obj: object

Has attributes ‘metadata’ (dict) and ‘scale’ (float)

guess : bool

If metadata doesn’t indicate units, guess from scale

Returns:
units: str

A guess of what the units might be

trimesh.util module

util.py

Standalone functions which require only imports from numpy and the standard library.

Other libraries may be imported must be wrapped in try/except blocks or imported inside of a function

trimesh.util.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

trimesh.util.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

trimesh.util.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

trimesh.util.attach_to_log(level=10, handler=None, loggers=None, colors=True, blacklist=['TerminalIPythonApp', 'PYREADLINE', 'pyembree', 'shapely.geos', 'shapely.speedups._speedups'])

Attach a stream handler to all loggers.

Parameters:
level: logging level
handler: log handler object
loggers: list of loggers to attach to

if None, will try to attach to all available

colors: bool, if True try to use colorlog formatter
blacklist: list of str, names of loggers NOT to attach to
trimesh.util.bounds_tree(bounds)

Given a set of axis aligned bounds, create an r-tree for broad- phase collision detection

bounds: (n, dimension*2) list of non- interleaved bounds
for a 2D bounds tree: [(minx, miny, maxx, maxy), …]
Returns:
tree: Rtree object
trimesh.util.compress(info)

Compress data stored in a dict.

Parameters:
info: dict, {name in archive: bytes or file-like object}
Returns:
compressed: bytes
trimesh.util.concatenate(a, b=None)

Concatenate two or more meshes.

Parameters:
a: Trimesh object, or list of such
b: Trimesh object, or list of such
Returns:
result: Trimesh object containing concatenated mesh
trimesh.util.convert_like(item, like)

Convert an item to have the dtype of another item

Parameters:
item: item to be converted
like: object with target dtype. If None, item is returned unmodified
Returns:
result: item, but in dtype of like
trimesh.util.decimal_to_digits(decimal, min_digits=None)

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
trimesh.util.decode_keys(store, encoding='utf-8')

If a dictionary has keys that are bytes decode them to a str.

store : dict
Dictionary with data
Returns:
result : dict

Values are untouched but keys that were bytes are converted to ASCII strings.

trimesh.util.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: open file object
file_type: str, file extension, ‘zip’, ‘tar.gz’, etc
Returns:
decompressed: dict:

{(str, file name) : (file-like object)}

trimesh.util.diagonal_dot(a, b)

Dot product by row of a and b.

Same as np.diag(np.dot(a, b.T)) but without the monstrous intermediate matrix.

Also equivalent to: np.einsum(‘ij,ij->i’, a, b)

Parameters:
a: (m, d) array
b: (m, d) array
Returns:
result: (m, d) array
trimesh.util.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
trimesh.util.encoded_to_array(encoded)

Turn a dictionary with base64 encoded strings back into a numpy array.

Parameters:
encoded : dict
Has keys:

dtype: string of dtype shape: int tuple of shape base64: base64 encoded string of flat array binary: decode result coming from numpy.tostring

Returns:
array: numpy array
trimesh.util.euclidean(a, b)

Euclidean distance between vectors a and b.

Parameters:
a : (n,) float

First vector

b : (n,) float

Second vector

Returns:
distance : float

Euclidean distance between A and B

trimesh.util.generate_basis(z)

Generate an arbitrary basis (coordinate frame) from the given z-axis.

Parameters:
z: (3,) float, a positive z-axis vector.
Returns:
x: (3,) float, the x axis
y: (3,) float, the y axis
z: (3,) float, the z axis
trimesh.util.grid_arange(bounds, step)

Return a grid from an (2,dimension) bounds with samples step distance apart.

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
trimesh.util.grid_linspace(bounds, count)

Return a grid spaced inside a bounding box with edges spaced using np.linspace.

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
trimesh.util.hash_file(file_obj, hash_function=<built-in function openssl_md5>)

Get the hash of an open file- like object.

file_obj: file like object hash_function: function to use to hash data

Returns:
hashed: str, hex version of result
trimesh.util.is_binary_file(file_obj)

Returns True if file has non-ASCII characters (> 0x7F, or 127) Should work in both Python 2 and 3

trimesh.util.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

trimesh.util.is_instance_named(obj, name)

Given an object, if it is a member of the class ‘name’, or a subclass of ‘name’, return True.

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

trimesh.util.is_none(obj)

Check to see if an object is None or not.

Handles the case of np.array(None) as well.

Parameters:
obj : object

Any object type to be checked

Returns:
is_none : bool

True if obj is None or numpy None-like

trimesh.util.is_sequence(obj)

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

trimesh.util.is_shape(obj, shape)

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.

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
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

trimesh.util.is_string(obj)

Check if an object is a string.

Parameters:
obj : object

Any object type to be checked

Returns:
is_string : bool

True if obj is a string

trimesh.util.jsonify(obj, **kwargs)

A version of json.dumps that can handle numpy arrays by creating a custom encoder for numpy dtypes.

Parameters:
obj : JSON- serializable blob
**kwargs :

Passed to json.dumps

Returns:
dumped: str, JSON dump of obj
trimesh.util.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

trimesh.util.md5_object(obj)

If an object is hashable, return the string of the MD5.

Parameters:
obj: object
Returns:
md5: str, MD5 hash
trimesh.util.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)
trimesh.util.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

trimesh.util.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

trimesh.util.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: values, but 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

trimesh.util.spherical_to_vector(spherical)

Convert a set of (n,2) spherical vectors to (n,3) vectors

Parameters:
spherical : (n , 2) float

Angles, in radians

Returns:
vectors : (n, 3) float

Unit vectors

trimesh.util.split_extension(file_name, special=['tar.bz2', 'tar.gz'])

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 charecters after a period, or

a value from ‘special’

trimesh.util.stack_lines(indices)

Stack a list of values that represent a polyline into individual line segments with duplicated consecutive values.

Parameters:
indices: sequence of items
Returns:
stacked: (n,2) set of items
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]])

trimesh.util.submesh(mesh, faces_sequence, only_watertight=False, append=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

only_watertight : bool

Only return submeshes which are watertight.

append : bool

Return a single mesh which has the faces appended, if this flag is set, only_watertight is ignored

Returns:
if append : Trimesh object
else list of Trimesh objects
trimesh.util.three_dimensionalize(points, return_2D=True)

Given a set of (n,2) or (n,3) points, return them as (n,3) points

Parameters:
points: (n, 2) or (n,3) points
return_2D: boolean flag
Returns:
if return_2D:

is_2D: boolean, True if points were (n,2) points: (n,3) set of points

else:

points: (n,3) set of points

trimesh.util.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

trimesh.util.triangle_strips_to_faces(strips)

Given a sequence of triangle strips, convert them 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
trimesh.util.type_bases(obj, depth=4)

Return the bases of the object passed.

trimesh.util.type_named(obj, name)

Similar to the type() builtin, but looks in class bases for named instance.

Parameters:
obj: object to look for class of
name : str, name of class
Returns:
named class, or None
trimesh.util.unique_id(length=12, increment=0)

Generate a decent looking alphanumeric unique identifier. First 16 bits are time- incrementing, followed by randomness.

This function is used as a nicer looking alternative to: >>> uuid.uuid4().hex

Follows the advice in: https://eager.io/blog/how-long-does-an-id-need-to-be/

Parameters:
length: int, length of resulting identifier
increment: int, number to add to header uint16

useful if calling this function repeatedly in a tight loop executing faster than time can increment the header

Returns
————
unique: str, unique alphanumeric identifier
trimesh.util.unitize(vectors, check_valid=False, threshold=None)

Unitize a vector or an array or row- vectors.

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.util.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
trimesh.util.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

trimesh.util.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.

trimesh.util.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
trimesh.util.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 and write

Parameters:
file_obj: file object, with ‘write’ and ‘mode’
stuff: str or bytes, stuff to be written
encoding: str, encoding of text
trimesh.util.zero_pad(data, count, right=True)

data: (n) length 1D array count: int

Returns:
padded: (count) length 1D array if (n < count), otherwise length (n)

trimesh.version module

trimesh.visual module

visual.py

Hold and deal with visual information about meshes.

There are lots of ways to encode visual information, and the goal of this architecture is to make it possible to define one, and then transparently get the others. The two general categories are:

  1. colors, defined for a face, vertex, or material
  2. textures, defined as an image and UV coordinates for each vertex

This module only implements diffuse colors at the moment.

Rules

  1. If nothing is defined sane defaults should be returned

  2. If a user alters or sets a value, that is considered user data and should be saved and treated as such.

  3. Only one mode of visual is allowed at a time, and setting or altering a value should transparently change the mode. Color modes are:

    • vertex colors
    • face colors
class trimesh.visual.ColorVisuals(mesh=None, face_colors=None, vertex_colors=None, **kwargs)

Bases: object

Store color information about a mesh.

Attributes:
defined

Are any colors defined for the current mesh.

face_colors

Colors defined for each face of a mesh.

kind

What color mode has been set.

main_color

What is the most commonly occurring color.

transparency

Does the current object contain any transparency.

vertex_colors

Return the colors for each vertex of a mesh

Methods

concatenate(other, *args) Concatenate two or more ColorVisuals objects into a single object.
crc() A checksum for the current visual object and its parent mesh.
face_subset(face_index) Given a mask of face indices, return a sliced version.
update_faces(mask) Apply a mask to remove or duplicate face properties
update_vertices(mask) Apply a mask to remove or duplicate vertex properties.
concatenate(other, *args)

Concatenate two or more ColorVisuals objects into a single object.

Parameters:
other: ColorVisuals object
*args: ColorVisuals objects
Returns:
result: ColorVisuals object containing information from current

object and others in the order it was passed.

crc()

A checksum for the current visual object and its parent mesh.

Returns:
crc: int, checksum of data in visual object and its parent mesh
defined

Are any colors defined for the current mesh.

Returns:
defined: bool, are colors defined or not.
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
face_subset(face_index)

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.
kind

What color mode has been set.

Returns:
mode: ‘face’, ‘vertex’, or 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
update_faces(mask)

Apply a mask to remove or duplicate face properties

update_vertices(mask)

Apply a mask to remove or duplicate vertex properties.

vertex_colors

Return the colors for each vertex of a mesh

Returns:
colors: (len(mesh.vertices), 4) uint8, color for each vertex
trimesh.visual.colors_to_materials(colors, count=None)

Convert a list of colors into a list of unique materials and material indexes.

Parameters:
colors: (n,(3,4)) colors
count: int, number of entities to apply color to
Returns:
diffuse: (m,4) int, colors
index: (count,) int, index of each color
trimesh.visual.concatenate_visuals(visuals, *args)

Concatenate multiple visual objects.

Parameters:
visuals: ColorVisuals object, or list of same
*args: ColorVisuals object, or list of same
Returns:
concat: ColorVisuals object
trimesh.visual.create_visual(**kwargs)

Create Visuals object from keyword arguments.

Parameters:
face_colors : (n,3|4) uint8, colors
vertex_colors : (n,3|4) uint8, colors
mesh: Trimesh object
Returns:
visuals: ColorVisuals object.
trimesh.visual.face_to_vertex_color(mesh, face_colors, dtype=<class 'numpy.uint8'>)

Convert a list of face colors into a list of vertex colors.

Parameters:
mesh: Trimesh object
face_colors: (n, (3,4)) int, face colors
dtype: data type of output
Returns:
vertex_colors: (m,4) dtype, colors for each vertex
trimesh.visual.hex_to_rgba(color)

Turn a string hex color to a (4,) RGBA color.

Parameters:
color: str, hex color
Returns:
rgba: (4,) np.uint8, RGBA color
trimesh.visual.random_color(dtype=<class 'numpy.uint8'>)

Return a random RGB color using datatype specified.

Parameters:
dtype: numpy dtype of result
Returns:
color: (4,) dtype, random color that looks OK
trimesh.visual.to_rgba(colors, dtype=<class 'numpy.uint8'>)

Convert a single or multiple RGB colors to RGBA colors.

Parameters:
colors: (n,[3|4]) list of RGB or RGBA colors
Returns:
colors: (n,4) list of RGBA colors

(4,) single RGBA color

trimesh.visual.vertex_to_face_color(vertex_colors, faces)

Convert a list of vertex colors to face colors.

Parameters:
vertex_colors: (n,(3,4)), colors
faces: (m,3) int, face indexes
Returns:
face_colors: (m,4) colors

trimesh.voxel module

voxel.py

Convert meshes to a simple voxel data structure and back again.

class trimesh.voxel.Voxel(*args, **kwargs)

Bases: object

Attributes:
filled_count

Return the number of voxels that are occupied.

marching_cubes

A marching cubes Trimesh representation of the voxels.

pitch
points

The center of each filled cell as a list of points.

shape

The shape of the matrix for the current voxel object.

volume

What is the volume of the filled cells in the current voxel object.

Methods

is_filled(point) Query a point to see if the voxel cell it lies in is filled or not.
point_to_index(point) Convert a point to an index in the matrix array.
filled_count

Return the number of voxels that are occupied.

Returns:
filled: int, number of voxels that are occupied
is_filled(point)

Query a point to see if the voxel cell it lies in is filled or not.

Parameters:
point: (3,) float, point in space
Returns:
is_filled: bool, is cell occupied or not
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.matrix.

Returns:
meshed: Trimesh object representing the current voxel

object, as returned by marching cubes algorithm.

pitch
point_to_index(point)

Convert a point to an index in the matrix array.

Parameters:
point: (3,) float, point in space
Returns:
index: (3,) int tuple, index in self.matrix
points

The center of each filled cell as a list of points.

Returns:
points: (self.filled, 3) float, list of points
shape

The shape of the matrix for the current voxel object.

Returns:
shape: (3,) int, what is the shape of the 3D matrix

for these voxels

volume

What is the volume of the filled cells in the current voxel object.

Returns:
volume: float, volume of filled cells
class trimesh.voxel.VoxelMesh(mesh, pitch, max_iter=10, size_max=None, method='subdivide')

Bases: trimesh.voxel.Voxel

Attributes:
filled_count

Return the number of voxels that are occupied.

marching_cubes

A marching cubes Trimesh representation of the voxels.

matrix

A matrix representation of the surface voxels.

matrix_solid

The voxels in a mesh as a 3D matrix.

matrix_surface

The voxels on the surface of the mesh as a 3D matrix.

origin

The origin of the voxel array.

pitch
points

The center of each filled cell as a list of points.

shape

The shape of the matrix for the current voxel object.

sparse_solid

Filled cells inside and on the surface of mesh

sparse_surface

Filled cells on the surface of the mesh.

volume

What is the volume of the filled cells in the current voxel object.

Methods

as_boxes([solid]) A rough Trimesh representation of the voxels with a box for each filled voxel.
is_filled(point) Query a point to see if the voxel cell it lies in is filled or not.
point_to_index(point) Convert a point to an index in the matrix array.
show([solid]) Convert the current set of voxels into a trimesh for visualization and show that via its built- in preview method.
as_boxes(solid=False)

A rough Trimesh representation of the voxels with a box for each filled voxel.

Parameters:
solid: bool, if True return boxes for sparse_solid
Returns:
mesh: Trimesh object made up of one box per filled cell.
matrix

A matrix representation of the surface voxels.

In the future this is planned to return a filled voxel matrix if the source mesh is watertight, and a surface voxelization otherwise.

Returns:
matrix: self.shape np.bool, cell occupancy
matrix_solid

The voxels in a mesh as a 3D matrix.

Returns:
matrix: self.shape np.bool, if a cell is True it is occupied
matrix_surface

The voxels on the surface of the mesh as a 3D matrix.

Returns:
matrix: self.shape np.bool, if a cell is True it is occupied
origin

The origin of the voxel array.

Returns:
origin: (3,) float, point in space
show(solid=False)

Convert the current set of voxels into a trimesh for visualization and show that via its built- in preview method.

sparse_solid

Filled cells inside and on the surface of mesh

Returns:
filled: (n, 3) int, filled cells in or on mesh.
sparse_surface

Filled cells on the surface of the mesh.

Returns:
voxels: (n, 3) int, filled cells on mesh surface
trimesh.voxel.boolean_sparse(a, b, operation=<ufunc 'logical_and'>)

Find common rows between two arrays very quickly using 3D boolean sparse matrices.

Parameters:
a: (n, d) int, coordinates in space
b: (m, d) int, coordinates in space
operation: numpy operation function, ie:

np.logical_and np.logical_or

Returns:
coords: (q, d) int, coordinates in space
trimesh.voxel.fill_voxelization(occupied)

Given a sparse surface voxelization, fill in between columns.

Parameters:
occupied: (n, 3) int, location of filled cells
Returns:
filled: (m, 3) int, location of filled cells
trimesh.voxel.local_voxelize(mesh, point, pitch, radius, fill=True, **kwargs)

Voxelize a mesh in the region of a cube around a point. When fill=True, uses proximity.contains to fill the resulting voxels so may be meaningless for non-watertight meshes. Useful to reduce memory cost for small values of pitch as opposed to global voxelization.

Parameters:
mesh : trimesh.Trimesh

Source geometry

point : (3, ) float

Point in space to voxelize around

pitch : float

Side length of a single voxel cube

radius : int

Number of voxel cubes to return in each direction.

kwargs : parameters to pass to voxelize_subdivide
Returns:
voxels : (m, m, m) bool

Array of local voxels where m=2*radius+1

origin_position : (3,) float

Position of the voxel grid origin in space

trimesh.voxel.matrix_to_marching_cubes(matrix, pitch, origin)

Convert an (n,m,p) matrix into a mesh, using marching_cubes.

Parameters:
matrix: (n,m,p) bool, voxel matrix
pitch: float, what pitch was the voxel matrix computed with
origin: (3,) float, what is the origin of the voxel matrix
Returns:
mesh: Trimesh object, generated by meshing voxels using

the marching cubes algorithm in skimage

trimesh.voxel.matrix_to_points(matrix, pitch, origin)

Convert an (n,m,p) matrix into a set of points for each voxel center.

Parameters:
matrix: (n,m,p) bool, voxel matrix
pitch: float, what pitch was the voxel matrix computed with
origin: (3,) float, what is the origin of the voxel matrix
Returns:
points: (q, 3) list of points
trimesh.voxel.multibox(centers, pitch)

Return a Trimesh object with a box at every center.

Doesn’t do anything nice or fancy.

Parameters:
centers: (n,3) float, center of boxes that are occupied
pitch: float, the edge length of a voxel
Returns:
rough: Trimesh object representing inputs
trimesh.voxel.sparse_to_matrix(sparse)

Take a sparse (n,3) list of integer indexes of filled cells, turn it into a dense (m,o,p) matrix.

Parameters:
sparse: (n,3) int, index of filled cells
Returns:
dense: (m,o,p) bool, matrix of filled cells

Module contents

https://github.com/mikedh/trimesh

Trimesh is a pure Python (2.7- 3.3+) library for loading and using triangular meshes with an emphasis on watertight meshes. The goal of the library is to provide a fully featured Trimesh object which allows for easy manipulation and analysis, in the style of the Polygon object in the Shapely library.