trimesh.path package

Submodules

trimesh.path.arc module

trimesh.path.arc.arc_center(points)

Given three points on an arc find: center, radius, normal, and angle.

This uses the fact that the intersection of the perp bisectors of the segments between the control points is the center of the arc.

Parameters

points ((3, dimension) float) – Points in space, where dimension is either 2 or 3

Returns

result

Has keys:

’center’: (d,) float, cartesian center of the arc ‘radius’: float, radius of the arc ‘normal’: (3,) float, the plane normal. ‘angle’: (2,) float, angle of start and end, in radians ‘span’ : float, angle swept by the arc, in radians

Return type

dict

trimesh.path.arc.discretize_arc(points, close=False, scale=1.0)

Returns a version of a three point arc consisting of line segments.

Parameters
  • points ((3, d) float) – Points on the arc where d in [2,3]

  • close (boolean) – If True close the arc into a circle

  • scale (float) – What is the approximate overall drawing scale Used to establish order of magnitude for precision

Returns

discrete – Connected points in space

Return type

(m, d) float

trimesh.path.arc.to_threepoint(center, radius, angles=None)

For 2D arcs, given a center and radius convert them to three points on the arc.

Parameters
  • center ((2,) float) – Center point on the plane

  • radius (float) – Radius of arc

  • angles ((2,) float) – Angles in radians for start and end angle if not specified, will default to (0.0, pi)

Returns

three – Arc control points

Return type

(3, 2) float

trimesh.path.creation module

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

Return a cuboid.

Parameters
  • extents (float, or (3,) float) – Edge lengths

  • transform ((4, 4) float) – Transformation matrix

  • **kwargs – passed to Trimesh to create box

Returns

geometry – Path outline of a cuboid geometry

Return type

trimesh.Path3D

trimesh.path.creation.circle(radius=None, center=None, **kwargs)

Create a Path2D containing a single or multiple rectangles with the specified bounds.

Parameters

bounds ((2, 2) float, or (m, 2, 2) float) – Minimum XY, Maximum XY

Returns

rect – Path containing specified rectangles

Return type

Path2D

trimesh.path.creation.circle_pattern(pattern_radius, circle_radius, count, center=[0.0, 0.0], angle=None, **kwargs)

Create a Path2D representing a circle pattern.

Parameters
  • pattern_radius (float) – Radius of circle centers

  • circle_radius (float) – The radius of each circle

  • count (int) – Number of circles in the pattern

  • center ((2,) float) – Center of pattern

  • angle (float) – If defined pattern will span this angle If None, pattern will be evenly spaced

Returns

pattern – Path containing circular pattern

Return type

trimesh.path.Path2D

trimesh.path.creation.rectangle(bounds, **kwargs)

Create a Path2D containing a single or multiple rectangles with the specified bounds.

Parameters

bounds ((2, 2) float, or (m, 2, 2) float) – Minimum XY, Maximum XY

Returns

rect – Path containing specified rectangles

Return type

Path2D

trimesh.path.curve module

trimesh.path.curve.binomial(n)

Return all binomial coefficients for a given order.

For n > 5, scipy.special.binom is used, below we hardcode to avoid the scipy.special dependency.

Parameters

n (int) – Order

Returns

binom – Binomial coefficients of a given order

Return type

(n + 1,) int

trimesh.path.curve.discretize_bezier(points, count=None, scale=1.0)
Parameters
  • points ((order, dimension) float) – Control points of the bezier curve For a 2D cubic bezier, order=3, dimension=2

  • count (int, or None) – Number of segments

  • scale (float) – Scale of curve

Returns

discrete – of the bezier curve which respects constants.RES_LENGTH

Return type

(n,d) list of points, a polyline representation

trimesh.path.curve.discretize_bspline(control, knots, count=None, scale=1.0)

Given a B-Splines control points and knot vector, return a sampled version of the curve.

Parameters
  • control ((o, d) float) – Control points of the b- spline

  • knots ((j,) float) – B-spline knots

  • count (int) – Number of line segments to discretize the spline If not specified will be calculated as something reasonable

Returns

discrete – Points on a polyline version of the B-spline

Return type

(count, dimension) float

trimesh.path.entities module

entities.py

Basic geometric primitives which only store references to vertex indices rather than vertices themselves.

class trimesh.path.entities.Arc(points, closed=None, layer=None, **kwargs)

Bases: trimesh.path.entities.Entity

bounds(vertices)

Return the AABB of the arc entity.

Parameters

vertices ((n, dimension) float) – Vertices in space

Returns

bounds – Coordinates of AABB in (min, max) form

Return type

(2, dimension) float

center(vertices)

Return the center information about the arc entity.

Parameters

vertices ((n, dimension) float) – Vertices in space

Returns

info – With keys: ‘radius’, ‘center’

Return type

dict

property closed

A boolean flag for whether the arc is closed (a circle) or not.

Returns

closed – If set True, Arc will be a closed circle

Return type

bool

discrete(vertices, scale=1.0)

Discretize the arc entity into line sections.

Parameters
  • vertices ((n, dimension) float) – Points in space

  • scale (float) – Size of overall scene for numerical comparisons

Returns

discrete – Path in space made up of line segments

Return type

(m, dimension) float

property is_valid

Is the current Arc entity valid.

Returns

valid – Does the current Arc have exactly 3 control points

Return type

bool

class trimesh.path.entities.BSpline(points, knots, closed=None, layer=None, **kwargs)

Bases: trimesh.path.entities.Curve

An open or closed B- Spline.

discrete(vertices, count=None, scale=1.0)

Discretize the B-Spline curve.

Parameters
  • vertices ((n, 2) or (n, 3) float) – Points in space

  • scale (float) – Scale of overall drawings (for precision)

  • count (int) – Number of segments to return

Returns

discrete – Curve as line segments

Return type

(m, 2) or (m, 3) float

to_dict()

Returns a dictionary with all of the information about the entity.

class trimesh.path.entities.Bezier(points, closed=None, layer=None, **kwargs)

Bases: trimesh.path.entities.Curve

An open or closed Bezier curve

discrete(vertices, scale=1.0, count=None)

Discretize the Bezier curve.

Parameters
  • vertices ((n, 2) or (n, 3) float) – Points in space

  • scale (float) – Scale of overall drawings (for precision)

  • count (int) – Number of segments to return

