trimesh.scene package¶
Submodules¶
trimesh.scene.cameras module¶

class
trimesh.scene.cameras.
Camera
(name=None, resolution=None, focal=None, fov=None, z_near=0.01, z_far=1000.0)¶ Bases:
object

property
K
¶ Get the intrinsic matrix for the Camera object.
 Returns
K – Intrinsic matrix for camera
 Return type
(3, 3) float

angles
()¶ Get ray spherical coordinates in radians.
 Returns
angles – Ray spherical coordinate angles in radians.
 Return type
(n, 2) float

copy
()¶ Safely get a copy of the current camera.

property
focal
¶ Get the focal length in pixels for the camera.
 Returns
focal – Focal length in pixels
 Return type
(2,) float

property
fov
¶ Get the field of view in degrees.
 Returns
fov – XY field of view in degrees
 Return type
(2,) float

look_at
(points, rotation=None, distance=None, center=None)¶ Generate transform for a camera to keep a list of points in the camera’s field of view.
 Parameters
points ((n, 3) float) – Points in space
rotation (None, or (4, 4) float) – Rotation matrix for initial rotation
distance (None or float) – Distance from camera to center
center (None, or (3,) float) – Center of field of view.
 Returns
transform – Transformation matrix from world to camera
 Return type
(4, 4) float

property
resolution
¶ Get the camera resolution in pixels.
 Returns
Camera resolution in pixels
 Return type
resolution (2,) float

to_rays
()¶ Calculate ray direction vectors.
Will return one ray per pixel, as set in self.resolution.
 Returns
vectors – Ray direction vectors in camera frame with z == 1
 Return type
(n, 3) float

property

trimesh.scene.cameras.
camera_to_rays
(camera)¶ Calculate the trimesh.scene.Camera object to direction vectors.
Will return one ray per pixel, as set in camera.resolution.
 Parameters
camera (trimesh.scene.Camera) –
 Returns
vectors – Ray direction vectors in camera frame with z == 1
 Return type
(n, 3) float

trimesh.scene.cameras.
look_at
(points, fov, rotation=None, distance=None, center=None)¶ Generate transform for a camera to keep a list of points in the camera’s field of view.
 Parameters
points ((n, 3) float) – Points in space
fov ((2,) float) – Field of view, in DEGREES
rotation (None, or (4, 4) float) – Rotation matrix for initial rotation
distance (None or float) – Distance from camera to center
center (None, or (3,) float) – Center of field of view.
 Returns
transform – Transformation matrix from world to camera
 Return type
(4, 4) float

trimesh.scene.cameras.
ray_pixel_coords
(camera)¶ Get the xy coordinates of rays in camera coordinates at z == 1.
One coordinate pair will be given for each pixel as defined in camera.resolution. If reshaped, the returned array corresponds to pixels of the rendered image.
i.e. ```python xy = ray_pixel_coords(camera).reshape(
tuple(camera.coordinates) + (2,))
top_left == xy[0, 0] bottom_right == xy[1, 1] ```
 Parameters
camera (trimesh.scene.Camera) –
 Returns
xy – xy coordinates of intersection of each camera ray with the z == 1 frame
 Return type
(n, 2) float
trimesh.scene.lighting module¶
lighting.py¶
Hold basic information about lights.
Forked from the light model in pyrender: https://github.com/mmatl/pyrender

class
trimesh.scene.lighting.
DirectionalLight
(name=None, color=None, intensity=None, radius=None)¶ Bases:
trimesh.scene.lighting.Light
Directional lights are light sources that act as though they are infinitely far away and emit light in the direction of the local z axis. This light type inherits the orientation of the node that it belongs to; position and scale are ignored except for their effect on the inherited node orientation. Because it is at an infinite distance, the light is not attenuated. Its intensity is defined in lumens per metre squared, or lux (lm/m2).

name
¶ Name of the light.
 Type
str, optional

color
¶ RGBA value for the light’s color in linear space.
 Type
(4,) unit8

intensity
¶ Brightness of light. The units that this is defined in depend on the type of light. point and spot lights use luminous intensity in candela (lm/sr), while directional lights use illuminance in lux (lm/m2).
 Type
float

radius
¶ Cutoff distance at which light’s intensity may be considered to have reached zero. Supported only for point and spot lights, must be > 0. If None, the radius is assumed to be infinite.
 Type
