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, face_attributes=None, vertex_attributes=None, metadata=None, process=True, validate=False, use_embree=True, initial_cache=None, visual=None, **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 faces 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_inverse

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

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.

referenced_vertices

Which vertices in the current mesh are referenced by a face.

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_faces

A representation of the face indices that correspond to each 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.

visual

Get the stored visuals for the current 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([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([digits, textured])

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 list of face indexes find the outline of those 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, **kwargs)

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, without changing source mesh.

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

property area

Summed area of all triangles in the current mesh.

Returns
areafloat

Surface area of mesh

property area_faces

The area of each face in the mesh.

Returns
area_faces(n,) float

Area of each face

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

Number of connected vertex groups

property bounds

The axis aligned bounds of the faces of the mesh.

Returns
bounds(2, 3) float

Bounding box with [min, max] coordinates

property 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

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

sigmafloat

The covariance for the multivariate gaussian used to sample center of mass locations

n_samplesint

The number of samples of the center of mass location

thresholdfloat

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
desiredstring

Units to convert to (eg ‘inches’)

guessboolean

If self.units are not defined should we guess the current units of the document and then convert?

convex_decomposition(maxhulls=20, **kwargs)

Compute an approximate convex decomposition of a mesh.

testVHACD Parameters which can be passed as kwargs:

Parameters
maxhullsint

Maximum number of convex hulls to return

**kwargstestVHACD keyword arguments
Returns
mesheslist of trimesh.Trimesh

List of convex meshes that approximate the original

property convex_hull

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

Returns
convextrimesh.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
copiedtrimesh.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
crcint

Checksum of current mesh data

property density

The density of the mesh.

Returns
densityfloat

The density of the mesh.

difference(other, engine=None)

Boolean difference between this mesh and n other meshes

othertrimesh.Trimesh, or list of trimesh.Trimesh objects

Meshes to difference

Returns
differencetrimesh.Trimesh

Difference between self and other Trimesh objects

property edges

Edges of the mesh (derived from faces).

Returns
edges(n, 2) int

List of vertex indices making up edges

property edges_face

Which face does each edge belong to.

Returns
edges_face(n,) int

Index of self.faces

property edges_sorted

Edges sorted along axis 1

Returns
edges_sorted(n, 2)

Same as self.edges but sorted along axis 1

property 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

property edges_unique

The unique edges of the mesh.

Returns
edges_unique(n, 2) int

Vertex indices for unique edges

property edges_unique_inverse

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

Useful for referencing edge properties: mesh.edges_unique[mesh.edges_unique_inverse] == m.edges_sorted

Returns
inverse(len(self.edges),) int

Indexes of self.edges_unique

property edges_unique_length

How long is each unique edge.

Returns
length(len(self.edges_unique), ) float

Length of each unique edge

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

Topological invariant

eval_cached(statement, *args)

Evaluate a statement and cache the result before returning.

Statements are evaluated inside the Trimesh object, and

Parameters
statementstr

Statement of valid python code

*argslist

Available inside statement as args[0], etc

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

property extents

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

Returns
extents(3,) float

Array containing axis aligned [length, width, height]

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

property 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

property 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

property 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

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

property 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

property 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

property face_adjacency_tree

An R-tree of face adjacencies.

Returns
tree: rtree.index

Where each edge in self.face_adjacency has a rectangular cell

property 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

property face_angles

Returns the angle at each vertex of a face.

Returns
angles(n, 3) float

Angle at each vertex of a face

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

property 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

property 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

property faces_sparse

A sparse matrix representation of the faces.

Returns
sparsescipy.sparse.coo_matrix

Has properties: dtype : bool shape : (len(self.vertices), len(self.faces))

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

property facets

Return a list of face indices for coplanar adjacent faces.

Returns
facets(n, ) sequence of (m,) int

Groups of indexes of self.faces

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

property facets_boundary

Return the edges which represent the boundary of each facet

Returns
edges_boundarysequence of (n, 2) int

Indices of self.vertices

property facets_normal

Return the normal of each facet

Returns
normals: (len(self.facets), 3) float

A unit normal vector for each facet

property 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

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

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
multibodyNone or bool

Fix normals across multiple bodies if None automatically pick from body_count

property 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

property identifier_md5

An MD5 of the rotation invariant identifier vector

Returns
hashedstr

MD5 hash of the identifier vector

intersection(other, engine=None)

Boolean intersection between this mesh and n other meshes

othertrimesh.Trimesh, or list of trimesh.Trimesh objects

Meshes to calculate intersections with

Returns
intersectiontrimesh.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.

property is_convex

Check if a mesh is convex or not.

Returns
is_convex: bool

Is mesh convex or not

property is_empty

Does the current mesh have data defined.

Returns
emptybool

If True, no data is set on the current mesh

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

Does the mesh represent a volume

property is_watertight

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

Returns
is_watertightbool

Is mesh watertight or not

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

Is winding is consistent or not

property kdtree

Return a scipy.spatial.cKDTree of the vertices of the mesh. Not cached as this lead to observed memory issues and segfaults.

Returns
treescipy.spatial.cKDTree

Contains mesh.vertices

property mass

Mass of the current mesh, based on specified density and volume. If the current mesh isn’t watertight this is garbage.

Returns
massfloat

Mass of the current mesh

property mass_properties

Returns the mass properties of the current mesh.

Assumes uniform density, and result is probably garbage if mesh isn’t watertight.

Returns
propertiesdict

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
md5string

MD5 of everything in the DataStore

merge_vertices(digits=None, textured=True)

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

Parameters
digitsint

If specified overrides tol.merge

texturedbool

If True avoids merging vertices with different UV coordinates. No effect on untextured meshes.

property 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 list of face indexes find the outline of those faces and return it as a Path3D.

The outline is defined here as every edge which is only included by a single triangle.

Note that this implies a non-watertight mesh as the outline of a watertight mesh is an empty path.

Parameters
face_ids(n,) int

Indices to compute the outline of. If None, outline of full mesh will be computed.

**kwargs: passed to Path3D constructor
Returns
pathPath3D

Curve in 3D of the outline

property principal_inertia_components

Return the principal components of inertia

Ordering corresponds to mesh.principal_inertia_vectors

Returns
components(3,) float

Principal components of inertia

property 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

property 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

property referenced_vertices

Which vertices in the current mesh are referenced by a face.

Returns
referenced(len(self.vertices),) bool

Which vertices are referenced by a face

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

Mesh to align with other

othertrimesh.Trimesh or (n, 3) float

Mesh or points in space

samplesint

Number of samples from mesh surface to align

icp_firstint

How many ICP iterations for the 9 possible combinations of

icp_finalint

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

costfloat

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
heightfloat

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

countint

Number of points to sample

return_indexbool

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

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

The length of the meshes AABB diagonal

scene(**kwargs)

Get a Scene object containing the current mesh.

Returns
scenetrimesh.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
smoothbool

Run smooth shading on mesh or not, large meshes will be slow

Returns
scenetrimesh.scene.Scene

Scene with current mesh in it

slice_plane(plane_origin, plane_normal, **kwargs)

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, without changing source mesh.

Parameters
anglefloat

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

Returns
smoothedtrimesh.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_watertightbool

Only return watertight meshes and discard remainder

adjacencyNone 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_sequencesequence (m,) int

Face indices of mesh

only_watertightbool

Only return submeshes which are watertight

appendbool

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

Returns
if appendtrimesh.Trimesh object
elselist of trimesh.Trimesh objects
property symmetry

Check whether a mesh has rotational symmetry.

Returns
symmetry: None No rotational symmetry

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

property 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

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

With keys that match trimesh constructor

property triangles

Actual triangles of the mesh (points, not indexes)

Returns
triangles(n, 3, 3) float

Points of triangle vertices

property 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

property triangles_cross

The cross product of two edges of each triangle.

Returns
crosses(n, 3) float

Cross product of each triangle

property triangles_tree

An R-tree containing each face of the mesh.

Returns
treertree.index

Each triangle in self.faces has a rectangular cell

union(other, engine=None)

Boolean union between this mesh and n other meshes

othertrimesh.Trimesh, or list of trimesh.Trimesh objects

Other meshes to union

Returns
uniontrimesh.Trimesh

Union of self and other Trimesh objects

property units

Definition of units for the mesh.

Returns
unitsstr

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

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

property 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

property vertex_faces

A representation of the face indices that correspond to each vertex.

Returns
vertex_faces(n,m) int

Each row contains the face indices that correspond to the given vertex, padded with -1 up to the max number of faces corresponding to any one vertex Where n == len(self.vertices), m == max number of faces for a single vertex

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

property 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

property visual

Get the stored visuals for the current mesh.

Returns
visualColorVisuals or TextureVisuals

Contains visual information about the mesh

property volume

Volume of the current mesh calculated using a surface integral. If the current mesh isn’t watertight this is garbage.

Returns
volumefloat

Volume of the current mesh

voxelized(pitch, **kwargs)

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

Parameters
pitchfloat

The edge length of a single voxel

Returns
voxelizedVoxel object

Representing the current mesh

trimesh.boolean module

boolean.py

Do boolean operations on meshes using either Blender or OpenSCAD.

trimesh.boolean.boolean_automatic(meshes, operation)

Automatically pick an engine for booleans based on availability.

Parameters
mesheslist of Trimesh

Meshes to be booleaned

operationstr

Type of boolean, i.e. ‘union’, ‘intersection’, ‘difference’

Returns
resulttrimesh.Trimesh

Result of boolean operation

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

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

Parameters
mesheslist of trimesh.Trimesh

Meshes to be processed

enginestr

Which backend to use, i.e. ‘blender’ or ‘scad’

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

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

Parameters
mesheslist of trimesh.Trimesh

Meshes to be processed

enginestr

Which backend to use, i.e. ‘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
mesheslist of trimesh.Trimesh

Meshes to be processed

enginestr

Which backend to use, i.e. ‘blender’ or ‘scad’

Returns
uniona + (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=6, angle_tol=0.001)

Find the approximate minimum volume cylinder which contains a mesh or a a list of points.

Samples a hemisphere then uses scipy.optimize to pick the final orientation of the cylinder.

A nice discussion about better ways to implement this is here: https://www.staff.uni-mainz.de/schoemer/publications/ALGO00.pdf

Parameters
objtrimesh.Trimesh, or (n, 3) float

Mesh object or points in space

sample_countint

How densely should we sample the hemisphere. Angular spacing is 180 degrees / this number

Returns
resultdict
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
objtrimesh.Trimesh, (n, 2) float, or (n, 3) float

Mesh object or points in 2D or 3D space

angle_digitsint

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

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
arrayarray- like object

To be turned into a TrackedArray

dtypenp.dtype

Which dtype to use for the array

Returns
trackedTrackedArray

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

An identifier for the object

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

If true, a set is returned containing the names of all pairs of objects in collision.

return_databool

If true, a list of ContactData is returned as well

Returns
is_collisionbool

True if a collision occurred between any pair of objects and False otherwise

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

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

Another collision manager object

return_namesbool

If true, a set is returned containing the names of all pairs of objects in collision.

return_databool

If true, a list of ContactData is returned as well

Returns
is_collisionbool

True if a collision occurred between any pair of objects and False otherwise

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

contactslist 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
meshTrimesh object

The geometry of the collision object

transform(4,4) float

Homogenous transform matrix

return_namesbool

If true, a set is returned containing the names of all objects in collision with the object

return_databool

If true, a list of ContactData is returned as well

Returns
is_collisionbool

True if a collision occurs and False otherwise

namesset of str

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

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

If true, a 2-tuple is returned containing the names of the closest objects.

return_databool

If true, a DistanceData object is returned as well

Returns
distancefloat

Min distance between any two managed objects

names(2,) str

The names of the closest objects

dataDistanceData

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_managerCollisionManager

Another collision manager object

return_namesbool

If true, a 2-tuple is returned containing the names of the closest objects.

return_databool

If true, a DistanceData object is returned as well

Returns
distancefloat

The min distance between a pair of objects, one from each manager.

names2-tup of str

A 2-tuple containing two names (first from this manager, second from the other_manager) indicating the two closest objects.

dataDistanceData

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

The geometry of the collision object

transform(4,4) float

Homogenous transform matrix for the object

return_namesbool

If true, return name of the closest object

return_databool

If true, a DistanceData object is returned as well

Returns
distancefloat

Min distance between mesh and any object in the manager

namestr

The name of the object in the manager that was closest

dataDistanceData

Extra data about the distance query

remove_object(name)

Delete an object from the collision manager.

Parameters
namestr

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
namestr

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
namestr

The name of the target object.

Returns
indexint

The index of the face in collison

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

property distance

Returns the distance between the two objects.

Returns
distancefloat

The euclidean distance between the objects.

index(name)

Returns the index of the closest face for the mesh with the given name.

Parameters
namestr

The name of the target object.

Returns
indexint

The index of the face in collisoin.

point(name)

The 3D point of closest distance on the mesh with the given name.

Parameters
namestr

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
meshTrimesh

Input geometry

Returns
bvhfcl.BVHModel

BVH of input geometry

trimesh.collision.scene_to_collision(scene)

Create collision objects from a trimesh.Scene object.

Parameters
scenetrimesh.Scene

Scene to create collision objects for

Returns
managerCollisionManager

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.face_ordering(mesh)

Triangles with three different length sides are ordered in two ways: [small edge, medium edge, large edge] (SML) [small edge, large edge, medium edge] (SLM)

This function returns [-1, 0, 1], depending on whether the triangle is SML or SLM, and 0 if M == L.

The reason this is useful as it as a rare property that is invariant to translation and rotation but changes when a mesh is reflected or inverted. It is NOT invariant to different tesselations of the same surface.

Parameters
meshtrimesh.Trimesh

Source geometry to calculate ordering on

Returns
order(len(mesh.faces), ) int

Is each face SML (-1), SLM (+1), or M==L (0)

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

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

Parameters
identifier(n,) float

Vector of properties

sigfig(n,) int

Number of sigfigs per property

Returns
md5str

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

Source geometry

Returns
identifier(6,) float

Identifying values of the mesh

trimesh.constants module

class trimesh.constants.ResolutionPath(**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.ToleranceMesh(**kwargs)

Bases: object

ToleranceMesh objects hold tolerance information about meshes.

Parameters
tol.zerofloat

Floating point numbers smaller than this are considered zero

tol.mergefloat

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

The maximum distance from a plane a point can be and still be considered to be on the plane

tol.facet_thresholdfloat

Threshold for two facets to be considered coplanar

tol.strictbool

If True, run additional in- process checks (slower)

class trimesh.constants.TolerancePath(**kwargs)

Bases: object

TolerancePath objects contain tolerance information used in Path objects.

Parameters
tol.zerofloat

Floating point numbers smaller than this are considered zero

tol.mergefloat

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

The maximum distance from a plane a point can be and still be considered to be on the plane

tol.seg_fracfloat
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.constants.log_time(method)

A decorator for methods which will time the method and then emit a log.debug message with the method name and how long it took to execute.

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
meshTrimesh

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.

objTrimesh, or (n,3) float

Mesh or cartesian points

Returns
convexTrimesh

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
meshTrimesh

Input geometry

Returns
convexbool

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, **kwargs)

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

Parameters
r_minfloat

The inner radius of the annular cylinder

r_maxfloat

The outer radius of the annular cylinder

heightfloat

The height of the annular cylinder

sectionsint

How many pie wedges should the annular cylinder have

**kwargs:

passed to Trimesh to create annulus

Returns
annulustrimesh.Trimesh

Mesh of annular cylinder

trimesh.creation.axis(origin_size=0.04, transform=None, origin_color=None, axis_radius=None, axis_length=None)

Return an XYZ axis marker as a Trimesh, which represents position and orientation. If you set the origin size the other parameters will be set relative to it.

Parameters
transform(4, 4) float

Transformation matrix

origin_sizefloat

Radius of sphere that represents the origin

origin_color(3,) float or int, uint8 or float

Color of the origin

axis_radiusfloat

Radius of cylinder that represents x, y, z axis

axis_length: float

Length of cylinder that represents x, y, z axis

Returns
markertrimesh.Trimesh

Mesh geometry of axis indicators

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

Return a cuboid.

Parameters
extentsfloat, or (3,) float

Edge lengths

transform: (4, 4) float

Transformation matrix

**kwargs:

passed to Trimesh to create box

Returns
geometrytrimesh.Trimesh

Mesh of a cuboid

trimesh.creation.camera_marker(camera, marker_height=0.4, origin_size=None)

Create a visual marker for a camera object, including an axis and FOV.

Parameters
cameratrimesh.scene.Camera

Camera object with FOV and transform defined

marker_heightfloat

How far along the camera Z should FOV indicators be

origin_sizefloat

Sphere radius of the origin (default: marker_height / 10.0)

Returns
mesheslist

Contains Trimesh and Path3D objects which can be visualized

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
heightfloat

Center to center distance of two spheres

radiusfloat

Radius of the cylinder and hemispheres

count(2,) int

Number of sections on latitude and longitude

Returns
capsuletrimesh.Trimesh
Capsule geometry with:
  • cylinder axis is along Z

  • one hemisphere is centered at the origin

  • other hemisphere is centered along the Z axis at height

trimesh.creation.cylinder(radius=1.0, height=1.0, sections=32, segment=None, transform=None, **kwargs)

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

Parameters
radiusfloat

The radius of the cylinder

heightfloat

The height of the cylinder

sectionsint

How many pie wedges should the cylinder have

segment(2, 3) float

Endpoints of axis, overrides transform and height

transform(4, 4) float

Transform to apply

**kwargs:

passed to Trimesh to create cylinder

Returns
cylinder: trimesh.Trimesh

Resulting mesh of a cylinder

trimesh.creation.extrude_polygon(polygon, height, **kwargs)

Extrude a 2D shapely polygon into a 3D mesh

Parameters
polygonshapely.geometry.Polygon

2D geometry to extrude

heightfloat

Distance to extrude polygon along Z

**kwargs:

passed to Trimesh

Returns
meshtrimesh.Trimesh

Resulting extrusion as watertight body

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

heightfloat

Distance to extrude triangulation

**kwargs:

passed to Trimesh

Returns
meshtrimesh.Trimesh

Mesh created from extrusion

trimesh.creation.icosahedron()

Create an icosahedron, a 20 faced polyhedron.

Returns
icotrimesh.Trimesh

Icosahederon centered at the origin.

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

Create an isophere centered at the origin.

Parameters
subdivisionsint

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

radiusfloat

Desired radius of sphere

color: (3,) float or uint8

Desired color of sphere

Returns
icotrimesh.Trimesh

Meshed sphere

trimesh.creation.random_soup(face_count=100)

Return random triangles as a Trimesh

Parameters
face_countint

Number of faces desired in mesh

Returns
souptrimesh.Trimesh

Geometry with face_count random faces

trimesh.creation.sweep_polygon(polygon, path, angles=None, **kwargs)

Extrude a 2D shapely polygon into a 3D mesh along an arbitrary 3D path. Doesn’t handle sharp curvature.

Parameters
polygonshapely.geometry.Polygon

Profile to sweep along path

path(n, 3) float

A path in 3D

angles(n,) float

Optional rotation angle relative to prior vertex at each vertex

Returns
meshtrimesh.Trimesh

Geometry of result

trimesh.creation.triangulate_polygon(polygon, triangle_args='pq30', 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

polygonShapely.geometry.Polygon

Polygon object to be triangulated

triangle_argsstr

Passed to triangle.triangulate

enginestr

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

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

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

Mesh of UV sphere with specified parameters

trimesh.creation.validate_polygon(obj)

Make sure an input can be returned as a valid polygon.

Parameters
objshapely.geometry.Polygon, str (wkb), or (n, 2) float

Object which might be a polygon

Returns
polygonshapely.geometry.Polygon

Valid polygon object

Raises
ValueError

If a valid finite- area polygon isn’t available

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
radiusfloat, 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
radiusfloat, the sphere radius
Returns
mean_curvature: (n,) float, discrete mean curvature measure.
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
radiusfloat, 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
Rfloat, sphere radius
rfloat, 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, **kwargs)

Compute an approximate convex decomposition of a mesh.

Parameters
meshtrimesh.Trimesh

Mesh to be decomposed into convex parts

Returns
mesh_argslist

List of **kwargs for Trimeshes that are nearly convex and approximate the original.

trimesh.geometry module

trimesh.geometry.align_vectors(a, b, return_angle=False)

Find a transform between two 3D vectors.

Implements the method described here: http://ethaneade.com/rot_between_vectors.pdf

Parameters
a(3,) float

Source vector

b(3,) float

Target vector

return_anglebool

If True return the angle between the two vectors

Returns
transform(4, 4) float

Homogenous transform from a to b

anglefloat

Angle between vectors in radians Only returned if return_angle

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_countint

The number of vertices faces refer to

faces(n, 3) int

List of vertex indices

face_normals(n, 3) float

Normal vector for each face

Returns
vertex_normals(vertex_count, 3) float

Normals for every vertex Vertices unreferenced by faces will be zero.

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.geometry.vertex_face_indices(vertex_count, faces, **kwargs)

Find vertex face indices from the faces array of vertices

Parameters
vertex_countint

The number of vertices faces refer to

faces(n, 3) int

List of vertex indices

Returns
vertex_faces(vertex_count, ) int

Face indices for every vertex Array padded with -1 in each row for all vertices with fewer face indices than the max number of face indices.

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

countint

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

meshTrimesh object

If passed will used cached edges instead of faces

return_edgesbool

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
meshtrimesh.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
meshTrimesh 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
facetssequence 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
traversalssequence of (m,) int

Node indexes of traversals of a graph

edges(n, 2) int

Pairs of connected node indexes

edges_hashNone, or (n,) int

Edges sorted along axis 1 then hashed using grouping.hashable_rows

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

List of vertex indices

edges_sorted(n, 2) int

Pass vertex indices sorted on axis 1 as a speedup

Returns
watertightboolean

Whether every edge is shared by an even number of faces

windingboolean

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
Gnetworkx.MultiDiGraph

Graph to evaluate

sourcehashable

Node to start traversal at

cutoffint

Number of nodes to visit If None will visit all nodes

Returns
traversals(n,) list of [(node, edge instance index), ] paths

Traversals of the multigraph

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 by disconnecting faces at sharp angles to each other.

meshtrimesh.Trimesh

Source geometry

anglefloat

Angle in radians, adjacent faces which have normals below this angle will be smoothed

Returns
smoothtrimesh.Trimesh

Geometry with disconnected face patches

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
splitsequence 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
modestr, ‘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
meshTrimesh object
Returns
graphnetworkx.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

operationfunction
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

radiusfloat

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

Input data

digitsfloat or int

Precision for float conversion

dtypenumpy.dtype

What datatype should result be returned as

Returns
as_int(n, d) 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

distancefloat

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

anglefloat

Group vectors closer than this angle in radians

include_negativebool

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

Input data

digitsint or None

How many digits to add to hash if data is floating point If None, tol.merge will be used

Returns
hashable(n,) array

Custom data type 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(mesh, digits=None, textured=True, uv_digits=4)

Removes duplicate vertices based on integer hashes of each row.

Parameters
meshTrimesh object

Mesh to merge vertices on

digitsint

How many digits to consider for vertices If not specified uses tol.merge

texturedbool

If True, for textured meshes only merge vertices with identical positions AND UV coordinates. No effect on untextured meshes

uv_digitsint

Number of digits to consider for UV coordinates.

trimesh.grouping.unique_bincount(values, minlength=0, return_inverse=False, return_counts=False)

For arrays of integers find unique values using bin counting. Roughly 10x faster for correct input than np.unique

Parameters
values(n,) int

Values to find unique members of

minlengthint

Maximum value that will occur in values (values.max())

return_inversebool

If True, return an inverse such that unique[inverse] == values

return_countsbool

If True, also return the number of times each unique item appears in values

Returns
unique(m,) int

Unique values in original array

inverse(n,) int, optional

An array such that unique[inverse] == values Only returned if return_inverse is True

counts(m,) int, optional

An array holding the counts of each unique item in values Only returned if return_counts is True

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 checked for internal consistency.

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

Return the inertia tensor of a cylinder.

Parameters
massfloat

Mass of cylinder

radiusfloat

Radius of cylinder

heightfloat

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
symmetryNone or str

None No rotational symmetry ‘radial’ Symmetric around an axis ‘spherical’ Symmetric around a point

axisNone or (3,) float

Rotation axis or point

sectionNone or (3, 2) float

If radial symmetry provide vectors to get cross section

trimesh.inertia.sphere_inertia(mass, radius)

Return the inertia tensor of a sphere.

Parameters
massfloat

Mass of sphere

radiusfloat

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

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

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_faces_plane(vertices, faces, plane_normal, plane_origin, cached_dots=None)

Slice a mesh (given as a set of faces and vertices) with a plane, returning a new mesh (again as a set of faces and vertices) that is the portion of the original mesh to the positive normal side of the plane.

vertices(n, 3) float

Vertices of source mesh to slice

faces(n, 3) int

Faces of source mesh to slice

plane_normal(3,) float

Normal vector of plane to intersect with mesh

plane_origin: (3,) float

Point on plane to intersect with mesh

cached_dots(n, 3) float

If an external function has stored dot products pass them here to avoid recomputing

new_vertices(n, 3) float

Vertices of sliced mesh

new_faces(n, 3) int

Faces of sliced mesh

trimesh.intersections.slice_mesh_plane(mesh, plane_normal, plane_origin, **kwargs)

Slice a mesh with a plane, returning a new mesh that is the portion of the original mesh to the positive normal side of the plane

meshTrimesh object

Source mesh to slice

plane_normal(3,) float

Normal vector of plane to intersect with mesh

plane_origin: (3,) float

Point on plane to intersect with mesh

cap: bool

If True, cap the result with a triangulated polygon

cached_dots(n, 3) float

If an external function has stored dot products pass them here to avoid recomputing

Returns
new_meshTrimesh object

Sliced mesh

trimesh.interval module

interval.py

Deal with 1D intervals which are defined by:

[start position, end position]

trimesh.interval.check(a, b, digits)

Check input ranges, convert them to vector form, and get a fixed precision integer version of them.

Parameters
a(2, ) or (2, n) float

Start and end of a 1D interval

b(2, ) or (2, n) float

Start and end of a 1D interval

digitsint

How many digits to consider

Returns
a(2, n) float

Ranges as vector

b(2, n) float

Ranges as vector

a_int(2, n) int64

Ranges rounded to digits, as vector

b_int(2, n) int64

Ranges rounded to digits, as vector

is_1Dbool

If True, input was single pair of ranges

trimesh.interval.intersection(a, b, digits=8)

Given a pair of ranges, merge them in to one range if they overlap at all

Parameters
a(2, ) float

Start and end of a 1D interval

b(2, ) float

Start and end of a 1D interval

digitsint

How many digits to consider

Returns
intersectsbool or (n,) bool

Indicates if the ranges overlap at all

new_range(2, ) or (2, 2) float

The unioned range from the two inputs, or both of the original ranges if not overlapping

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

Points in space

prior(d,) float

Best guess for center of nsphere

Returns
center(d,) float

Location of center

radiusfloat

Mean radius across circle

errorfloat

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
checkbool

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(n, d) float or trimesh.Trimesh

Points or mesh to find minimum bounidng nsphere

Returns
center(d,) float

Center of fitted n- sphere

radiusfloat

Radius of fitted n-sphere

trimesh.parent module

parent.py

The base class for Trimesh, PointCloud, and Scene objects

class trimesh.parent.Geometry

Bases: abc.ABC

Parent of geometry classes.

The Geometry object is the parent object of geometry classes, including: Trimesh, PointCloud, and Scene objects.

By decorating a method with abc.abstractmethod it just means the objects that inherit from Geometry MUST implement those methods.

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
extents

Methods

apply_scale(scaling)

Scale the mesh equally on all axis.

apply_translation(translation)

Translate the current mesh.

apply_transform

copy

is_empty

show

apply_scale(scaling)

Scale the mesh equally on all axis.

Parameters
scalingfloat

Scale factor to apply to the mesh

abstract apply_transform()
apply_translation(translation)

Translate the current mesh.

Parameters
translation(3,) float

Translation in XYZ

property bounding_box

An axis aligned bounding box for the current mesh.

Returns
aabbtrimesh.primitives.Box

Box object with transform and extents defined representing the axis aligned bounding box of the mesh

property bounding_box_oriented

An oriented bounding box for the current mesh.

Returns
obbtrimesh.primitives.Box

Box object with transform and extents defined representing the minimum volume oriented bounding box of the mesh

property bounding_cylinder

A minimum volume bounding cylinder for the current mesh.

Returns
mincyltrimesh.primitives.Cylinder

Cylinder primitive containing current mesh

property bounding_primitive

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

Returns
bounding_primitivetrimesh.primitives.Sphere

trimesh.primitives.Box trimesh.primitives.Cylinder

Primitive which bounds the mesh with the smallest volume

property 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

abstract property bounds
abstract copy()
abstract property extents
abstract is_empty()
abstract show()

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(vertices, colors=None, color=None)

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

is_empty

Are there any vertices defined or not.

shape

Get the shape of the pointcloud

vertices

Vertices of the PointCloud

Methods

apply_scale(scaling)

Scale the mesh equally on all axis.

apply_transform(transform)

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

apply_translation(translation)

Translate the current mesh.

copy()

Safely get a copy of the current point cloud.

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(**kwargs)

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

property bounds

The axis aligned bounds of the PointCloud

Returns
bounds(2, 3) float

Miniumum, Maximum verteex

property centroid

The mean vertex position

Returns
centroid(3,) float

Mean vertex position

property colors

Stored per- point color

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

Per- point RGBA color

property convex_hull

A convex hull of every point.

Returns
convex_hulltrimesh.Trimesh

A watertight mesh of the hull of the points

copy()

Safely get a copy of the current point cloud.

Copied objects will have emptied caches to avoid memory issues and so may be slow on initial operations until caches are regenerated.

Current object will not have its cache cleared.

Returns
copiedtrimesh.PointCloud

Copy of current point cloud

property extents

The size of the axis aligned bounds

Returns
extents(3,) float

Edge length of axis aligned bounding box

property is_empty

Are there any vertices defined or not.

Returns
emptybool

True if no vertices defined

md5()

Get an MD5 hash of the current vertices.

Returns
md5str

Hash of self.vertices

merge_vertices()

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

scene()

A scene containing just the PointCloud

Returns
scenetrimesh.Scene

Scene object containing this PointCloud

property shape

Get the shape of the pointcloud

Returns
shape(2,) int

Shape of vertex array

show(**kwargs)

Open a viewer window displaying the current PointCloud

property 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

kint

Number of centroids to compute

**kwargsdict

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

showbool

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

radiusfloat

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

startint

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

The target mesh

com(3,) float

Rhe object center of mass. If None, this method assumes uniform density and watertightness and computes a center of mass explicitly

sigmafloat

Rhe covariance for the multivariate gaussian used to sample center of mass locations

n_samplesint

The number of samples of the center of mass location

thresholdfloat

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

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

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

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.

referenced_vertices

Which vertices in the current mesh are referenced by a face.

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_faces

A representation of the face indices that correspond to each 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.

visual

Get the stored visuals for the current 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([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([digits, textured])

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 list of face indexes find the outline of those 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, **kwargs)

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, without changing source mesh.

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

property 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
countint or (3,) int

If specified samples are spaced with np.linspace

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

Number of samples to return

Returns
samples(count, 3) float

Points inside the volume

property 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 faces 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_inverse

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

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.

referenced_vertices

Which vertices in the current mesh are referenced by a face.

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_faces

A representation of the face indices that correspond to each 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.

visual

Get the stored visuals for the current 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([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([digits, textured])

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 list of face indexes find the outline of those 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, **kwargs)

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, without changing source mesh.

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

property 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 faces 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_inverse

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

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.

referenced_vertices

Which vertices in the current mesh are referenced by a face.

scale

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

segment

A line segment which if inflated by cylinder radius would represent the cylinder primitive.

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_faces

A representation of the face indices that correspond to each 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.

visual

Get the stored visuals for the current 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.

buffer(distance)

Return a cylinder primitive which covers the source cylinder by distance: radius is inflated by distance, height by twice the 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([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([digits, textured])

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 list of face indexes find the outline of those 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, **kwargs)

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, without changing source mesh.

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

buffer(distance)

Return a cylinder primitive which covers the source cylinder by distance: radius is inflated by distance, height by twice the distance.

Parameters
distancefloat

Distance to inflate cylinder radius and height

Returns
bufferedCylinder

Cylinder primitive inflated by distance

property direction

The direction of the cylinder’s axis.

Returns
axis: (3,) float, vector along the cylinder axis
property moment_inertia

The analytic inertia tensor of the cylinder primitive.

Returns
tensor: (3,3) float, 3D inertia tensor
property segment

A line segment which if inflated by cylinder radius would represent the cylinder primitive.

Returns
segment(2, 3) float

Points representing a single line segment

property volume

The analytic volume of the cylinder primitive.

Returns
volumefloat

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

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

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.

referenced_vertices

Which vertices in the current mesh are referenced by a face.

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_faces

A representation of the face indices that correspond to each 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.

visual

Get the stored visuals for the current 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([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([digits, textured])

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 list of face indexes find the outline of those 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, **kwargs)

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, without changing source mesh.

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

property 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
property 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
property 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 faces 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_inverse

Return the inverse required to reproduce self.edges_sorted from self.edges_unique.

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.

referenced_vertices

Which vertices in the current mesh are referenced by a face.

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_faces

A representation of the face indices that correspond to each 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.

visual

Get the stored visuals for the current 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([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([digits, textured])

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 list of face indexes find the outline of those 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, **kwargs)

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, without changing source mesh.

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

Surface area of the current sphere primitive.

Returns
area: float, surface area of the sphere Primitive
property bounding_box_oriented

An oriented bounding box for the current mesh.

Returns
obbtrimesh.primitives.Box

Box object with transform and extents defined representing the minimum volume oriented bounding box of the mesh

property bounds

The axis aligned bounds of the faces of the mesh.

Returns
bounds(2, 3) float

Bounding box with [min, max] coordinates

property moment_inertia

The analytic inertia tensor of the sphere primitive.

Returns
tensor: (3,3) float, 3D inertia tensor
property 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
meshTrimesh 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
meshTrimesh

Takes mesh to have same interfaces as closest_point

points(m, 3) float

Points in space

Returns
closest(m, 3) float

Closest point on triangles for each point

distance(m,) float

Distances between point and triangle

triangle_id(m,) int

Index of triangle containing closest point

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
inwardsbool, 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
meshTrimesh 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
meshTrimesh 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
exteriorbool, 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.

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

thresholdfloat

Stop when change in cost is less than threshold

max_iterationsint

Maximum number of iterations

kwargsdict

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

costfloat

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

Mesh to align with other

othertrimesh.Trimesh or (n, 3) float

Mesh or points in space

samplesint

Number of samples from mesh surface to align

scalebool

Allow scaling in transform

icp_firstint

How many ICP iterations for the 9 possible combinations of sign flippage

icp_finalint

How many ICP iterations for the closest candidate from the wider search

Returns
mesh_to_other(4, 4) float

Transform to align mesh to the other object

costfloat

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

reflectionbool

If the transformation is allowed reflections

translationbool

If the transformation is allowed translations

scalebool

If the transformation is allowed scaling

return_costbool

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

costfloat

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.

Note that if face_index is passed, only those faces will be subdivided and their neighbors won’t be modified making the mesh no longer “watertight.”

Parameters
vertices(n, 3) float

Vertices in space

faces(n, 3) int

Indexes of vertices which make up triangular faces

face_indexfaces to subdivide.

if None: all faces of mesh will be subdivided if (n,) int array of indices: only specified faces

Returns
new_vertices(n, 3) float

Vertices in space

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_edgefloat

Maximum length of any edge in the result

max_iterint

The maximum number of times to run subdivision

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_typestr

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
objTrimesh, Path2D, Path3D, (n,2) float, (n,3) float

Object to render

Returns
argstuple

Args to be passed to pyglet indexed vertex list constructor.

trimesh.rendering.light_to_gl(light, transform, lightN)

Convert trimesh.scene.lighting.Light objects into args for gl.glLightFv calls

Parameters
lighttrimesh.scene.lighting.Light

Light object to be converted to GL

transform(4, 4) float

Transformation matrix of light

lightNint

Result of gl.GL_LIGHT0, gl.GL_LIGHT1, etc

Returns
multiarg[tuple]

List of args to pass to gl.glLightFv eg: [gl.glLightfb(*a) for a in multiarg]

trimesh.rendering.material_to_texture(material)

Convert a trimesh.visual.texture.Material object into a pyglet- compatible texture object.

Parameters
materialtrimesh.visual.texture.Material

Material to be converted

Returns
texturepyglet.image.Texture

Texture loaded into pyglet form

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,) 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
meshtrimesh.Trimesh

Mesh to be rendered

groupstr

Rendering group for the vertex list

smoothbool

Should we try to smooth shade the mesh

smooth_thresholdint

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
pathtrimesh.path.Path3D object

Mesh to be rendered

groupstr

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

groupstr

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

meshtrimesh.Trimesh

Mesh will be repaired in- place

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.smoothing module

trimesh.smoothing.filter_humphrey(mesh, alpha=0.1, beta=0.5, iterations=10, laplacian_operator=None)

Smooth a mesh in-place using laplacian smoothing and Humphrey filtering.

Articles “Improved Laplacian Smoothing of Noisy Surface Meshes” J. Vollmer, R. Mencl, and H. Muller

Parameters
meshtrimesh.Trimesh

Mesh to be smoothed in place

alphafloat

Controls shrinkage, range is 0.0 - 1.0 If 0.0, not considered If 1.0, no smoothing

betafloat

Controls how aggressive smoothing is If 0.0, no smoothing If 1.0, full aggressiveness

iterationsint

Number of passes to run filter

laplacian_operatorNone or scipy.sparse.coo.coo_matrix

Sparse matrix laplacian operator Will be autogenerated if None

trimesh.smoothing.filter_laplacian(mesh, lamb=0.5, iterations=10, implicit_time_integration=False, volume_constraint=True, laplacian_operator=None)

Smooth a mesh in-place using laplacian smoothing. Articles 1 - “Improved Laplacian Smoothing of Noisy Surface Meshes”

  1. Vollmer, R. Mencl, and H. Muller

2 - “Implicit Fairing of Irregular Meshes using Diffusion

and Curvature Flow”. M. Desbrun, M. Meyer, P. Schroder, A.H.B. Caltech

Parameters
meshtrimesh.Trimesh
Mesh to be smoothed in place
lambfloat
Diffusion speed constant
If 0.0, no diffusion
If > 0.0, diffusion occurs
implicit_time_integration: boolean
if False: explicit time integration

-lamb <= 1.0 - Stability Limit (Article 1)

if True: implict time integration

-lamb no limit (Article 2)

iterationsint
Number of passes to run filter
laplacian_operatorNone or scipy.sparse.coo.coo_matrix
Sparse matrix laplacian operator
Will be autogenerated if None
trimesh.smoothing.filter_taubin(mesh, lamb=0.5, nu=0.5, iterations=10, laplacian_operator=None)

Smooth a mesh in-place using laplacian smoothing and taubin filtering.

Articles “Improved Laplacian Smoothing of Noisy Surface Meshes” J. Vollmer, R. Mencl, and H. Muller

Parameters
meshtrimesh.Trimesh

Mesh to be smoothed in place.

lambfloat

Controls shrinkage, range is 0.0 - 1.0

nufloat

Controls dilation, range is 0.0 - 1.0 Nu shall be between 0.0 < 1.0/lambda - 1.0/nu < 0.1

iterationsint

Number of passes to run the filter

laplacian_operatorNone or scipy.sparse.coo.coo_matrix

Sparse matrix laplacian operator Will be autogenerated if None

trimesh.smoothing.laplacian_calculation(mesh, equal_weight=True)

Calculate a sparse matrix for laplacian operations.

Parameters
meshtrimesh.Trimesh

Input geometry

equal_weightbool

If True, all neighbors will be considered equally If False, all neightbors will be weighted by inverse distance

Returns
laplacianscipy.sparse.coo.coo_matrix

Laplacian operator

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_coplanarbool

True if all triangles are coplanar

trimesh.triangles.angles(triangles)

Calculates the angles of input triangles.

Parameters
triangles(n, 3, 3) float

Vertex positions

Returns
angles(n, 3) float

Angles at vertex positions in radians Degenerate angles will be returned as zero

trimesh.triangles.any_coplanar(triangles)

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

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

Calculates the sum area of input triangles

Parameters
triangles(n, 3, 3) float

Vertices of triangles

crosses(n, 3) float or None

As a speedup don’t re- compute cross products

sumbool

Return summed area or individual triangle area

Returns
area(n,) float or float

Individual or summed area depending on sum argument

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

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

Triangles in space

Returns
treertree.Rtree

One node per triangle

trimesh.triangles.closest_point(triangles, points)

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

Implements the method from “Real Time Collision Detection” and use the same variable names as “ClosestPtPointTriangle” to avoid being any more confusing.

Parameters
triangles(n, 3, 3) float

Triangle vertices in space

points(n, 3) float

Points in space

Returns
closest(n, 3) float

Point on each triangle closest to each point

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

Triangles in space

areas(n,) float

Optional area of input triangles

Returns
box(n, 2) float

The size of each triangle’s 2D oriented bounding box

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

Triangle vertices in space

crosses(n,) float

Optional cross products of triangles

densityfloat

Optional override for density

center_mass(3,) float

Optional override for center mass

skip_inertiabool

if True will not return moments matrix

Returns
infodict

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

Triangles in space

heightfloat

Minimum edge length of a triangle to keep

Returns
nondegenerate(n,) bool

True if a triangle meets required minimum height

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

Was the face nonzero area or not

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 vertices in space

points(n, 3) float

Point in space associated with a triangle

methodstr
Which method to compute the barycentric coordinates with:
  • ‘cross’: uses a method using cross products, roughly 2x slower but

    different numerical robustness properties

  • anything else: uses a cramer’s rule solution

Returns
barycentric(n, 3) float

Barycentric coordinates of each point

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
kwargsdict

Keyword arguments for the trimesh.Trimesh constructor Includes keys ‘vertices’ and ‘faces’

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

Vertex locations in space

normals_compare(n, 3) float

List of normals to compare

Returns
aligned(n,) bool

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.

currentstr

Unit system values are in now (eg ‘millimeters’)

desiredstr

Unit system we’d like values in (eg ‘inches’)

Returns
conversionfloat

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)

guessbool

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
arrayarray

Any numpy array

dtypestr or None

Optional dtype to encode array

encodingstr

‘base64’ or ‘binary’

Returns
encodeddict

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_delimstr

What string should separate values in a column

row_delimstr

What string should separate values in a row

digitsint

How many digits should floating point numbers include

value_formatstr

Format string for each value or sequence of values If multiple values per value_format it must divide into array evenly.

Returns
formattedstr

String representation of original array

trimesh.util.attach_to_log(level=10, handler=None, loggers=None, colors=True, capture_warnings=True, blacklist=None)

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
infodict

Data to compress in form: {file name in archive: bytes or file-like object}

Returns
compressedbytes

Compressed file data

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.

storedict

Dictionary with data

Returns
resultdict

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

Containing compressed data

file_typestr

File extension, ‘zip’, ‘tar.gz’, etc

Returns
decompresseddict

Data from archive in format {file name : file-like}

trimesh.util.diagonal_dot(a, b)

Dot product by row of a and b.

There are a lot of ways to do this though performance varies very widely. This method uses the dot product to sum the row and avoids function calls if at all possible.

Comparing performance of some equivalent versions: ``` In [1]: import numpy as np; import trimesh

In [2]: a = np.random.random((10000, 3))

In [3]: b = np.random.random((10000, 3))

In [4]: %timeit (a * b).sum(axis=1) 1000 loops, best of 3: 181 us per loop

In [5]: %timeit np.einsum(‘ij,ij->i’, a, b) 10000 loops, best of 3: 62.7 us per loop

In [6]: %timeit np.diag(np.dot(a, b.T)) 1 loop, best of 3: 429 ms per loop

In [7]: %timeit np.dot(a * b, np.ones(a.shape[1])) 10000 loops, best of 3: 61.3 us per loop

In [8]: %timeit trimesh.util.diagonal_dot(a, b) 10000 loops, best of 3: 55.2 us per loop ```

Parameters
a(m, d) float

First array

b(m, d) float

Second array

Returns
result(m,) float

Dot product of each row

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

Euclidean distance between A and B

trimesh.util.generate_basis(z)

Generate an arbitrary basis (also known as a coordinate frame) from a given z-axis vector.

Parameters
z: (3,) float

A vector along the positive z-axis

Returns
x(3,) float

Vector along x axis

y(3,) float

Vector along y axis

z(3,) float

Vector along 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
objobject

Any object type to be checked

Returns
is_filebool

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.

objinstance

Some object of some class

name: str

The name of the class we want to check for

Returns
is_instancebool

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
objobject

Any object type to be checked

Returns
is_nonebool

True if obj is None or numpy None-like

trimesh.util.is_sequence(obj)

Check if an object is a sequence or not.

Parameters
objobject

Any object type to be checked

Returns
is_sequencebool

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.

objnp.ndarray

Array to check the shape on

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

Any object type to be checked

Returns
is_stringbool

True if obj is a string

trimesh.util.isclose(a, b, atol)

A replacement for np.isclose that does fewer checks and validation and as a result is roughly 4x faster.

Note that this is used in tight loops, and as such a and b MUST be np.ndarray, not list or “array-like”

Parameters
anp.ndarray

To be compared

bnp.ndarray

To be compared

atolfloat

Acceptable distance between a and b to be “close”

Returns
closenp.ndarray, bool

Per- element closeness

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

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

Parameters
objJSON- serializable blob
**kwargs :

Passed to json.dumps

Returns
dumpedstr

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
objobject

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.row_norm(data)

Compute the norm per- row of a numpy array.

This is identical to np.linalg.norm(data, axis=1) but roughly three times faster due to being less general.

In [3]: %timeit trimesh.util.row_norm(a) 76.3 us +/- 651 ns per loop

In [4]: %timeit np.linalg.norm(a, axis=1) 220 us +/- 5.41 us per loop

Parameters
data(n, d) float

Input 2D data to calculate per- row norm of

Returns
norm(n,) float

Norm of each row of input array

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

a value from ‘special’

trimesh.util.stack_3D(points, return_2D=False)

For a list of (n, 2) or (n, 3) points return them as (n, 3) 3D points, 2D points on the XY plane.

Parameters
points(n, 2) or (n, 3) float

Points in either 2D or 3D space

return_2Dbool

Were the original points 2D?

Returns
points(n, 3) float

Points in space

is_2Dbool

Only returned if return_2D If source points were (n, 2) True

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
meshTrimesh

Source mesh to take geometry from

faces_sequencesequence (p,) int

Indexes of mesh.faces

only_watertightbool

Only return submeshes which are watertight.

appendbool

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

Returns
if appendTrimesh object
else list of Trimesh objects
trimesh.util.tolist(data)

Ensure that any arrays or dicts passed containing numpy arrays are properly converted to lists

Parameters
dataany

Usually a dict with some numpy arrays as values

Returns
resultany

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
namestr, 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_validbool

If set, will return mask of nonzero vectors

thresholdfloat

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_signbool

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

1D array

countint

Minimum length of result array

Returns
padded(m,)

1D array where m >= count

trimesh.version module

trimesh.voxel module

voxel.py

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

class trimesh.voxel.Voxel(matrix, pitch, origin)

Bases: trimesh.voxel.VoxelBase

Voxel representation with matrix, pitch and origin.

All voxels are referenced by the center of their cell box, for example, the origin exactly matches the center of the first voxel.

Parameters
matrix: (X, Y, Z)

Matrix that is interpreted as boolean to represent filled voxels.

pitch: float

Scale of each voxel.

origin: (3,) float

The center of the first voxel.

Attributes
filled_count

Return the number of voxels that are occupied.

marching_cubes

A marching cubes Trimesh representation of the voxels.

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

as_boxes([colors])

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

is_filled(point)

Query points to see if the voxel cells they lie in are filled or not.

point_to_index(point)

Convert points to indices in the matrix array.

show(*args, **kwargs)

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

as_boxes(colors=None)

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

Parameters
colors(3,) or (4,) float or uint8

(X, Y, Z, 3) or (X, Y, Z, 4) float or uint8

Where matrix.shape == (X, Y, Z)

Returns
meshtrimesh.Trimesh

Mesh with one box per filled cell.

property matrix
property origin
show(*args, **kwargs)

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

class trimesh.voxel.VoxelBase(*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 points to see if the voxel cells they lie in are filled or not.

point_to_index(point)

Convert points to indices in the matrix array.

property filled_count

Return the number of voxels that are occupied.

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

Query points to see if the voxel cells they lie in are filled or not.

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

property pitch
point_to_index(point)

Convert points to indices in the matrix array.

Parameters
point: (…, 3) float, point in space
Returns
index: (…, 3) int array of indices into self.matrix
property points

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

Returns
points: (self.filled, 3) float, list of points
property 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

property 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.VoxelBase

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 points to see if the voxel cells they lie in are filled or not.

point_to_index(point)

Convert points to indices 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.
property 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
property 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
property 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
property 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.

property sparse_solid

Filled cells inside and on the surface of mesh

Returns
filled: (n, 3) int, filled cells in or on mesh.
property 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.indices_to_points(indices, pitch, origin)

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

Parameters
indices: (…, 3) int, index of voxel matrix (n,m,p)
pitch: float, what pitch was the voxel matrix computed with
origin: (3,) float, what is the origin of the voxel matrix
Returns
points: (…, 3) float, list of points
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
meshtrimesh.Trimesh

Source geometry

point(3, ) float

Point in space to voxelize around

pitchfloat

Side length of a single voxel cube

radiusint

Number of voxel cubes to return in each direction.

kwargsparameters 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

pitchfloat

What pitch was the voxel matrix computed with

origin(3,) float

What is the origin of the voxel matrix

Returns
meshtrimesh.Trimesh

Mesh 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, colors=None)

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
colors: (3,) or (4,) or (n,3) or (n, 4) float, color of boxes
Returns
rough: Trimesh object representing inputs
trimesh.voxel.points_to_indices(points, pitch, origin)

Convert points in voxel-space to indices of an (n,m,p) matrix.

Parameters
points(…, 3) float

Center points of voxel matrix (n,m,p)

pitchfloat

What pitch was the voxel matrix computed with

origin(3,) float

What is the origin of the voxel matrix

Returns
indices(…, 3) int

numpy array of indices. Leading dims are the same as points

trimesh.voxel.points_to_marching_cubes(points, pitch)

Mesh points by assuming they fill a voxel box, and then running marching cubes on them

Parameters
points(n, 3) float

Points in 3D space

pitchfloat

Spacing of boxes to use

Returns
meshtrimesh.Trimesh

Points meshed using marching cubes at pitch

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.