Returns

discrete – Curve as line segments

Return type

(m, 2) or (m, 3) float

class trimesh.path.entities.Curve(points, closed=None, layer=None, **kwargs)

Bases: trimesh.path.entities.Entity

The parent class for all wild curves in space.

property nodes

Returns an (n,2) list of nodes, or vertices on the path. Note that this generic class function assumes that all of the reference points are on the path which is true for lines and three point arcs.

If you were to define another class where that wasn’t the case (for example, the control points of a bezier curve), you would need to implement an entity- specific version of this function.

The purpose of having a list of nodes is so that they can then be added as edges to a graph so we can use functions to check connectivity, extract paths, etc.

The slicing on this function is essentially just tiling points so the first and last vertices aren’t repeated. Example:

self.points = [0,1,2] returns: [[0,1], [1,2]]

class trimesh.path.entities.Entity(points, closed=None, layer=None, **kwargs)

Bases: object

bounds(vertices)

Return the AABB of the current entity.

Parameters

vertices ((n, dimension) float) – Vertices in space

Returns

bounds – Coordinates of AABB, in (min, max) form

Return type

(2, dimension) float

property closed

If the first point is the same as the end point the entity is closed

Returns

closed – Is the entity closed or not?

Return type

bool

copy()

Return a copy of the current entity.

Returns

copied – Copy of current entity

Return type

Entity

property end_points

Returns the first and last points. Also note that if you define a new entity class where the first and last vertices in self.points aren’t the endpoints of the curve you need to implement this function for your class.

Returns

ends – Indices of the two end points of the entity

Return type

(2,) int

explode()

Split the entity into multiple entities.

Returns

explode – Current entity split into multiple entities if necessary

Return type

list of Entity

property is_valid

Is the current entity valid.

Returns

valid – Is the current entity well formed

Return type

bool

length(vertices)

Return the total length of the entity.

Parameters

vertices ((n, dimension) float) – Vertices in space

Returns

length – Total length of entity

Return type

float

property nodes

Returns an (n,2) list of nodes, or vertices on the path. Note that this generic class function assumes that all of the reference points are on the path which is true for lines and three point arcs.

If you were to define another class where that wasn’t the case (for example, the control points of a bezier curve), you would need to implement an entity- specific version of this function.

The purpose of having a list of nodes is so that they can then be added as edges to a graph so we can use functions to check connectivity, extract paths, etc.

The slicing on this function is essentially just tiling points so the first and last vertices aren’t repeated. Example:

self.points = [0,1,2] returns: [[0,1], [1,2]]

reverse(direction=-1)

Reverse the current entity in place.

Parameters

direction (int) – If positive will not touch direction If negative will reverse self.points

to_dict()

Returns a dictionary with all of the information about the entity.

Returns

as_dict – Has keys ‘type’, ‘points’, ‘closed’

Return type

dict

class trimesh.path.entities.Line(points, closed=None, layer=None, **kwargs)

Bases: trimesh.path.entities.Entity

A line or poly-line entity

discrete(vertices, scale=1.0)

Discretize into a world- space path.

Parameters
  • vertices ((n, dimension) float) – Points in space

  • scale (float) – Size of overall scene for numerical comparisons

Returns

discrete – Path in space composed of line segments

Return type

(m, dimension) float

explode()

If the current Line entity consists of multiple line break it up into n Line entities.

Returns

exploded

Return type

(n,) Line entities

property is_valid

Is the current entity valid.

Returns

valid – Is the current entity well formed

Return type

bool

class trimesh.path.entities.Text(origin, text, height=None, vector=None, normal=None, align=None)

Bases: trimesh.path.entities.Entity

Text to annotate a 2D or 3D path.

angle(vertices)

If Text is 2D, get the rotation angle in radians.

Parameters

vertices ((n, 2) float) – Vertices in space referenced by self.points

Returns

angle – Rotation angle in radians

Return type

float

property closed

If the first point is the same as the end point the entity is closed

Returns

closed – Is the entity closed or not?

Return type

bool

discrete(*args, **kwargs)
property end_points

Returns the first and last points. Also note that if you define a new entity class where the first and last vertices in self.points aren’t the endpoints of the curve you need to implement this function for your class.

Returns

ends – Indices of the two end points of the entity

Return type

(2,) int

property is_valid

Is the current entity valid.

Returns

valid – Is the current entity well formed

Return type

bool

length(vertices)

Return the total length of the entity.

Parameters

vertices ((n, dimension) float) – Vertices in space

Returns

length – Total length of entity

Return type

float

property nodes

Returns an (n,2) list of nodes, or vertices on the path. Note that this generic class function assumes that all of the reference points are on the path which is true for lines and three point arcs.

If you were to define another class where that wasn’t the case (for example, the control points of a bezier curve), you would need to implement an entity- specific version of this function.

The purpose of having a list of nodes is so that they can then be added as edges to a graph so we can use functions to check connectivity, extract paths, etc.

The slicing on this function is essentially just tiling points so the first and last vertices aren’t repeated. Example:

self.points = [0,1,2] returns: [[0,1], [1,2]]

property normal

A point representing the plane normal along the vector: vertices[normal] - vertices[origin]

Returns

normal – Index of vertex

Return type

int

property origin

The origin point of the text.

Returns

origin – Index of vertices

Return type

int

plot(vertices, show=False)

Plot the text using matplotlib.

Parameters
  • vertices ((n, 2) float) – Vertices in space

  • show (bool) – If True, call plt.show()

property vector

A point representing the text direction along the vector: vertices[vector] - vertices[origin]

Returns

vector – Index of vertex

Return type

int

trimesh.path.intersections module

trimesh.path.intersections.line_line(origins, directions, plane_normal=None)

Find the intersection between two lines. Uses terminology from: http://geomalgorithms.com/a05-_intersect-1.html

line 1: P(s) = p_0 + sU line 2: Q(t) = q_0 + tV

Parameters
  • origins ((2, d) float, points on lines (d in [2,3])) –

  • directions ((2, d) float, direction vectors) –

  • plane_normal ((3, ) float, if not passed computed from cross) –

Returns

  • intersects (boolean, whether the lines intersect.) – In 2D, false if the lines are parallel In 3D, false if lines are not coplanar

  • intersection (if intersects: (d) length point of intersection) – else: None