float


class
trimesh.scene.lighting.
Light
(name=None, color=None, intensity=None, radius=None)¶ Bases:
abc.ABC
Base class for all light objects.

name
¶ Name of the light.
 Type
str, optional

color
¶ RGBA value for the light’s color in linear space.
 Type
(4,) uint8

intensity
¶ Brightness of light. The units that this is defined in depend on the type of light: point and spot lights use luminous intensity in candela (lm/sr) while directional lights use illuminance in lux (lm/m2).
 Type
float

radius
¶ Cutoff distance at which light’s intensity may be considered to have reached zero. Supported only for point and spot lights Must be > 0.0 If None, the radius is assumed to be infinite.
 Type
float

property
color

property
intensity

property
radius


class
trimesh.scene.lighting.
PointLight
(name=None, color=None, intensity=None, radius=None)¶ Bases:
trimesh.scene.lighting.Light
Point lights emit light in all directions from their position in space; rotation and scale are ignored except for their effect on the inherited node position. The brightness of the light attenuates in a physically correct manner as distance increases from the light’s position (i.e. brightness goes like the inverse square of the distance). Point light intensity is defined in candela, which is lumens per square radian (lm/sr).

name
¶ Name of the light.
 Type
str, optional

color
¶ RGBA value for the light’s color in linear space.
 Type
(4,) uint8

intensity
¶ Brightness of light. The units that this is defined in depend on the type of light. point and spot lights use luminous intensity in candela (lm/sr), while directional lights use illuminance in lux (lm/m2).
 Type
float

radius
¶ Cutoff distance at which light’s intensity may be considered to have reached zero. Supported only for point and spot lights, must be > 0. If None, the radius is assumed to be infinite.
 Type
float


class
trimesh.scene.lighting.
SpotLight
(name=None, color=None, intensity=None, radius=None, innerConeAngle=0.0, outerConeAngle=0.7853981633974483)¶ Bases:
trimesh.scene.lighting.Light
Spot lights emit light in a cone in the direction of the local z axis. The angle and falloff of the cone is defined using two numbers, the innerConeAngle and outerConeAngle. As with point lights, the brightness also attenuates in a physically correct manner as distance increases from the light’s position (i.e. brightness goes like the inverse square of the distance). Spot light intensity refers to the brightness inside the innerConeAngle (and at the location of the light) and is defined in candela, which is lumens per square radian (lm/sr). A spot light’s position and orientation are inherited from its node transform. Inherited scale does not affect cone shape, and is ignored except for its effect on position and orientation.

name
¶ Name of the light.
 Type
str, optional

color
¶ RGBA value for the light’s color in linear space.
 Type
(4,) uint8

intensity
¶ Brightness of light. The units that this is defined in depend on the type of light. point and spot lights use luminous intensity in candela (lm/sr), while directional lights use illuminance in lux (lm/m2).
 Type
float

radius
¶ Cutoff distance at which light’s intensity may be considered to have reached zero. Supported only for point and spot lights, must be > 0. If None, the radius is assumed to be infinite.
 Type
float

innerConeAngle
¶ Angle, in radians, from centre of spotlight where falloff begins. Must be greater than or equal to 0 and less than outerConeAngle.
 Type
float

outerConeAngle
¶ Angle, in radians, from centre of spotlight where falloff ends. Must be greater than innerConeAngle and less than or equal to PI / 2.0.
 Type
float

property
innerConeAngle

property
outerConeAngle


trimesh.scene.lighting.
autolight
(scene)¶ Generate a list of lights for a scene that looks decent.
 Parameters
scene (trimesh.Scene) – Scene with geometry
 Returns
lights ([Light]) – List of light objects
transforms ((len(lights), 4, 4) float) – Transformation matrices for light positions.
trimesh.scene.scene module¶

class
trimesh.scene.scene.
Scene
(geometry=None, base_frame='world', metadata={}, graph=None, camera=None, lights=None, camera_transform=None)¶ Bases:
trimesh.parent.Geometry
A simple scene graph which can be rendered directly via pyglet/openGL or through other endpoints such as a raytracer. Meshes are added by name, which can then be moved by updating transform in the transform tree.

add_geometry
(geometry, node_name=None, geom_name=None, parent_node_name=None, transform=None)¶ Add a geometry to the scene.
If the mesh has multiple transforms defined in its metadata, they will all be copied into the TransformForest of the current scene automatically.
 Parameters
geometry (Trimesh, Path2D, Path3D PointCloud or list) – Geometry to initially add to the scene
base_frame (str or hashable) – Name of base frame
metadata (dict) – Any metadata about the scene
graph (TransformForest or None) – A passed transform graph to use
 Returns
node_name – Name of node in self.graph
 Return type
str

apply_transform
(transform)¶

property
bounds
¶ Return the overall bounding box of the scene.
 Returns
bounds
 Return type
(2,3) float points for min, max corner

property
bounds_corners
¶ A list of points that represent the corners of the AABB of every geometry in the scene.
This can be useful if you want to take the AABB in a specific frame.
 Returns
corners
 Return type
(n, 3) float, points in space

property
camera
¶ Get the single camera for the scene. If not manually set one will abe automatically generated.
 Returns
camera – Camera object defined for the scene
 Return type
trimesh.scene.Camera

camera_rays
()¶ Calculate the trimesh.scene.Camera origin and ray direction vectors.
Will return one ray per pixel, as set in camera.resolution.
 Returns
origins ((3,) float) – Ray origins in space
vectors ((n, 3)) – Ray direction unit vectors in world coordinates

property
camera_transform
¶ Get camera transform in the base frame
 Returns
camera_transform – Camera transform in the base frame
 Return type
(4, 4), float

property
centroid
¶ Return the center of the bounding box for the scene.
 Returns
centroid
 Return type
float point for center of bounding box

convert_units
(desired, guess=False)¶ If geometry has units defined convert them to new units.
Returns a new scene with geometries and transforms scaled.
 Parameters
desired (str) – Desired final unit system: ‘inches’, ‘mm’, etc.
guess (bool) – Is the converter allowed to guess scale when models don’t have it specified in their metadata.
 Returns
scaled – Copy of scene with scaling applied and units set for every model
 Return type

property
convex_hull
¶ The convex hull of the whole scene
 Returns
hull
 Return type
Trimesh object, convex hull of all meshes in scene

copy
()¶ Return a deep copy of the current scene
 Returns
copied – Copy of the current scene
 Return type

dump
()¶ Append all meshes in scene to a list of meshes.
 Returns
dumped – location the scene.graph
 Return type
(n,) list, of Trimesh objects transformed to their

property
duplicate_nodes
¶ Return a sequence of node keys of identical meshes.
Will combine meshes duplicated by copying in space with different keys in self.geometry, as well as meshes repeated by self.nodes.
 Returns
duplicates – identical geometry
 Return type
sequence of keys to self.nodes that represent

explode
(vector=None, origin=None)¶ Explode a scene around a point and vector.
 Parameters
vector ((3,) float or float) – Explode radially around a direction vector or spherically
origin ((3,) float) – Point to explode around

export
(file_obj=None, file_type=None, **kwargs)¶ Export a snapshot of the current scene.
 Parameters
file_type (what encoding to use for meshes) – ie: dict, dict64, stl
 Returns
export – Only returned if file_obj is None
 Return type
bytes

property
extents
¶ Return the axis aligned box size of the current scene.
 Returns
extents
 Return type
(3,) float, bounding box sides length

property
geometry_identifiers
¶ Look up geometries by identifier MD5
 Returns
identifiers
 Return type
dict, identifier md5: key in self.geometry

property
is_empty
¶ Does the scene have anything in it.
 Returns
is_empty
 Return type
bool, True if nothing is in the scene

property
is_valid
¶ Is every geometry connected to the root node.
 Returns
is_valid – Does every geometry have a transform
 Return type
bool

property
lights
¶ Get a list of the lights in the scene. If nothing is set it will generate some automatically.
 Returns
lights – Lights in the scene.
 Return type

md5
()¶ MD5 of scene which will change when meshes or transforms are changed
 Returns
hashed
 Return type
str, MD5 hash of scene

rezero
()¶ Move the current scene so that the AABB of the whole scene is centered at the origin.
Does this by changing the base frame to a new, offset base frame.

save_image
(resolution=None, **kwargs)¶ Get a PNG image of a scene.
 Parameters
resolution ((2,) int, resolution to render image) –
**kwargs (passed to SceneViewer constructor) –
 Returns