trimesh.path.packing module

class trimesh.path.packing.RectangleBin(bounds=None, size=None)

Bases: object

2D BSP tree node. http://www.blackpawn.com/texts/lightmaps/

property extents

Bounding box size.

Returns

extents

Return type

(2,) float, edge lengths of bounding box

insert(rectangle)

Insert a rectangle into the bin.

Parameters

rectangle ((2,) float, size of rectangle to insert) –

split(length, vertical=True)

Returns two bounding boxes representing the current bounds split into two smaller boxes.

Parameters
  • length (float, length to split) –

  • vertical (bool, if True will split box vertically) –

Returns

box – [minx, miny, maxx, maxy]

Return type

(2,4) float, two bounding boxes consisting of:

trimesh.path.packing.multipack(polygons, sheet_size=None, iterations=50, density_escape=0.95, spacing=0.094, quantity=None)

Pack polygons into a rectangle by taking each Polygon’s OBB and then packing that as a rectangle.

Parameters
  • polygons ((n,) shapely.geometry.Polygon) – Source geometry

  • sheet_size ((2,) float) – Size of rectangular sheet

  • iterations (int) – Number of times to run the loop

  • density_escape (float) – When to exit early (0.0 - 1.0)

  • spacing (float) – How big a gap to leave between polygons

  • quantity ((n,) int, or None) – Quantity of each Polygon

Returns

  • overall_inserted ((m,) int) – Indexes of inserted polygons

  • packed ((m, 3, 3) float) – Homogeonous transforms from original frame to packed frame

trimesh.path.packing.pack_paths(paths, sheet_size=None)

Pack a list of Path2D objects into a rectangle.

Parameters

paths ((n,) Path2D) – Geometry to be packed

Returns

  • packed (trimesh.path.Path2D) – Object containing input geometry

  • inserted ((m,) int) – Indexes of paths inserted into result

trimesh.path.packing.pack_rectangles(rectangles, sheet_size, shuffle=False)

Pack smaller rectangles onto a larger rectangle, using a binary space partition tree.

Parameters
  • rectangles ((n, 2) float) – An array of (width, height) pairs representing the rectangles to be packed.

  • sheet_size ((2,) float) – Width, height of rectangular sheet

  • shuffle (bool) – Whether or not to shuffle the insert order of the smaller rectangles, as the final packing density depends on insertion order.

Returns

  • density (float) – Area filled over total sheet area

  • offset ((m,2) float) – Offsets to move rectangles to their packed location

  • inserted ((n,) bool) – Which of the original rectangles were packed

  • consumed_box ((2,) float) – Bounding box size of packed result

trimesh.path.path module

path.py

A library designed to work with vector paths.

class trimesh.path.path.Path(entities=None, vertices=None, metadata=None, process=True)

Bases: object

A Path object consists of:

vertices: (n,[2|3]) coordinates, stored in self.vertices

entities: geometric primitives (aka Lines, Arcs, etc.)

that reference indexes in self.vertices

apply_layer(name)

Apply a layer name to every entity in the path.

Parameters

name (str) – Apply layer name to every entity

apply_scale(scale)

Apply a transformation matrix to the current path in- place

Parameters

scale (float or (3,) float) – Scale to be applied to mesh

apply_transform(transform)

Apply a transformation matrix to the current path in- place

Parameters

transform ((d+1, d+1) float) – Homogeneous transformation for vertices

apply_translation(offset)

Apply a transformation matrix to the current path in- place

Parameters

offset (float or (3,) float) – Translation to be applied to mesh

property bounds

Return the axis aligned bounding box of the current path.

Returns

bounds

Return type

(2, dimension) float, (min, max) coordinates

convert_units(desired, guess=False)

Convert the units of the current drawing in place.

Parameters
  • desired (str, unit system to convert to) –

  • guess (bool, if True will attempt to guess units) –

copy()

Get a copy of the current mesh

Returns

copied

Return type

Path object, copy of self

crc()

A CRC of the current vertices and entities.

Returns

crc

Return type

int, CRC of entity points and vertices

property dangling

List of entities that aren’t included in a closed path

Returns

dangling

Return type

(n,) int, index of self.entities

property discrete

A sequence of connected vertices in space, corresponding to self.paths.

Returns

discrete – A sequence of (m*, dimension) float

Return type

(len(self.paths),)

discretize_path(path)

Given a list of entities, return a list of connected points.

Parameters

path ((n,) int, indexes of self.entities) –

Returns

discrete

Return type

(m, dimension)

property entities
explode()

Turn every multi- segment entity into single segment entities in- place.

export(file_obj=None, file_type=None, **kwargs)

Export the path to a file object or return data.

Parameters
  • file_obj (None, str, or file object) – File object or string to export to

  • file_type (None or str) – Type of file: dxf, dict, svg

Returns

exported – Exported as specified type

Return type

bytes or str

property extents

The size of the axis aligned bounding box.

Returns

extents

Return type

(dimension,) float, edge length of AABB

fill_gaps(distance=0.025)

Find vertices without degree 2 and try to connect to other vertices. Operations are done in-place.

Parameters

distance (float) – Connect vertices up to this distance

property is_closed

Are all entities connected to other entities.

Returns

closed – Every entity is connected at its ends

Return type

bool

property is_empty

Are any entities defined for the current path.

Returns

empty – True if no entities are defined

Return type

bool

property kdtree

A KDTree object holding the vertices of the path.

Returns

kdtree

Return type

scipy.spatial.cKDTree object holding self.vertices

property layers

If entities have a layer defined, return it.

Returns

layers

Return type

(len(entities), ) list of str

md5()

An MD5 hash of the current vertices and entities.

Returns

md5

Return type

str, two appended MD5 hashes

merge_vertices(digits=None)

Merges vertices which are identical and replace references.

Parameters
  • digits (None, or int) – How many digits to consider when merging vertices

  • Alters

  • -----------

  • self.entities (entity.points re- referenced) –

  • self.vertices (duplicates removed) –

property paths

Sequence of closed paths, encoded by entity index.

Returns

paths

Return type

(n,) sequence of (*,) int referencing self.entities

process()

Apply basic cleaning functions to the Path object, in- place.

property referenced_vertices

Which vertices are referenced by an entity.

Returns

referenced_vertices

Return type

(n,) int, indexes of self.vertices

remove_duplicate_entities()

Remove entities that are duplicated

self.entities: length same or shorter

remove_entities(entity_ids)

Remove entities by index.

Parameters

entity_ids ((n,) int) – Indexes of self.entities to remove

remove_invalid()

Remove entities which declare themselves invalid

self.entities: shortened

remove_unreferenced_vertices()

Removes all vertices which aren’t used by an entity.

self.vertices: reordered and shortened self.entities: entity.points references updated

replace_vertex_references(mask)

Replace the vertex index references in every entity.

Parameters
  • mask ((len(self.vertices), ) int) – Contains new vertex indexes

  • Alters

  • ------------

  • in self.entities (entity.points) – Replaced by mask[entity.points]

rezero()

Translate so that every vertex is positive in the current mesh is positive.

Returns

matrix – Homogeneous transformation that was applied to the current Path object.

Return type

(dimension + 1, dimension + 1) float

property scale

What is a representitive number that reflects the magnitude of the world holding the paths, for numerical comparisons.

Returns

scale – Approximate size of the world holding this path

Return type

float

scene()

Get a scene object containing the current Path3D object.

Returns

scene

Return type

trimesh.scene.Scene object containing current path

to_dict()
property units

If there are units defined in self.metadata return them.

Returns

units

Return type

str, current unit system

property vertex_graph

Return a networkx.Graph object for the entity connectiviy

graphnetworkx.Graph

Holds vertex indexes

property vertex_nodes

Get a list of which vertex indices are nodes, which are either endpoints or points where the entity makes a direction change.

Returns

nodes – Indexes of self.vertices which are nodes

Return type

(n, 2) int

property vertices
class trimesh.path.path.Path2D(entities=None, vertices=None, metadata=None, process=True)

Bases: trimesh.path.path.Path

apply_obb()

Transform the current path so that its OBB is axis aligned and OBB center is at the origin.

Returns

obb – Homogeneous transformation matrix

Return type

(3, 3) float

property area

Return the area of the polygons interior.

Returns

area

Return type

float, total area of polygons minus interiors

property body_count
property centroid

Return the centroid of the path object.

Returns

centroid – Approximate centroid of the path

Return type

(d,) float

connected_paths(path_id, include_self=False)

Given an index of self.paths find other paths which overlap with that path.

Parameters
  • path_id (int) – Index of self.paths

  • include_self (bool) – Should the result include path_id or not

Returns

path_ids – Indexes of self.paths that overlap input path_id

Return type

(n, ) int

property enclosure

Networkx Graph object of polygon enclosure.

property enclosure_directed

Networkx DiGraph of polygon enclosure

property enclosure_shell

A dictionary of path indexes which are ‘shell’ paths, and values of ‘hole’ paths.

Returns

corresponding

Return type

dict, {index of self.paths of shell : [indexes of holes]}

extrude(height, **kwargs)

Extrude the current 2D path into a 3D mesh.

Parameters
  • height (float, how far to extrude the profile) –

  • kwargs (passed directly to meshpy.triangle.build:) –

    triangle.build(mesh_info,

    verbose=False, refinement_func=None, attributes=False, volume_constraints=True, max_volume=None, allow_boundary_steiner=True, allow_volume_steiner=True, quality_meshing=True, generate_edges=None, generate_faces=False, min_angle=None)

Returns

mesh

Return type

trimesh object representing extruded polygon

property identifier

A unique identifier for the path.

Returns

identifier

Return type

(5,) float, unique identifier

property identifier_md5

Return an MD5 of the identifier

property length

The total discretized length of every entity.

Returns

length

Return type

float, summed length of every entity

medial_axis(resolution=None, clip=None)

Find the approximate medial axis based on a voronoi diagram of evenly spaced points on the boundary of the polygon.

Parameters
  • resolution (None or float) – Distance between each sample on the polygon boundary

  • clip (None, or (2,) float) – Min, max number of samples

Returns

medial – Contains only medial axis of Path

Return type

Path2D object

property obb

Get a transform that centers and aligns the OBB of the referenced vertices with the XY axis.

Returns

obb – Homogeneous transformation matrix

Return type

(3, 3) float

property path_valid
Returns

path_valid – which are valid polygons

Return type

(n,) bool, indexes of self.paths self.polygons_closed

plot_discrete(show=False, annotations=True)

Plot the closed curves of the path.

plot_entities(show=False, annotations=True, color=None)

Plot the entities of the path, with no notion of topology

property polygons_closed

Cycles in the vertex graph, as shapely.geometry.Polygons. These are polygon objects for every closed circuit, with no notion of whether a polygon is a hole or an area. Every polygon in this list will have an exterior, but NO interiors.

Returns

polygons_closed

Return type

(n,) list of shapely.geometry.Polygon objects

property polygons_full

A list of shapely.geometry.Polygon objects with interiors created by checking which closed polygons enclose which other polygons.

Returns

full – Polygons containing interiors

Return type

(len(self.root),) shapely.geometry.Polygon

rasterize(pitch, origin, resolution=None, fill=True, width=None, **kwargs)

Rasterize a Path2D object into a boolean image (“mode 1”).

Parameters
  • pitch (float, length in model space of a pixel edge) –

  • origin ((2,) float, origin position in model space) –

  • resolution ((2,) int, resolution in pixel space) –

  • fill (bool, if True will return closed regions as filled) –

  • width (int, if not None will draw outline this wide (pixels)) –

Returns

raster

Return type

PIL.Image object, mode 1

property root

Which indexes of self.paths/self.polygons_closed are root curves. Also known as ‘shell’ or ‘exterior.

Returns

root

Return type

(n,) int, list of indexes

sample(count, **kwargs)

Use rejection sampling to generate random points inside a polygon.

Parameters
  • count (int) – Number of points to return If there are multiple bodies, there will be up to count * bodies points returned

  • factor (float) – How many points to test per loop IE, count * factor

  • max_iter (int,) – Maximum number of intersection loops to run, total points sampled is count * factor * max_iter

Returns

hit – Random points inside polygon

Return type

(n, 2) float

show(annotations=True)

Plot the current Path2D object using matplotlib.

simplify(**kwargs)