png
 Return type
bytes, render of scene in PNG form

property
scale
¶ The approximate scale of the mesh
 Returns
scale
 Return type
float, the mean of the bounding box edge lengths

scaled
(scale)¶ Return a copy of the current scene, with meshes and scene transforms scaled to the requested factor.
 Parameters
scale (float) – Factor to scale meshes and transforms
 Returns
scaled – A copy of the current scene but scaled
 Return type

set_camera
(angles=None, distance=None, center=None, resolution=None, fov=None)¶ Create a camera object for self.camera, and add a transform to self.graph for it.
If arguments are not passed sane defaults will be figured out which show the mesh roughly centered.
 Parameters
angles ((3,) float) – Initial euler angles in radians
distance (float) – Distance from centroid
center ((3,) float) – Point camera should be center on
camera (Camera object) – Object that stores camera parameters

show
(viewer=None, **kwargs)¶ Display the current scene.
 Parameters
viewer (str) – What kind of viewer to open, including ‘gl’ to open a pyglet window, ‘notebook’ for a jupyter notebook or None
kwargs (dict) – Includes smooth, which will turn on or off automatic smooth shading

property
triangles
¶ Return a correctly transformed polygon soup of the current scene.
 Returns
triangles
 Return type
(n,3,3) float, triangles in space

property
triangles_node
¶ Which node of self.graph does each triangle come from.
 Returns
triangles_index – Node name for each triangle
 Return type
(len(self.triangles),)

property
units
¶ Get the units for every model in the scene, and raise a ValueError if there are mixed units.
 Returns
units – Units for every model in the scene
 Return type
str


trimesh.scene.scene.
append_scenes
(iterable, common=['world'])¶ Concatenate multiple scene objects into one scene.
 Parameters
 Returns
result – Scene containing all geometry
 Return type

trimesh.scene.scene.
split_scene
(geometry)¶ Given a geometry, list of geometries, or a Scene return them as a single Scene object.
 Parameters
geometry (splittable) –
 Returns
scene
 Return type
trimesh.scene.transforms module¶

class
trimesh.scene.transforms.
EnforcedForest
(*args, **kwargs)¶ Bases:
networkx.classes.digraph.DiGraph
A subclass of networkx.DiGraph that will raise an error if an edge is added which would make the DiGraph not a forest or tree.

add_edge
(u, v, *args, **kwargs)¶ Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by providing a dictionary with key/value pairs. See examples below.
 Parameters
v (u,) – Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
attr_dict (dictionary, optional (default= no attributes)) – Dictionary of edge attributes. Key/value pairs will update existing data associated with the edge.
attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using keyword arguments.
See also
add_edges_from()
add a collection of edges
Notes
Adding an edge that already exists updates the edge data.
Many NetworkX algorithms designed for weighted graphs use as the edge weight a numerical value assigned to a keyword which by default is ‘weight’.
Examples
The following all add the edge e=(1,2) to graph G:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = (1,2) >>> G.add_edge(1, 2) # explicit twonode form >>> G.add_edge(*e) # single edge as tuple of two nodes >>> G.add_edges_from( [(1,2)] ) # add edges from iterable container
Associate data to edges using keywords:
>>> G.add_edge(1, 2, weight=3) >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)

add_edges_from
(*args, **kwargs)¶ Add all the edges in ebunch.
 Parameters
ebunch (container of edges) – Each edge given in the container will be added to the graph. The edges must be given as as 2tuples (u,v) or 3tuples (u,v,d) where d is a dictionary containing edge data.
attr_dict (dictionary, optional (default= no attributes)) – Dictionary of edge attributes. Key/value pairs will update existing data associated with each edge.
attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using keyword arguments.
See also
add_edge()
add a single edge
add_weighted_edges_from()
convenient way to add weighted edges
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in edges take precedence over attributes specified generally.
Examples
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0,1),(1,2)]) # using a list of edge tuples >>> e = zip(range(0,3),range(1,4)) >>> G.add_edges_from(e) # Add the path graph 0123
Associate data to edges
>>> G.add_edges_from([(1,2),(2,3)], weight=3) >>> G.add_edges_from([(3,4),(1,4)], label='WN2898')

add_path
(*args, **kwargs)¶ Add a path.
 Parameters