Return a version of the current path with colinear segments merged, and circles entities replacing segmented circular paths.

Returns

simplified

Return type

Path2D object

simplify_spline(smooth=0.0002, verbose=False)

Convert paths into b-splines.

Parameters
  • smooth (float) – How much the spline should smooth the curve

  • verbose (bool) – Print detailed log messages

Returns

simplified – Discrete curves replaced with splines

Return type

Path2D

split()

If the current Path2D consists of n ‘root’ curves, split them into a list of n Path2D objects

Returns

split – Each connected region and interiors

Return type

(n,) list of Path2D objects

to_3D(transform=None)

Convert 2D path to 3D path on the XY plane.

Parameters

transform ((4, 4) float) – If passed, will transform vertices. If not passed and ‘to_3D’ is in metadata that transform will be used.

Returns

path_3D

Return type

Path3D version of current path

triangulate(**kwargs)

Create a region- aware triangulation of the 2D path.

Parameters

**kwargs (dict) – Passed to trimesh.creation.triangulate_polygon

Returns

  • vertices ((n, 2) float) – 2D vertices of triangulation

  • faces ((n, 3) int) – Indexes of vertices for triangles

class trimesh.path.path.Path3D(entities=None, vertices=None, metadata=None, process=True)

Bases: trimesh.path.path.Path

plot_discrete(show=False)

Plot closed curves

Parameters

show (bool) – If False will not execute matplotlib.pyplot.show

plot_entities(show=False)

Plot discrete version of entities without regards for connectivity.

Parameters

show (bool) – If False will not execute matplotlib.pyplot.show

show(**kwargs)

Show the current Path3D object.

to_planar(to_2D=None, normal=None, check=True)

Check to see if current vectors are all coplanar.

If they are, return a Path2D and a transform which will transform the 2D representation back into 3 dimensions

Parameters
  • to_2D ((4,4) float) – Homogeneous transformation matrix to apply, If not passed a plane will be fitted to vertices.

  • normal ((3,) float, or None) – Approximate normal of direction of plane If to_2D is not specified sign will be applied to fit plane normal

  • check (bool) – If True: Raise a ValueError if points aren’t coplanar

Returns

  • planar (trimesh.path.Path2D) – Current path transformed onto plane

  • to_3D ((4,4) float) – Homeogenous transformation to move planar back into 3D space

trimesh.path.polygons module

trimesh.path.polygons.edges_to_polygons(edges, vertices)

Given an edge list of indices and associated vertices representing lines, generate a list of polygons.

Parameters
  • edges ((n, 2) int) – Indexes of vertices which represent lines

  • vertices ((m, 2) float) – Vertices in 2D space

Returns

polygons – Polygon objects with interiors

Return type

(p,) shapely.geometry.Polygon

trimesh.path.polygons.enclosure_tree(polygons)

Given a list of shapely polygons with only exteriors, find which curves represent the exterior shell or root curve and which represent holes which penetrate the exterior.

This is done with an R-tree for rough overlap detection, and then exact polygon queries for a final result.

Parameters

polygons ((n,) shapely.geometry.Polygon) – Polygons which only have exteriors and may overlap

Returns

  • roots ((m,) int) – Index of polygons which are root

  • contains (networkx.DiGraph) – Edges indicate a polygon is contained by another polygon

trimesh.path.polygons.medial_axis(polygon, resolution=None, clip=None)

Given a shapely polygon, find the approximate medial axis using a voronoi diagram of evenly spaced points on the boundary of the polygon.

Parameters
  • polygon (shapely.geometry.Polygon) – The source geometry

  • resolution (float) – Distance between each sample on the polygon boundary

  • clip (None, or (2,) int) – Clip sample count to min of clip[0] and max of clip[1]

Returns

  • edges ((n, 2) int) – Vertex indices representing line segments on the polygon’s medial axis

  • vertices ((m, 2) float) – Vertex positions in space

trimesh.path.polygons.paths_to_polygons(paths, scale=None)

Given a sequence of connected points turn them into valid shapely Polygon objects.

Parameters
  • paths ((n,) sequence) – Of (m,2) float, closed paths

  • scale (float) – Approximate scale of drawing for precision

Returns

polys – shapely.geometry.Polygon None

Return type

(p,) list

trimesh.path.polygons.plot_polygon(polygon, show=True, **kwargs)

Plot a shapely polygon using matplotlib.

Parameters
  • polygon (shapely.geometry.Polygon) – Polygon to be plotted

  • show (bool) – If True will display immediately

  • **kwargs – Passed to plt.plot

trimesh.path.polygons.polygon_hash(polygon)

Return a vector containing values representitive of a particular polygon.

Parameters

polygon (shapely.geometry.Polygon) – Input geometry

Returns

hashed – Representitive values representing input polygon

Return type

(6), float

trimesh.path.polygons.polygon_obb(polygon)

Find the oriented bounding box of a Shapely polygon.

The OBB is always aligned with an edge of the convex hull of the polygon.

Parameters

polygons (shapely.geometry.Polygon) –

Returns

  • transform ((3,3) float, transformation matrix) – which will move input polygon from its original position to the first quadrant where the AABB is the OBB

  • extents ((2,) float, extents of transformed polygon)

trimesh.path.polygons.polygon_scale(polygon)

For a Polygon object, return the diagonal length of the AABB.

Parameters

polygon (shapely.geometry.Polygon object) –

Returns

scale

Return type

float, length of AABB diagonal

trimesh.path.polygons.polygons_obb(polygons)

Find the OBBs for a list of shapely.geometry.Polygons

trimesh.path.polygons.random_polygon(segments=8, radius=1.0)

Generate a random polygon with a maximum number of sides and approximate radius.

Parameters
  • segments (int, the maximum number of sides the random polygon will have) –

  • radius (float, the approximate radius of the polygon desired) –

Returns

polygon

Return type

shapely.geometry.Polygon object with random exterior, and no interiors.

trimesh.path.polygons.repair_invalid(polygon, scale=None, rtol=0.5)

Given a shapely.geometry.Polygon, attempt to return a valid version of the polygon through buffering tricks.

Parameters
  • polygon (shapely.geometry.Polygon object) –

  • rtol (float, how close does a perimeter have to be) –

  • scale (float, or None) –

Returns

repaired

Return type

shapely.geometry.Polygon object

Raises

ValueError – if polygon can’t be repaired:

trimesh.path.polygons.resample_boundaries(polygon, resolution, clip=None)

Return a version of a polygon with boundaries resampled to a specified resolution.

Parameters
  • polygon (shapely.geometry.Polygon object) –

  • resolution (float, desired distance between points on boundary) –

  • clip ((2,) int, upper and lower bounds to clip) – number of samples to (to avoid exploding counts)

Returns

kwargs

Return type

dict, keyword args for a Polygon(**kwargs)

trimesh.path.polygons.sample(polygon, count, factor=1.5, max_iter=10)

Use rejection sampling to generate random points inside a polygon.

Parameters
  • polygon (shapely.geometry.Polygon) – Polygon that will contain points

  • count (int) – Number of points to return

  • factor (float) – How many points to test per loop IE, count * factor

  • max_iter (int,) – Maximum number of intersection loops to run, total points sampled is count * factor * max_iter

Returns

hit – Random points inside polygon where n <= count

Return type

(n, 2) float

trimesh.path.polygons.stack_boundaries(boundaries)

Stack the boundaries of a polygon into a single (n, 2) list of vertices.

Parameters

boundaries (dict, with keys 'shell', 'holes') –

Returns

stacked

Return type

(n, 2) float, list of vertices

trimesh.path.polygons.transform_polygon(polygon, matrix)

Transform a polygon by a a 2D homogeneous transform.

Parameters
  • polygon (shapely.geometry.Polygon) – 2D polygon to be transformed.

  • matrix ((3, 3) float) – 2D homogeneous transformation.

Returns

result – Polygon transformed by matrix.

Return type

shapely.geometry.Polygon

trimesh.path.raster module

raster.py

Turn 2D vector paths into raster images, using pillow

trimesh.path.raster.rasterize(path, pitch, origin, resolution=None, fill=True, width=None)

Rasterize a Path2D object into a boolean image (“mode 1”).

Parameters
  • path (Path2D object) –

  • pitch (float, length in model space of a pixel edge) –

  • origin ((2,) float, origin position in model space) –

  • resolution ((2,) int, resolution in pixel space) –

  • fill (bool, if True will return closed regions as filled) –

  • width (int, if not None will draw outline this wide (pixels)) –

Returns

raster

Return type

PIL.Image object, mode 1

trimesh.path.repair module

repair.py

Try to fix problems with closed regions.

trimesh.path.repair.fill_gaps(path, distance=0.025)

For 3D line segments defined by two points, turn them in to an origin defined as the closest point along the line to the zero origin as well as a direction vector and start and end parameter.

Parameters

segments ((n, 2, 3) float) – Line segments defined by start and end points

Returns

  • origins ((n, 3) float) – Point on line closest to [0, 0, 0]

  • vectors ((n, 3) float) – Unit line directions

  • parameters ((n, 2) float) – Start and end distance pairs for each line

trimesh.path.segments module

segments.py

Deal with (n, 2, 3) line segments.

trimesh.path.segments.colinear_pairs(segments, radius=0.01, angle=0.01, length=None)

Find pairs of segments which are colinear.

Parameters
  • segments ((n, 2, (2, 3)) float) – Two or three dimensional line segments

  • radius (float) – Maximum radius line origins can differ and be considered colinear

  • angle (float) – Maximum angle in radians segments can differ and still be considered colinear

  • length (None or float) – If specified, will additionally require that pairs have a mean vertex distance less than this value from each other to qualify.

Returns

pairs – Indexes of segments which are colinear

Return type

(m, 2) int

trimesh.path.segments.overlap(origins, vectors, params)

Find the overlap of two parallel line segments.

Parameters
  • origins ((2, 3) float) – Origin points of lines in space

  • vectors ((2, 3) float) – Unit direction vectors of lines

  • params ((2, 2) float) – Two (start, end) distance pairs

Returns

  • length (float) – Overlapping length

  • overlap ((n, 2, 3) float) – Line segments for overlapping distance

trimesh.path.segments.parameters_to_segments(origins, vectors, parameters)

Convert a parametric line segment representation to a two point line segment representation

Parameters
  • origins ((n, 3) float) – Line origin point

  • vectors ((n, 3) float) – Unit line directions

  • parameters ((n, 2) float) – Start and end distance pairs for each line

Returns

segments – Line segments defined by start and end points

Return type

(n, 2, 3) float

trimesh.path.segments.segments_to_parameters(segments)

For 3D line segments defined by two points, turn them in to an origin defined as the closest point along the line to the zero origin as well as a direction vector and start and end parameter.

Parameters

segments ((n, 2, 3) float) – Line segments defined by start and end points

Returns

  • origins ((n, 3) float) – Point on line closest to [0, 0, 0]

  • vectors ((n, 3) float) – Unit line directions

  • parameters ((n, 2) float) – Start and end distance pairs for each line

trimesh.path.segments.split(segments, points, atol=1e-05)

Find any points that lie on a segment (not an endpoint) and then split that segment into two segments.

We are basically going to find the distance between point and both segment vertex, and see if it is with tolerance of the segment length.