nodes (iterable container) – A container of nodes. A path will be constructed from the nodes (in order) and added to the graph.
attr (keyword arguments, optional (default= no attributes)) – Attributes to add to every edge in path.
See also
add_star()
,add_cycle()
Examples
>>> G=nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> G.add_path([10,11,12],weight=7)

disconnect_path
(path)¶

get_edge_data_direction
(u, v)¶

remove_edge
(*args, **kwargs)¶ Remove the edge between u and v.
 Parameters
v (u,) – Remove the edge between nodes u and v.
 Raises
NetworkXError – If there is not an edge between u and v.
See also
remove_edges_from()
remove a collection of edges
Examples
>>> G = nx.Graph() # or DiGraph, etc >>> G.add_path([0,1,2,3]) >>> G.remove_edge(0,1) >>> e = (1,2) >>> G.remove_edge(*e) # unpacks e from an edge tuple >>> e = (2,3,{'weight':7}) # an edge with attribute data >>> G.remove_edge(*e[:2]) # select first part of edge tuple

remove_edges_from
(*args, **kwargs)¶ Remove all edges specified in ebunch.
 Parameters
ebunch (list or container of edge tuples) –
Each edge given in the list or container will be removed from the graph. The edges can be:
2tuples (u,v) edge between u and v.
3tuples (u,v,k) where k is ignored.
See also
remove_edge()
remove a single edge
Notes
Will fail silently if an edge in ebunch is not in the graph.
Examples
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> ebunch=[(1,2),(2,3)] >>> G.remove_edges_from(ebunch)

shortest_path_undirected
(u, v)¶


class
trimesh.scene.transforms.
TransformForest
(base_frame='world')¶ Bases:
object

clear
()¶

copy
()¶ Return a copy of the current TransformForest
 Returns
copied
 Return type

from_edgelist
(edges, strict=True)¶ Load transform data from an edge list into the current scene graph.
 Parameters
edgelist ((n,) tuples) – (node_a, node_b, {key: value})
strict (bool) – If true, raise a ValueError when a malformed edge is passed in a tuple.

get
(frame_to, frame_from=None)¶ Get the transform from one frame to another, assuming they are connected in the transform tree.
If the frames are not connected a NetworkXNoPath error will be raised.
 Parameters
frame_to (hashable) – Node name, usually a string (eg ‘mesh_0’)
frame_from (hashable) – Node name, usually a string (eg ‘world’). If None it will be set to self.base_frame
 Returns
transform – Homogeneous transformation matrix
 Return type
(4, 4) float

load
(edgelist)¶ Load transform data from an edge list into the current scene graph.
 Parameters
edgelist ((n,) tuples) – (node_a, node_b, {key: value})

md5
()¶

property
nodes
¶ A list of every node in the graph.
 Returns
nodes
 Return type
(n,) array, of node names

property
nodes_geometry
¶ The nodes in the scene graph with geometry attached.
 Returns
nodes_geometry
 Return type
(m,) array, of node names

show
()¶ Plot the graph layout of the scene.

to_edgelist
()¶ Export the current transforms as a list of edge tuples, with each tuple having the format: (node_a, node_b, {metadata})
 Returns
edgelist
 Return type
(n,) list of tuples

to_flattened
(base_frame=None)¶ Export the current transform graph as a flattened

to_gltf
(scene)¶ Export a transforms as the ‘nodes’ section of a GLTF dict. Flattens tree.
 Returns
gltf – with ‘nodes’ referencing a list of dicts
 Return type
dict

to_svg
()¶

update
(frame_to, frame_from=None, **kwargs)¶ Update a transform in the tree.
 Parameters
frame_from (hashable object) – Usually a string (eg ‘world’). If left as None it will be set to self.base_frame
frame_to (hashable object) – Usually a string (eg ‘mesh_0’)
matrix ((4,4) float) – Homogeneous transformation matrix
quaternion ((4,) float) – Quaternion ordered [w, x, y, z]
axis ((3,) float) – Axis of rotation
angle (float) – Angle of rotation, in radians
translation ((3,) float) – Distance to translate
geometry (hashable) – Geometry object name, e.g. ‘mesh_0’


trimesh.scene.transforms.
kwargs_to_matrix
(**kwargs)¶ Turn a set of keyword arguments into a transformation matrix.