Parameters
  • segments ((n, 2, (2, 3) float) – Line segments in space

  • points ((n, (2, 3)) float) – Points in space

  • atol (float) – Absolute tolerance for distances

Returns

split – Line segments in space, split at vertices

Return type

(n, 2, (3 | 3) float

trimesh.path.segments.unique(segments, digits=5)

Find unique line segments.

Parameters
  • segments ((n, 2, (2|3)) float) – Line segments in space

  • digits (int) – How many digits to consider when merging vertices

Returns

unique – Segments with duplicates merged

Return type

(m, 2, (2|3)) float

trimesh.path.simplify module

trimesh.path.simplify.fit_circle_check(points, scale, prior=None, final=False, verbose=False)

Fit a circle, and reject the fit if: * the radius is larger than tol.radius_min*scale or tol.radius_max*scale * any segment spans more than tol.seg_angle * any segment is longer than tol.seg_frac*scale * the fit deviates by more than tol.radius_frac*radius * the segments on the ends deviate from tangent by more than tol.tangent

Parameters
  • points ((n, d) set of points which represent a path) –

  • prior ((center, radius) tuple for best guess, or None if unknown) –

  • scale (float, what is the overall scale of the set of points) –

  • verbose (boolean, if True output log.debug messages for the reasons) – for fit rejection. Potentially generates hundreds of thousands of messages so only suggested in manual debugging.

Returns

  • if fit is acceptable – (center, radius) tuple

  • else – None

trimesh.path.simplify.is_circle(points, scale, verbose=False)

Given a set of points, quickly determine if they represent a circle or not.

Parameters
  • points ((n,2) float, points in space) –

  • scale (float, scale of overall drawing) –

  • verbose (bool, print all fit messages or not) –

Returns

control – None, if not a circle

Return type

(3,2) float, points in space, OR

trimesh.path.simplify.merge_colinear(points, scale)

Given a set of points representing a path in space, merge points which are colinear.

Parameters
  • points ((n, d) set of points (where d is dimension)) –

  • scale (float, scale of drawing) –

Returns

merged – points merged, where (j < n)

Return type

(j, d) set of points with colinear and duplicate

trimesh.path.simplify.points_to_spline_entity(points, smooth=None, count=None)

Create a spline entity from a curve in space

Parameters
  • points ((n, dimension) float, points in space) –

  • smooth (float, smoothing amount) –

  • count (int, number of samples in result) –

Returns

  • entity (entities.BSpline object with points indexed at zero)

  • control ((m, dimension) float, new vertices for entity)

trimesh.path.simplify.resample_spline(points, smooth=0.001, count=None, degree=3)

Resample a path in space, smoothing along a b-spline.

Parameters
  • points ((n, dimension) float, points in space) –

  • smooth (float, smoothing amount) –

  • count (number of samples in output) –

  • degree (int, degree of spline polynomial) –

Returns

resampled

Return type

(count, dimension) float, points in space

trimesh.path.simplify.simplify_basic(drawing, process=False, **kwargs)

Merge colinear segments and fit circles.

Parameters

drawing (Path2D object, will not be modified.) –

Returns

simplified

Return type

Path2D with circles.

trimesh.path.simplify.simplify_spline(path, smooth=None, verbose=False)

Replace discrete curves with b-spline or Arc and return the result as a new Path2D object.

Parameters
Returns

simplified – Consists of Arc and BSpline entities

Return type

Path2D

trimesh.path.traversal module

class trimesh.path.traversal.PathSample(points)

Bases: object

sample(distances)
truncate(distance)

Return a truncated version of the path. Only one vertex (at the endpoint) will be added.

trimesh.path.traversal.closed_paths(entities, vertices)

Paths are lists of entity indices. We first generate vertex paths using graph cycle algorithms, and then convert them to entity paths.

This will also change the ordering of entity.points in place so a path may be traversed without having to reverse the entity.

Parameters
  • entities ((n,) entity objects) – Entity objects

  • vertices ((m, dimension) float) – Vertex points in space

Returns

entity_paths – Ordered traversals of entities

Return type

sequence of (n,) int

trimesh.path.traversal.discretize_path(entities, vertices, path, scale=1.0)

Turn a list of entity indices into a path of connected points.

Parameters
  • entities ((j,) entity objects) – Objects like ‘Line’, ‘Arc’, etc.

  • vertices ((n, dimension) float) – Vertex points in space.

  • path ((m,) int) – Indexes of entities

  • scale (float) – Overall scale of drawing used for numeric tolerances in certain cases

Returns

discrete – Connected points in space that lie on the path and can be connected with line segments.

Return type

(p, dimension) float

trimesh.path.traversal.resample_path(points, count=None, step=None, step_round=True)

Given a path along (n,d) points, resample them such that the distance traversed along the path is constant in between each of the resampled points. Note that this can produce clipping at corners, as the original vertices are NOT guaranteed to be in the new, resampled path.

ONLY ONE of count or step can be specified Result can be uniformly distributed (np.linspace) by specifying count Result can have a specific distance (np.arange) by specifying step

Parameters
  • points ((n, d) float) – Points in space

  • count (int,) – Number of points to sample evenly (aka np.linspace)

  • step (float) – Distance each step should take along the path (aka np.arange)

Returns

resampled – Points on the path

Return type

(j,d) float

trimesh.path.traversal.split(self)

Split a Path2D into multiple Path2D objects where each one has exactly one root curve.

Parameters

self (trimesh.path.Path2D) – Input geometry

Returns

split – Original geometry as separate paths

Return type

list of trimesh.path.Path2D

trimesh.path.traversal.vertex_graph(entities)

Given a set of entity objects generate a networkx.Graph that represents their vertex nodes.

Parameters

entities (list) – Objects with ‘closed’ and ‘nodes’ attributes

Returns

  • graph (networkx.Graph) – Graph where node indexes represent vertices

  • closed ((n,) int) – Indexes of entities which are ‘closed’

trimesh.path.traversal.vertex_to_entity_path(vertex_path, graph, entities, vertices=None)

Convert a path of vertex indices to a path of entity indices.

Parameters
  • vertex_path ((n,) int) – Ordered list of vertex indices representing a path

  • graph (nx.Graph) – Vertex connectivity

  • entities ((m,) list) – Entity objects

  • vertices ((p, dimension) float) – Vertex points in space

Returns

entity_path – Entity indices which make up vertex_path

Return type

(q,) int

trimesh.path.util module

trimesh.path.util.concatenate(paths)

Concatenate multiple paths into a single path.

Parameters

paths (list of Path, Path2D, or Path3D objects) –

Returns

concat

Return type

Path, Path2D, or Path3D object

trimesh.path.util.is_ccw(points)

Check if connected planar points are counterclockwise.

Parameters

points ((n,2) float, connected points on a plane) –

Returns

ccw

Return type

bool, True if points are counterclockwise

Module contents

class trimesh.path.Path2D(entities=None, vertices=None, metadata=None, process=True)

Bases: trimesh.path.path.Path

apply_obb()

Transform the current path so that its OBB is axis aligned and OBB center is at the origin.

Returns

obb – Homogeneous transformation matrix

Return type

(3, 3) float

property area

Return the area of the polygons interior.

Returns

area

Return type

float, total area of polygons minus interiors

property body_count
property centroid

Return the centroid of the path object.

Returns

centroid – Approximate centroid of the path

Return type

(d,) float

connected_paths(path_id, include_self=False)

Given an index of self.paths find other paths which overlap with that path.

Parameters
  • path_id (int) – Index of self.paths

  • include_self (bool) – Should the result include path_id or not

Returns

path_ids – Indexes of self.paths that overlap input path_id

Return type

(n, ) int

property enclosure

Networkx Graph object of polygon enclosure.

property enclosure_directed

Networkx DiGraph of polygon enclosure

property enclosure_shell

A dictionary of path indexes which are ‘shell’ paths, and values of ‘hole’ paths.

Returns

corresponding

Return type

dict, {index of self.paths of shell : [indexes of holes]}

extrude(height, **kwargs)

Extrude the current 2D path into a 3D mesh.

Parameters
  • height (float, how far to extrude the profile) –

  • kwargs (passed directly to meshpy.triangle.build:) –

    triangle.build(mesh_info,

    verbose=False, refinement_func=None, attributes=False, volume_constraints=True, max_volume=None, allow_boundary_steiner=True, allow_volume_steiner=True, quality_meshing=True, generate_edges=None, generate_faces=False, min_angle=None)

Returns

mesh

Return type

trimesh object representing extruded polygon

property identifier

A unique identifier for the path.

Returns

identifier

Return type

(5,) float, unique identifier

property identifier_md5

Return an MD5 of the identifier

property length

The total discretized length of every entity.

Returns

length

Return type

float, summed length of every entity

medial_axis(resolution=None, clip=None)

Find the approximate medial axis based on a voronoi diagram of evenly spaced points on the boundary of the polygon.

Parameters
  • resolution (None or float) – Distance between each sample on the polygon boundary

  • clip (None, or (2,) float) – Min, max number of samples

Returns

medial – Contains only medial axis of Path

Return type

Path2D object

property obb

Get a transform that centers and aligns the OBB of the referenced vertices with the XY axis.

Returns

obb – Homogeneous transformation matrix

Return type

(3, 3) float

property path_valid
Returns

path_valid – which are valid polygons

Return type

(n,) bool, indexes of self.paths self.polygons_closed

plot_discrete(show=False, annotations=True)

Plot the closed curves of the path.

plot_entities(show=False, annotations=True, color=None)

Plot the entities of the path, with no notion of topology

property polygons_closed

Cycles in the vertex graph, as shapely.geometry.Polygons. These are polygon objects for every closed circuit, with no notion of whether a polygon is a hole or an area. Every polygon in this list will have an exterior, but NO interiors.

Returns

polygons_closed

Return type

(n,) list of shapely.geometry.Polygon objects

property polygons_full

A list of shapely.geometry.Polygon objects with interiors created by checking which closed polygons enclose which other polygons.

Returns

full – Polygons containing interiors

Return type

(len(self.root),) shapely.geometry.Polygon

rasterize(pitch, origin, resolution=None, fill=True, width=None, **kwargs)

Rasterize a Path2D object into a boolean image (“mode 1”).

Parameters
  • pitch (float, length in model space of a pixel edge) –

  • origin ((2,) float, origin position in model space) –

  • resolution ((2,) int, resolution in pixel space) –

  • fill (bool, if True will return closed regions as filled) –

  • width (int, if not None will draw outline this wide (pixels)) –

Returns

raster

Return type

PIL.Image object, mode 1

property root

Which indexes of self.paths/self.polygons_closed are root curves. Also known as ‘shell’ or ‘exterior.

Returns

root

Return type

(n,) int, list of indexes

sample(count, **kwargs)

Use rejection sampling to generate random points inside a polygon.

Parameters
  • count (int) – Number of points to return If there are multiple bodies, there will be up to count * bodies points returned

  • factor (float) – How many points to test per loop IE, count * factor

  • max_iter (int,) – Maximum number of intersection loops to run, total points sampled is count * factor * max_iter

Returns

hit – Random points inside polygon

Return type

(n, 2) float

show(annotations=True)

Plot the current Path2D object using matplotlib.

simplify(**kwargs)

Return a version of the current path with colinear segments merged, and circles entities replacing segmented circular paths.

Returns

simplified

Return type

Path2D object

simplify_spline(smooth=0.0002, verbose=False)

Convert paths into b-splines.

Parameters
  • smooth (float) – How much the spline should smooth the curve

  • verbose (bool) – Print detailed log messages

Returns

simplified – Discrete curves replaced with splines

Return type

Path2D

split()

If the current Path2D consists of n ‘root’ curves, split them into a list of n Path2D objects

Returns

split – Each connected region and interiors

Return type

(n,) list of Path2D objects

to_3D(transform=None)

Convert 2D path to 3D path on the XY plane.

Parameters

transform ((4, 4) float) – If passed, will transform vertices. If not passed and ‘to_3D’ is in metadata that transform will be used.

Returns

path_3D

Return type

Path3D version of current path

triangulate(**kwargs)

Create a region- aware triangulation of the 2D path.

Parameters

**kwargs (dict) – Passed to trimesh.creation.triangulate_polygon

Returns

  • vertices ((n, 2) float) – 2D vertices of triangulation

  • faces ((n, 3) int) – Indexes of vertices for triangles

class trimesh.path.Path3D(entities=None, vertices=None, metadata=None, process=True)

Bases: trimesh.path.path.Path

plot_discrete(show=False)

Plot closed curves

Parameters

show (bool) – If False will not execute matplotlib.pyplot.show

plot_entities(show=False)

Plot discrete version of entities without regards for connectivity.

Parameters

show (bool) – If False will not execute matplotlib.pyplot.show

show(**kwargs)

Show the current Path3D object.

to_planar(to_2D=None, normal=None, check=True)

Check to see if current vectors are all coplanar.

If they are, return a Path2D and a transform which will transform the 2D representation back into 3 dimensions

Parameters
  • to_2D ((4,4) float) – Homogeneous transformation matrix to apply, If not passed a plane will be fitted to vertices.

  • normal ((3,) float, or None) – Approximate normal of direction of plane If to_2D is not specified sign will be applied to fit plane normal

  • check (bool) – If True: Raise a ValueError if points aren’t coplanar

Returns

  • planar (trimesh.path.Path2D) – Current path transformed onto plane

  • to_3D ((4,4) float) – Homeogenous transformation to move planar back into 3D space