Geometry#
2D and 3D geometry types that the tree nodes are built on. Some are inputs you build directly: vectors
and polygons, meshes and CAD models, height fields for surface relief, the CellMap that bends a
lattice to a part, unit cells, and seed points with their surface Voronoi diagrams. Others are
helpers for custom geometry and analysis, such as hexahedral and tetrahedral meshing.
- class pyvcad.Point2#
A 2D point with exact (CGAL) coordinates. Read the coordinates with x() and y().
- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.Point2) -> None
Default constructor creating a point at origin (0,0)
Example
>>> p = Point2() >>> print(f'({p.x()}, {p.y()})') (0.0, 0.0)
__init__(self: pyvcad.pyvcad.Point2, x: typing.SupportsFloat | typing.SupportsIndex, y: typing.SupportsFloat | typing.SupportsIndex) -> None
Create a 2D point with given x and y coordinates
- Parameters:
x (float) – X coordinate
y (float) – Y coordinate
Example
>>> p = Point2(1.0, 2.0) >>> print(f'({p.x()}, {p.y()})') (1.0, 2.0)
- x(self: pyvcad.pyvcad.Point2) float#
Get the x coordinate of the point
- Returns:
X coordinate
- Return type:
float
- y(self: pyvcad.pyvcad.Point2) float#
Get the y coordinate of the point
- Returns:
Y coordinate
- Return type:
float
- class pyvcad.Segment2#
A 2D line segment between two Point2 endpoints.
- __init__(self: pyvcad.pyvcad.Segment2, p1: pyvcad.pyvcad.Point2, p2: pyvcad.pyvcad.Point2) None#
Create a 2D line segment between two points
- Parameters:
Example
>>> p1 = Point2(0.0, 0.0) >>> p2 = Point2(1.0, 1.0) >>> segment = Segment2(p1, p2) >>> source = segment.source() >>> target = segment.target() >>> print(f'From ({source.x()}, {source.y()}) to ({target.x()}, {target.y()})') From (0.0, 0.0) to (1.0, 1.0)
- source(self: pyvcad.pyvcad.Segment2) pyvcad.pyvcad.Point2#
Returns the source point of the segment
- Returns:
The starting point of the segment
- Return type:
- target(self: pyvcad.pyvcad.Segment2) pyvcad.pyvcad.Point2#
Returns the target point of the segment
- Returns:
The ending point of the segment
- Return type:
- class pyvcad.Vec2#
A 2D float vector with x and y components.
- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.Vec2) -> None
Default constructor creating a zero vector (0,0)
Example
>>> v = Vec2() >>> print(f'({v.x}, {v.y})') (0.0, 0.0)
__init__(self: pyvcad.pyvcad.Vec2, x: typing.SupportsFloat | typing.SupportsIndex, y: typing.SupportsFloat | typing.SupportsIndex) -> None
Create a 2D vector with given x and y components
- Parameters:
x (float) – X component
y (float) – Y component
Example
>>> v = Vec2(1.0, 2.0) >>> print(f'({v.x}, {v.y})') (1.0, 2.0)
- property x#
X component of the vector
- property y#
Y component of the vector
- class pyvcad.Vec3#
A 3D float vector with x, y and z components.
Any argument typed Vec3 also accepts a tuple or list of three numbers, e.g.
(0, 0, 1).- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.Vec3) -> None
Default constructor creating a zero vector (0,0,0)
Example
>>> v = Vec3() >>> print(f'({v.x}, {v.y}, {v.z})') (0.0, 0.0, 0.0)
__init__(self: pyvcad.pyvcad.Vec3, x: typing.SupportsFloat | typing.SupportsIndex, y: typing.SupportsFloat | typing.SupportsIndex, z: typing.SupportsFloat | typing.SupportsIndex) -> None
Create a 3D vector with given x, y, and z components
- Parameters:
x (float) – X component
y (float) – Y component
z (float) – Z component
Example
>>> v = Vec3(1.0, 2.0, 3.0) >>> print(f'({v.x}, {v.y}, {v.z})') (1.0, 2.0, 3.0)
__init__(self: pyvcad.pyvcad.Vec3, arg0: collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex]) -> None
Create a 3D vector from a list or tuple of 3 floats
Example
>>> v = Vec3([1.0, 2.0, 3.0]) >>> print(f'({v.x}, {v.y}, {v.z})') (1.0, 2.0, 3.0)
- property x#
X component of the vector
- property y#
Y component of the vector
- property z#
Z component of the vector
- class pyvcad.Vec4#
A 4D float vector, used for RGBA colors. Components are r, g, b and a.
- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.Vec4) -> None
Default constructor creating a zero vector (0,0,0,0)
Example
>>> v = Vec4() >>> print(f'({v.r}, {v.g}, {v.b}, {v.a})') (0.0, 0.0, 0.0, 0.0)
__init__(self: pyvcad.pyvcad.Vec4, r: typing.SupportsFloat | typing.SupportsIndex, g: typing.SupportsFloat | typing.SupportsIndex, b: typing.SupportsFloat | typing.SupportsIndex, a: typing.SupportsFloat | typing.SupportsIndex) -> None
Create a 4D vector with given r, g, b, and a components
- Parameters:
r (float) – Red component
g (float) – Green component
b (float) – Blue component
a (float) – Alpha component
Example
>>> v = Vec4(1.0, 0.0, 0.0, 1.0) # Red color with full opacity >>> print(f'({v.r}, {v.g}, {v.b}, {v.a})') (1.0, 0.0, 0.0, 1.0)
- property a#
Alpha component of the vector
- property b#
Blue component of the vector
- property g#
Green component of the vector
- property r#
Red component of the vector
- class pyvcad.Polygon2#
A 2D polygon with exact (CGAL) coordinates and an optional list of holes.
The vertices are the outer boundary, stored without repeating the first point. Holes are kept as a separate list of Polygon2. Iterating a Polygon2 yields the outer boundary’s Point2 values. Most queries (is_ccw, inside, on_boundary, bounding_box, double_area, simplify) look only at the outer boundary; the booleans, offset and clip also use the holes.
The boolean operations use Clipper2 with the even-odd fill rule, so polygons that overlap inside one operand list cancel (XOR) there. They return one Polygon2 per output contour: outer contours are counter-clockwise, and holes come back as separate clockwise polygons with no holes() of their own.
Example
>>> import pyvcad as pv >>> square = pv.Polygon2([pv.Vec2(0, 0), pv.Vec2(2, 0), pv.Vec2(2, 2), pv.Vec2(0, 2)]) >>> square.double_area() 4.0
- static Clip(polygons: collections.abc.Sequence[pyvcad.pyvcad.Polygon2], polylines: collections.abc.Sequence[Polyline2]) tuple[list[pyvcad.pyvcad.Polygon2], list[Polyline2]]#
Clip polylines to the region covered by a list of polygons and their holes (even-odd fill).
Only open paths are clipped, so the closed part of the result is always empty.
- static Difference(polygons: collections.abc.Sequence[pyvcad.pyvcad.Polygon2], others: collections.abc.Sequence[pyvcad.pyvcad.Polygon2]) list[pyvcad.pyvcad.Polygon2]#
Difference of two lists of polygons: polygons minus others (even-odd fill, output as in Union).
- static Intersection(polygons: collections.abc.Sequence[pyvcad.pyvcad.Polygon2], others: collections.abc.Sequence[pyvcad.pyvcad.Polygon2]) list[pyvcad.pyvcad.Polygon2]#
Intersection of two lists of polygons (even-odd fill, output as in Union).
- static Offset(polygons: collections.abc.Sequence[pyvcad.pyvcad.Polygon2], distance: SupportsFloat | SupportsIndex) list[pyvcad.pyvcad.Polygon2]#
Offset a list of polygons, with their holes, by one distance.
The offset uses miter joins, so convex corners stay sharp (Clipper2’s default miter limit of 2 applies). Coordinates are snapped to a 1e-6 grid. Counter-clockwise results become outer polygons; each clockwise result is attached as a hole to the first outer polygon containing it.
- static Union(polygons: collections.abc.Sequence[pyvcad.pyvcad.Polygon2], others: collections.abc.Sequence[pyvcad.pyvcad.Polygon2]) list[pyvcad.pyvcad.Polygon2]#
Union of two lists of polygons (even-odd fill).
Each list, with its holes, is filled even-odd, so polygons that overlap inside one list cancel (XOR) before the union.
- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.Polygon2) -> None
Create an empty polygon.
__init__(self: pyvcad.pyvcad.Polygon2, points: collections.abc.Sequence[pyvcad.pyvcad.Point2]) -> None
Create a polygon from at least 3 Point2 values.
The sequence may be open or closed. If the last point equals the first, it is dropped.
- Parameters:
points (list[Point2]) – The outer boundary points.
Example
>>> import pyvcad as pv >>> tri = pv.Polygon2([pv.Point2(0, 0), pv.Point2(1, 0), pv.Point2(0, 1)])
__init__(self: pyvcad.pyvcad.Polygon2, points: collections.abc.Sequence[pyvcad.pyvcad.Vec2]) -> None
Create a polygon from at least 3 Vec2 values.
The sequence may be open or closed. If the last point equals the first, it is dropped.
- Parameters:
points (list[Vec2]) – The outer boundary points.
Example
>>> import pyvcad as pv >>> tri = pv.Polygon2([pv.Vec2(0, 0), pv.Vec2(1, 0), pv.Vec2(0, 1)])
- bounding_box(self: pyvcad.pyvcad.Polygon2) tuple[pyvcad.pyvcad.Point2, pyvcad.pyvcad.Point2]#
Compute the axis-aligned bounding box of the outer boundary.
- diff(self: pyvcad.pyvcad.Polygon2, other: pyvcad.pyvcad.Polygon2) list[pyvcad.pyvcad.Polygon2]#
Subtract another polygon from this one (even-odd fill).
- do_clip(self: pyvcad.pyvcad.Polygon2, polylines: collections.abc.Sequence[Polyline2]) tuple[list[pyvcad.pyvcad.Polygon2], list[Polyline2]]#
Clip polylines to the inside of this polygon (holes excluded).
- do_union(*args, **kwargs)#
Overloaded function.
do_union(self: pyvcad.pyvcad.Polygon2, other: pyvcad.pyvcad.Polygon2) -> list[pyvcad.pyvcad.Polygon2]
Union of this polygon with another (even-odd fill).
- Parameters:
other (Polygon2) – The other polygon.
- Returns:
The result contours. Holes are separate clockwise polygons.
- Return type:
list[Polygon2]
do_union(self: pyvcad.pyvcad.Polygon2, others: collections.abc.Sequence[pyvcad.pyvcad.Polygon2]) -> list[pyvcad.pyvcad.Polygon2]
Union of this polygon with a list of polygons (even-odd fill).
Polygons in others that overlap each other cancel (XOR) before the union.
- double_area(self: pyvcad.pyvcad.Polygon2) float#
Compute the signed area of the outer boundary.
Despite the name, this is the signed area itself, not twice it. It is positive for a counter-clockwise boundary and negative for a clockwise one. Holes are not subtracted.
- Returns:
The signed area.
- Return type:
float
- draw(self: pyvcad.pyvcad.Polygon2) None#
Show the outer boundary in CGAL’s basic viewer (a debugging aid).
This only opens a window when CGAL is built with its Qt viewer (CGAL_USE_BASIC_VIEWER); otherwise CGAL prints a message and nothing is shown.
- holes(self: pyvcad.pyvcad.Polygon2) list[pyvcad.pyvcad.Polygon2]#
Return a copy of the polygon’s holes.
- Returns:
The holes.
- Return type:
list[Polygon2]
- inside(self: pyvcad.pyvcad.Polygon2, point: pyvcad.pyvcad.Point2) bool#
Check whether a point is strictly inside the outer boundary.
Holes are ignored, and a point on the boundary is not inside.
- Parameters:
point (Point2) – The point to test.
- Returns:
True if the point is inside the outer boundary.
- Return type:
bool
- intersect(*args, **kwargs)#
Overloaded function.
intersect(self: pyvcad.pyvcad.Polygon2, other: pyvcad.pyvcad.Polygon2) -> list[pyvcad.pyvcad.Polygon2]
Intersection of this polygon with another (even-odd fill).
- Parameters:
other (Polygon2) – The other polygon.
- Returns:
The result contours. Holes are separate clockwise polygons.
- Return type:
list[Polygon2]
intersect(self: pyvcad.pyvcad.Polygon2, others: collections.abc.Sequence[pyvcad.pyvcad.Polygon2]) -> list[pyvcad.pyvcad.Polygon2]
Intersection of this polygon with a list of polygons (even-odd fill).
The list is filled even-odd first, so polygons in it that overlap each other cancel (XOR).
- is_ccw(self: pyvcad.pyvcad.Polygon2) bool#
Check whether the outer boundary is counter-clockwise.
- Returns:
True if the outer boundary is counter-clockwise.
- Return type:
bool
- offset(self: pyvcad.pyvcad.Polygon2, distance: SupportsFloat | SupportsIndex) list[pyvcad.pyvcad.Polygon2]#
Offset the polygon and its holes. Same as Polygon2.Offset([self], distance).
- Parameters:
distance (float) – Positive grows the region, negative shrinks it.
- Returns:
Counter-clockwise outer polygons with their holes attached.
- Return type:
list[Polygon2]
- on_boundary(self: pyvcad.pyvcad.Polygon2, point: pyvcad.pyvcad.Point2) bool#
Check whether a point lies on the outer boundary. Hole boundaries are not checked.
- Parameters:
point (Point2) – The point to test.
- Returns:
True if the point is on the outer boundary.
- Return type:
bool
- reverse(self: pyvcad.pyvcad.Polygon2) None#
Reverse the order of the outer boundary’s points in place. Holes are not changed.
- set_holes(self: pyvcad.pyvcad.Polygon2, holes: collections.abc.Sequence[pyvcad.pyvcad.Polygon2]) None#
Replace the polygon’s holes.
- Parameters:
holes (list[Polygon2]) – The new holes.
- simplify(self: pyvcad.pyvcad.Polygon2, tolerance: SupportsFloat | SupportsIndex = 0.001) None#
Remove nearly collinear points from the outer boundary in place.
A point is dropped when the triangle it forms with the previous kept point and the next point has an area below tolerance. The first point is always kept. The polygon is rebuilt from the remaining points, so its holes are dropped.
- Parameters:
tolerance (float) – The triangle-area threshold, in squared length units (not a distance).
- Raises:
RuntimeError – If fewer than 3 points would remain.
- to_polyline(self: pyvcad.pyvcad.Polygon2) Polyline2#
Convert the outer boundary to a Polyline2.
The polyline repeats the first point at the end, so it ends where it starts. Holes are dropped.
- Returns:
The perimeter.
- Return type:
- to_profile(self: pyvcad.pyvcad.Polygon2) Profile#
Convert the polygon and its holes to a Profile, the general closed 2D region.
Example
>>> profile = polygon.to_profile()
- class pyvcad.Polyline2#
An open polyline in the XY plane, used with Polygon2 and Arrangement2.
Polyline2 is a PolylineCurve at z = 0, so it has every Curve method (point, closest_point, length, frames, …). Its own methods work with Point2 and Segment2 and edit the polyline in place.
- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.Polyline2) -> None
Create an empty polyline.
__init__(self: pyvcad.pyvcad.Polyline2, points: collections.abc.Sequence[pyvcad.pyvcad.Point2]) -> None
Create a polyline from at least 2 Point2 values.
- Parameters:
points (list[Point2]) – The points.
Example
>>> import pyvcad as pv >>> line = pv.Polyline2([pv.Point2(0, 0), pv.Point2(1, 0), pv.Point2(1, 1)])
__init__(self: pyvcad.pyvcad.Polyline2, points: collections.abc.Sequence[pyvcad.pyvcad.Vec2]) -> None
Create a polyline from at least 2 Vec2 values.
- Parameters:
points (list[Vec2]) – The points.
Example
>>> line = pv.Polyline2([pv.Vec2(0, 0), pv.Vec2(1, 0)])
- append(self: pyvcad.pyvcad.Polyline2, polyline: pyvcad.pyvcad.Polyline2) None#
Add another polyline’s points after this one’s. A shared end point is kept once.
- Parameters:
polyline (Polyline2) – The polyline to append.
- points(self: pyvcad.pyvcad.Polyline2) list[pyvcad.pyvcad.Point2]#
The points as a list of Point2.
- prepend(self: pyvcad.pyvcad.Polyline2, polyline: pyvcad.pyvcad.Polyline2) None#
Insert another polyline’s points before this one’s. A shared end point is kept once.
- Parameters:
polyline (Polyline2) – The polyline to prepend.
- reverse(self: pyvcad.pyvcad.Polyline2) None#
Reverse the order of the points in place.
- segments(self: pyvcad.pyvcad.Polyline2) list[pyvcad.pyvcad.Segment2]#
The segments as a list of Segment2.
- simplify(self: pyvcad.pyvcad.Polyline2, tolerance: SupportsFloat | SupportsIndex = 0.001) None#
Remove nearly collinear interior points in place.
An interior point is dropped when the triangle it forms with the previous kept point and the next point has an area below tolerance. The end points are always kept, and polylines with fewer than 3 points are unchanged.
- Parameters:
tolerance (float) – The triangle-area threshold, in squared length units (not a distance).
- translate(self: pyvcad.pyvcad.Polyline2, translation: pyvcad.pyvcad.Point2) None#
Move every point in place.
- Parameters:
translation (Point2) – The offset.
- class pyvcad.Arrangement2#
A 2D arrangement of line segments.
Inserted polygons and polylines are split at every crossing, and the plane is divided into faces. There is exactly one unbounded face (everything outside the inserted geometry); all other faces are bounded.
Example
>>> import pyvcad as pv >>> arrangement = pv.Arrangement2() >>> arrangement.insert(pv.Polygon2([pv.Vec2(0, 0), pv.Vec2(2, 0), pv.Vec2(2, 2), pv.Vec2(0, 2)])) >>> arrangement.insert(pv.Polyline2([pv.Vec2(1, -1), pv.Vec2(1, 3)])) >>> len(arrangement.getBoundedFaces()) 2
- __init__(self: pyvcad.pyvcad.Arrangement2) None#
Default constructor. Creates an Arrangement2 object.
- getBoundedFaces(self: pyvcad.pyvcad.Arrangement2) list[pyvcad.pyvcad.Polygon2]#
Returns the bounded faces of the arrangement.
Each face is a counter-clockwise Polygon2 with the face’s inner boundaries attached as clockwise holes.
- Returns:
The bounded faces.
- Return type:
list[Polygon2]
- getUnboundedFaces(self: pyvcad.pyvcad.Arrangement2) list[pyvcad.pyvcad.Polygon2]#
Returns the outlines of the arrangement’s single unbounded face.
The unbounded face has no outer boundary, so this returns one clockwise Polygon2 per connected component of the inserted geometry, tracing its outline. No polygon extends to infinity. Dangling polyline edges are traced on both sides, so their outlines can be degenerate.
- Returns:
One outline per connected component.
- Return type:
list[Polygon2]
- insert(*args, **kwargs)#
Overloaded function.
insert(self: pyvcad.pyvcad.Arrangement2, polygon: pyvcad.pyvcad.Polygon2) -> None
Inserts a Polygon2 into the arrangement.
- Parameters:
polygon (Polygon2) – The polygon to insert.
insert(self: pyvcad.pyvcad.Arrangement2, polyline: pyvcad.pyvcad.Polyline2) -> None
Inserts a Polyline2 into the arrangement.
- Parameters:
polyline (Polyline2) – The polyline to insert.
- profiles(self: pyvcad.pyvcad.Arrangement2) list[Profile]#
Returns the bounded faces as Profile objects, each with its holes.
Example
>>> faces = arrangement.profiles()
- class pyvcad.HexahedralMesh#
Structured geometric hexahedral mesh.
The tree’s bounding box is split into voxel_size cells; a cell becomes an element when the signed distance at its centre is <= 0.
- __init__(self: pyvcad.pyvcad.HexahedralMesh) None#
Create an empty mesh. Use HexahedralMesh.from_tree() to mesh a tree.
Example
>>> import pyvcad as pv >>> mesh = pv.HexahedralMesh() >>> mesh.number_of_elements() 0
- bounding_box(self: pyvcad.pyvcad.HexahedralMesh) tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#
Returns the mesh bounding box.
- property cell_centroids#
Centroid of each element.
- property elements#
Hexahedral element connectivity.
- static from_tree(root: pyvcad.pyvcad.Node, settings: pyvcad.pyvcad.HexahedralMeshSettings) pyvcad.pyvcad.HexahedralMesh#
Build a structured hexahedral mesh from a tree.
- Parameters:
root (Node) – The tree; it is prepared here with settings.voxel_size.
settings (HexahedralMeshSettings) – The mesh settings.
- Returns:
The mesh.
- Return type:
Example
>>> import pyvcad as pv >>> settings = pv.HexahedralMeshSettings() >>> settings.voxel_size = pv.Vec3(1, 1, 1) >>> mesh = pv.HexahedralMesh.from_tree(pv.Sphere(pv.Vec3(0, 0, 0), 10.0), settings)
- property nodes#
Mesh node coordinates.
- number_of_elements(self: pyvcad.pyvcad.HexahedralMesh) int#
Returns the number of elements.
- number_of_nodes(self: pyvcad.pyvcad.HexahedralMesh) int#
Returns the number of nodes.
- voxel_size(self: pyvcad.pyvcad.HexahedralMesh) pyvcad.pyvcad.Vec3#
Returns the voxel size used to build the mesh.
- class pyvcad.HexahedralMeshSettings#
Settings for a structured, voxel-aligned hexahedral mesh.
- __init__(self: pyvcad.pyvcad.HexahedralMeshSettings) None#
Create hexahedral mesh settings with voxel_size = Vec3(1, 1, 1).
Example
>>> import pyvcad as pv >>> settings = pv.HexahedralMeshSettings() >>> settings.voxel_size = pv.Vec3(0.5, 0.5, 0.5)
- property voxel_size#
Edge lengths (Vec3) of each hexahedron along x, y and z, in mm.
- class pyvcad.TetrahedralMesh#
Geometric tetrahedral mesh of an implicit tree: node positions and element connectivity.
- __init__(self: pyvcad.pyvcad.TetrahedralMesh) None#
Create an empty mesh. Use TetrahedralMesh.from_tree() to mesh a tree.
Example
>>> import pyvcad as pv >>> mesh = pv.TetrahedralMesh() >>> mesh.number_of_elements() 0
- bounding_box(self: pyvcad.pyvcad.TetrahedralMesh) tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#
Returns the mesh bounding box.
- property cell_centroids#
Centroid of each element.
- property elements#
Tetrahedral element connectivity.
- static from_tree(*args, **kwargs)#
Overloaded function.
from_tree(root: pyvcad.pyvcad.Node, settings: pyvcad.pyvcad.TetrahedralMeshFixedSettings) -> pyvcad.pyvcad.TetrahedralMesh
Build a tetrahedral mesh from a tree using fixed cell sizing.
- Parameters:
root (Node) – The tree; it is prepared here.
settings (TetrahedralMeshFixedSettings) – Mesh criteria.
Example
>>> import pyvcad as pv >>> settings = pv.TetrahedralMeshFixedSettings() >>> settings.cell_size = 4.0 >>> mesh = pv.TetrahedralMesh.from_tree(pv.Sphere(pv.Vec3(0, 0, 0), 10.0), settings)
from_tree(root: pyvcad.pyvcad.Node, settings: pyvcad.pyvcad.TetrahedralMeshAdaptiveSettings) -> pyvcad.pyvcad.TetrahedralMesh
Build a tetrahedral mesh from a tree using adaptive cell sizing.
- Parameters:
root (Node) – The tree; it is prepared here.
settings (TetrahedralMeshAdaptiveSettings) – Mesh criteria and the cell-size expression.
Example
>>> import pyvcad as pv >>> settings = pv.TetrahedralMeshAdaptiveSettings() >>> mesh = pv.TetrahedralMesh.from_tree(pv.Sphere(pv.Vec3(0, 0, 0), 10.0), settings)
- property nodes#
Mesh node coordinates.
- number_of_elements(self: pyvcad.pyvcad.TetrahedralMesh) int#
Returns the number of elements.
- number_of_nodes(self: pyvcad.pyvcad.TetrahedralMesh) int#
Returns the number of nodes.
- class pyvcad.TetrahedralMeshFixedSettings#
Settings for a tetrahedral mesh with one target cell size (CGAL mesh criteria, in mm).
- property cell_radius_edge_ratio#
Largest circumradius to shortest edge ratio of a tetrahedron.
- property cell_size#
Largest tetrahedron circumradius in mm.
- property facet_angle#
Smallest surface-triangle angle in degrees.
- property facet_distance#
Largest distance in mm between a surface triangle and the true surface.
- property facet_size#
Largest surface-triangle size in mm.
- property random_seed#
Seed for the mesher’s random choices.
- class pyvcad.TetrahedralMeshAdaptiveSettings#
Settings for a tetrahedral mesh whose cell size follows an expression (CGAL mesh criteria, in mm).
- property cell_radius_edge_ratio#
Largest circumradius to shortest edge ratio of a tetrahedron.
- property cell_size_lower#
Smallest cell size in mm (min_cell in the expression).
- property cell_size_upper#
Largest cell size in mm (max_cell in the expression).
- property facet_angle#
Smallest surface-triangle angle in degrees.
- property facet_distance#
Largest distance in mm between a surface triangle and the true surface.
- property facet_size#
Largest surface-triangle size in mm.
- property random_seed#
Seed for the mesher’s random choices.
- property variable_cell_size_expression#
Cell-size expression of min_cell, max_cell and h, the length of the tree’s gradient.
- class pyvcad.SurfaceMesh#
Triangle surface mesh.
- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.SurfaceMesh) -> None
Constructor. Creates an empty surface mesh.
__init__(self: pyvcad.pyvcad.SurfaceMesh, vertices: collections.abc.Sequence[pyvcad.pyvcad.Vec3], triangles: collections.abc.Sequence[typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], “FixedSize(3)”]], disable_validation: bool = True) -> None
Constructor. Creates a surface mesh from vertices and indexed triangles.
__init__(self: pyvcad.pyvcad.SurfaceMesh, file_path: str, disable_validation: bool = True) -> None
Constructor. Loads a surface mesh from a file.
__init__(self: pyvcad.pyvcad.SurfaceMesh, root: pyvcad.pyvcad.Node, voxel_size: typing.SupportsFloat | typing.SupportsIndex, disable_validation: bool = True, root_already_prepared: bool = False, adaptivity: typing.SupportsFloat | typing.SupportsIndex = 0.0, relax_disoriented_triangles: bool = True) -> None
Constructor. Samples a tree at a uniform voxel size and extracts a surface mesh.
- Parameters:
root (Node) – Tree to mesh.
voxel_size (float) – Sampling voxel size in millimetres. Halving it roughly quadruples the triangle count and file size.
disable_validation (bool) – Skip the CGAL closed-mesh check (default True).
root_already_prepared (bool) – If True, the tree is not prepared again.
adaptivity (float) – 0 (default) gives uniform voxel-sized triangles. Larger values merge voxels (within blocks of 8 x 8 x 8) whose surface normals differ by less than an angle with 1 - cos(angle) = adaptivity: 0.01 is about 8 degrees, 0.05 about 18, 0.1 about 26. Flat faces merge at any value; small values suit curved lattices. The surface stays closed.
relax_disoriented_triangles (bool) – Smooth badly oriented triangles in adaptive mode.
Example
>>> mesh = pv.SurfaceMesh(root, 0.25, adaptivity=0.02)
__init__(self: pyvcad.pyvcad.SurfaceMesh, sdf_volume: VDBVolume<openvdb::v13_2::Grid<openvdb::v13_2::tree::Tree<openvdb::v13_2::tree::RootNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::LeafNode<float, 3u>, 4u>, 5u>>>>>, disable_validation: bool = True, adaptivity: typing.SupportsFloat | typing.SupportsIndex = 0.0, relax_disoriented_triangles: bool = True) -> None
Constructor. Extracts a surface mesh from a float signed-distance volume.
- Parameters:
sdf_volume (FloatVolume) – Signed-distance volume (inside negative).
disable_validation (bool) – Skip the CGAL closed-mesh check (default True).
adaptivity (float) – 0 (default) for uniform triangles, up to 1 for adaptive meshing.
relax_disoriented_triangles (bool) – Smooth badly oriented triangles in adaptive mode.
- property area#
Total triangle area in square millimetres.
- boundary_loop_count(self: pyvcad.pyvcad.SurfaceMesh) int#
Count the closed loops of open edges (holes and patch borders).
0 for a watertight mesh, 1 for a disk patch, 2 for an open tube.
Example
>>> holes = mesh.boundary_loop_count()
- boundary_loops(self: pyvcad.pyvcad.SurfaceMesh) list[PolylineCurve]#
Return the loops of open edges (holes and patch borders) as closed PolylineCurves.
Each loop follows the triangles’ winding. Chains that do not close (at non-manifold edges) are left out.
Example
>>> rims = [pv.Tube(loop, 0.8) for loop in mesh.boundary_loops()]
- bounding_box(self: pyvcad.pyvcad.SurfaceMesh) tuple[pyvcad.pyvcad.Vec3, pyvcad.pyvcad.Vec3]#
Returns the mesh bounding box.
- center(self: pyvcad.pyvcad.SurfaceMesh) None#
Centers the mesh about the origin.
- clipped(self: pyvcad.pyvcad.SurfaceMesh, node: pyvcad.pyvcad.Node, keep: str = 'inside', voxel_size: SupportsFloat | SupportsIndex | None = None) pyvcad.pyvcad.SurfaceMesh#
Return the part of the mesh inside (or outside) a node’s zero level.
Triangles crossing the level are split at the true crossing, so planes, primitives, and Function expressions all leave a clean open boundary. The node is prepared by this call. A Function node is only defined inside its bounding box, so make the box cover the mesh.
- Parameters:
node (Node) – Any node; inside is where its signed distance is negative.
keep (str) – ‘inside’ (default) or ‘outside’.
voxel_size (float, optional) – Voxel size in millimetres for preparing the node; None uses the mean mesh edge length.
Example
>>> plane = pv.Function('z - 30', pv.Vec3(-200, -200, -200), pv.Vec3(200, 200, 200)) >>> top = head.clipped(plane, keep='outside')
- compute_sdf(self: pyvcad.pyvcad.SurfaceMesh, voxel_size: pyvcad.pyvcad.Vec3, exterior_band_width: SupportsFloat | SupportsIndex = 3.0, interior_band_width: SupportsFloat | SupportsIndex = 3.0) VDBVolume<openvdb::v13_2::Grid<openvdb::v13_2::tree::Tree<openvdb::v13_2::tree::RootNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::InternalNode<openvdb::v13_2::tree::LeafNode<float, 3u>, 4u>, 5u>>>>>#
Converts the mesh into a narrow-band float signed-distance volume.
The grid is isotropic: only the smallest component of voxel_size is used as the spacing.
- Parameters:
voxel_size (Vec3) – Voxel size in millimetres; only min(x, y, z) is used.
exterior_band_width (float) – Narrow-band width outside the surface, in millimetres.
interior_band_width (float) – Narrow-band width inside the surface, in millimetres.
- Returns:
The signed-distance volume (negative inside).
- Return type:
- Raises:
RuntimeError – If the mesh is empty.
Example
>>> sdf = mesh.compute_sdf(pv.Vec3(0.1, 0.1, 0.1))
- connected_components(self: pyvcad.pyvcad.SurfaceMesh) list[pyvcad.pyvcad.SurfaceMesh]#
Return the vertex-connected pieces as separate meshes, largest (most triangles) first.
Example
>>> pieces = mesh.connected_components() >>> print(len(pieces), 'pieces')
- decimated(self: pyvcad.pyvcad.SurfaceMesh, target_count: SupportsInt | SupportsIndex | None = None, target_ratio: SupportsFloat | SupportsIndex | None = None, max_error: SupportsFloat | SupportsIndex | None = None) pyvcad.pyvcad.SurfaceMesh#
Return a simplified copy using edge collapse with quadric (Garland-Heckbert) error.
Give a target size (target_count or target_ratio), an error bound, or both. Label boundaries (for example CAD faces) are never collapsed.
- Parameters:
target_count (int, optional) – Stop at or below this many triangles.
target_ratio (float, optional) – Stop at or below this fraction of the triangles, in (0, 1].
max_error (float, optional) – Stop before the surface would move more than about this many millimetres from the original face planes.
Example
>>> light = mesh.decimated(target_ratio=0.2, max_error=0.05)
- filled_holes(self: pyvcad.pyvcad.SurfaceMesh, max_hole_size: SupportsFloat | SupportsIndex | None = None, fair: bool = True) pyvcad.pyvcad.SurfaceMesh#
Return a copy with open boundary loops (holes) closed by new triangles.
Each hole is triangulated, refined to the surrounding density, and optionally faired. Compare boundary_loop_count() before and after to see how many holes were closed.
- Parameters:
max_hole_size (float, optional) – Only fill holes whose boundary bounding-box diagonal is at most this many millimetres. None fills every hole.
fair (bool) – Blend the patch smoothly into the surrounding surface (default True).
Example
>>> closed = scan.filled_holes(max_hole_size=10.0)
- property fingerprint#
Deterministic fingerprint of ordered vertices and triangles.
- is_closed(self: pyvcad.pyvcad.SurfaceMesh) bool#
Return True when every edge is shared by exactly two triangles (watertight).
Example
>>> mesh.is_closed()
- is_manifold(self: pyvcad.pyvcad.SurfaceMesh) bool#
Return True when no edge has more than two triangles and every vertex has a single fan of triangles around it.
Example
>>> mesh.is_manifold()
- merge(self: pyvcad.pyvcad.SurfaceMesh, mesh_to_merge: pyvcad.pyvcad.SurfaceMesh) None#
Merges another mesh into this mesh.
- nearest_triangle(self: pyvcad.pyvcad.SurfaceMesh, point: pyvcad.pyvcad.Vec3) pyvcad.pyvcad.MeshHit#
Find the closest source triangle to a world-space point.
- Parameters:
point (Vec3) – Query point in millimetres.
Example
>>> hit = mesh.nearest_triangle(pv.Vec3(0, 0, 10))
- nearest_vertex(self: pyvcad.pyvcad.SurfaceMesh, point: pyvcad.pyvcad.Vec3) int#
Find the source vertex nearest to a world-space point.
- Parameters:
point (Vec3) – Query point in millimetres.
Example
>>> vertex_id = mesh.nearest_vertex(pv.Vec3(0, 0, 10))
- ray_intersection(self: pyvcad.pyvcad.SurfaceMesh, origin: pyvcad.pyvcad.Vec3, direction: pyvcad.pyvcad.Vec3) pyvcad.pyvcad.MeshHit | None#
Find the first source triangle hit by a world-space ray.
Example
>>> hit = mesh.ray_intersection(pv.Vec3(0, 0, 10), pv.Vec3(0, 0, -1))
- remeshed(self: pyvcad.pyvcad.SurfaceMesh, target_edge_length: SupportsFloat | SupportsIndex, iterations: SupportsInt | SupportsIndex = 3, feature_angle: SupportsFloat | SupportsIndex | None = None) pyvcad.pyvcad.SurfaceMesh#
Return an isotropically remeshed copy with near-uniform edge lengths.
Vertices are projected back onto the input surface. Open borders and label boundaries stay in place.
- Parameters:
target_edge_length (float) – Target edge length in millimetres.
iterations (int) – Number of remeshing passes (default 3).
feature_angle (float, optional) – Keep edges sharper than this dihedral angle in degrees.
Example
>>> even = mesh.remeshed(1.0, iterations=5)
- remove_small_components(self: pyvcad.pyvcad.SurfaceMesh, min_volume: SupportsFloat | SupportsIndex | None = None, min_triangles: SupportsInt | SupportsIndex | None = None, keep_largest: bool = False) pyvcad.pyvcad.SurfaceMesh#
Return a copy without small disconnected pieces such as floating islands.
Inner cavity surfaces stay with the body that encloses them, so hollow parts are judged by their material volume and keep their inner walls.
- Parameters:
min_volume (float, optional) – Remove bodies enclosing less than this volume (mm^3).
min_triangles (int, optional) – Remove bodies with fewer triangles than this.
keep_largest (bool) – Keep only the body with the largest volume.
Example
>>> clean = mesh.remove_small_components(min_volume=1.0)
- static seed_points_inside(region: pyvcad.pyvcad.Node, seed_count: SupportsInt | SupportsIndex) list[pyvcad.pyvcad.Vec3]#
Return evenly spread points inside a node (negative signed distance).
A grid over the node bounding box is filtered to inside points, then a deterministic farthest-point subset is returned. The node is prepared by this call.
- Parameters:
region (Node) – Node to sample.
seed_count (int) – Number of points to return.
Example
>>> seeds = pv.SurfaceMesh.seed_points_inside(head_node, 8)
- select_by_geodesic_radius(self: pyvcad.pyvcad.SurfaceMesh, seed_vertex: SupportsInt | SupportsIndex, radius: SupportsFloat | SupportsIndex) MeshSelection#
Select triangles reached within a shortest mesh-edge distance.
A triangle is included when at least one of its vertices is within the radius.
- Parameters:
seed_vertex (int) – Source vertex at the selection center.
radius (float) – Non-negative surface distance in millimetres.
Example
>>> patch = mesh.select_by_geodesic_radius(seed_vertex, 12.0)
- select_enclosed_region(self: pyvcad.pyvcad.SurfaceMesh, boundary_edges: collections.abc.Sequence[Annotated[collections.abc.Sequence[SupportsInt | SupportsIndex], 'FixedSize(2)']], seed_triangle: SupportsInt | SupportsIndex) MeshSelection#
Select the side of one closed source-edge loop containing a seed triangle.
- Parameters:
boundary_edges (list[tuple[int, int]]) – One connected closed mesh-edge loop.
seed_triangle (int) – Triangle on the desired side of the loop.
Example
>>> patch = mesh.select_enclosed_region(loop_edges, seed_triangle=20)
- select_linked(self: pyvcad.pyvcad.SurfaceMesh, seed_triangle: SupportsInt | SupportsIndex, cross_non_manifold: bool = False) MeshSelection#
Flood-fill the edge-connected component containing a seed triangle.
Open boundaries and non-manifold edges delimit growth by default.
- Parameters:
seed_triangle (int) – Source triangle ID.
cross_non_manifold (bool) – Allow growth across edges used by more than two faces.
Example
>>> selection = mesh.select_linked(0)
- select_linked_by_face_angle(self: pyvcad.pyvcad.SurfaceMesh, seed_triangle: SupportsInt | SupportsIndex, max_angle_degrees: SupportsFloat | SupportsIndex, cross_non_manifold: bool = False) MeshSelection#
Flood-fill across edges whose local adjacent-face angle is within a threshold.
- Parameters:
seed_triangle (int) – Source triangle ID.
max_angle_degrees (float) – Inclusive local face-angle threshold from 0 to 180.
cross_non_manifold (bool) – Allow growth across edges used by more than two faces.
Example
>>> selection = mesh.select_linked_by_face_angle(0, 25.0)
- select_linked_constrained(self: pyvcad.pyvcad.SurfaceMesh, seed_triangle: SupportsInt | SupportsIndex, max_angle_degrees: SupportsFloat | SupportsIndex | None = None, blocked_edges: collections.abc.Sequence[Annotated[collections.abc.Sequence[SupportsInt | SupportsIndex], 'FixedSize(2)']] = [], triangle_regions: collections.abc.Sequence[SupportsInt | SupportsIndex] = []) MeshSelection#
Flood-fill with optional angle, marked-edge, and region-label delimiters.
Open and non-manifold edges always delimit this selection.
- Parameters:
seed_triangle (int) – Source triangle ID.
max_angle_degrees (float, optional) – Inclusive local face-angle limit.
blocked_edges (list[tuple[int, int]]) – Source mesh edges that growth cannot cross.
triangle_regions (list[int]) – Optional per-triangle labels; unequal labels delimit growth.
Example
>>> patch = mesh.select_linked_constrained(0, 35.0, marked_edges, labels)
- select_triangles(self: pyvcad.pyvcad.SurfaceMesh, triangle_ids: collections.abc.Sequence[SupportsInt | SupportsIndex]) MeshSelection#
Create an explicit immutable triangle selection.
- Parameters:
triangle_ids (list[int]) – Source triangle IDs; duplicates are removed.
Example
>>> selection = mesh.select_triangles([0, 1])
- select_visible_from(self: pyvcad.pyvcad.SurfaceMesh, points_or_node: object, seed_count: SupportsInt | SupportsIndex = 16, facing: str = 'any', max_view_angle: SupportsFloat | SupportsIndex | None = None) MeshSelection#
Select the triangles that can be seen from seed points.
A triangle is selected when a straight line from a seed reaches it before any other triangle. The selection crosses sharp creases freely, so it picks the inner surface of a shell (including around openings) as seen from points inside it. Returns a MeshSelection that composes with union, intersection, difference, grown, and shrunk.
- Parameters:
points_or_node – Seed points (Vec3 values or (x, y, z) triples, in mm), or a Node whose inside is filled with seed_count evenly spread seeds.
seed_count (int) – Seeds to place when a Node is given (default 16).
facing (str) – ‘any’ (default), ‘toward’ (triangle normal points at the seed), or ‘away’.
max_view_angle (float, optional) – Skip triangles seen more obliquely than this angle in degrees between the triangle normal and the direction to the seed.
Example
>>> inner = shell_mesh.select_visible_from([(0, 0, 40), (0, 20, 50)], facing='toward')
- shortest_surface_path(self: pyvcad.pyvcad.SurfaceMesh, start_vertex: SupportsInt | SupportsIndex, end_vertex: SupportsInt | SupportsIndex, blocked_edges: collections.abc.Sequence[Annotated[collections.abc.Sequence[SupportsInt | SupportsIndex], 'FixedSize(2)']] = []) pyvcad.pyvcad.MeshPath#
Find the shortest path between two source vertices along mesh edges.
- Parameters:
start_vertex (int) – First source vertex ID.
end_vertex (int) – Last source vertex ID.
blocked_edges (list[tuple[int, int]]) – Optional edges the path cannot traverse.
Example
>>> path = mesh.shortest_surface_path(start_vertex, end_vertex)
- translate(self: pyvcad.pyvcad.SurfaceMesh, translation: pyvcad.pyvcad.Vec3) None#
Translates the mesh by the provided vector.
- property triangle_count#
Number of indexed mesh triangles.
- property triangle_labels#
Optional per-triangle integer labels, for example CAD face IDs from CADModel.to_surface_mesh(). Empty when the mesh has none. Assign a list with one label per triangle, or an empty list to clear. Clipping, components, decimation, remeshing, hole filling (new triangles get -1), merging, and selection.mesh() keep labels.
- property triangles#
Triangle connectivity.
- property vertex_count#
Number of mesh vertices.
- property vertices#
Mesh vertices.
- property volume#
Signed enclosed volume in cubic millimetres; positive for closed meshes wound outward.
- write_3mf(self: pyvcad.pyvcad.SurfaceMesh, output_file_name: str) None#
Writes the mesh to a 3MF file.
- write_stl(self: pyvcad.pyvcad.SurfaceMesh, output_file_name: str) None#
Writes the mesh to a binary STL file.
- class pyvcad.MeshSelection#
An immutable set of triangle IDs tied to one SurfaceMesh fingerprint.
- property area#
Total selected triangle area in square millimetres.
- boundary_edges(self: pyvcad.pyvcad.MeshSelection) list[Annotated[list[int], 'FixedSize(2)']]#
Return source vertex-index pairs along the selection boundary.
Example
>>> edges = selection.boundary_edges()
- boundary_loops(self: pyvcad.pyvcad.MeshSelection) list[PolylineCurve]#
Return the boundary of the selection as closed PolylineCurves, one per loop.
Loops follow the selected triangles’ winding; chains that do not close are left out.
Example
>>> border = selection.boundary_loops()[0]
- contains(self: pyvcad.pyvcad.MeshSelection, triangle_id: SupportsInt | SupportsIndex) bool#
Test whether a source triangle is selected.
- Parameters:
triangle_id (int) – Source triangle ID.
Example
>>> selected = selection.contains(10)
- difference(self: pyvcad.pyvcad.MeshSelection, other: pyvcad.pyvcad.MeshSelection) pyvcad.pyvcad.MeshSelection#
Return selected triangles not present in another matching selection.
- Parameters:
other (MeshSelection) – Selection to subtract.
Example
>>> remaining = first.difference(second)
- grown(self: pyvcad.pyvcad.MeshSelection, rings: SupportsInt | SupportsIndex = 1, cross_non_manifold: bool = False) pyvcad.pyvcad.MeshSelection#
Add edge-adjacent triangle rings around this selection.
- Parameters:
rings (int) – Number of neighboring rings to add.
cross_non_manifold (bool) – Allow growth across non-manifold edges.
Example
>>> expanded = selection.grown(2)
- intersection(self: pyvcad.pyvcad.MeshSelection, other: pyvcad.pyvcad.MeshSelection) pyvcad.pyvcad.MeshSelection#
Return the set intersection with a selection on matching source geometry.
- Parameters:
other (MeshSelection) – Selection to intersect.
Example
>>> shared = first.intersection(second)
- inverted(self: pyvcad.pyvcad.MeshSelection) pyvcad.pyvcad.MeshSelection#
Return every source triangle not currently selected.
Example
>>> opposite = selection.inverted()
- mesh(self: pyvcad.pyvcad.MeshSelection) pyvcad.pyvcad.SurfaceMesh#
Extract a compact, reindexed SurfaceMesh containing the selected triangles.
Example
>>> patch_mesh = selection.mesh()
- shrunk(self: pyvcad.pyvcad.MeshSelection, rings: SupportsInt | SupportsIndex = 1) pyvcad.pyvcad.MeshSelection#
Remove triangle rings from every open or unselected boundary.
- Parameters:
rings (int) – Number of boundary rings to remove.
Example
>>> inset = selection.shrunk(1)
- property source_fingerprint#
Source geometry fingerprint captured when the selection was created.
- property source_is_current#
Whether the source mesh still matches the captured fingerprint.
- property source_mesh#
Retained source SurfaceMesh.
- to_triangle_mesh_surface(self: pyvcad.pyvcad.MeshSelection, u_axis_hint: pyvcad.pyvcad.Vec3 | None = None, method: str = 'lscm') TriangleMeshSurface#
Convert the selection to a TriangleMeshSurface that can drive a CellMap.
Topology validation is intentionally deferred until this conversion: the patch must be a connected, manifold, genus-0 open patch. Interior holes are allowed and become trims. Only ‘lscm’ is near-conformal; ‘arap’ balances angle and area distortion, and ‘authalic’ preserves area. The result has outward_orientation_validated False; use TriangleMeshSurface.from_selection() when that evidence is needed.
- Parameters:
u_axis_hint (Vec3, optional) – World-space chart U direction.
method (str) – Flattening method: ‘lscm’, ‘arap’, or ‘authalic’.
Example
>>> surface = selection.to_triangle_mesh_surface()
- property triangle_count#
Number of selected triangles.
- property triangle_ids#
Sorted, unique source triangle IDs.
- union(self: pyvcad.pyvcad.MeshSelection, other: pyvcad.pyvcad.MeshSelection) pyvcad.pyvcad.MeshSelection#
Return the set union with a selection on matching source geometry.
- Parameters:
other (MeshSelection) – Selection to combine.
Example
>>> combined = first.union(second)
- class pyvcad.MeshHit#
A closest-point or ray hit on one triangle of a SurfaceMesh.
- property distance#
Euclidean distance from the query point or ray origin in millimetres.
- property point#
World-space hit or closest point in millimetres.
- property triangle_id#
Stable zero-based triangle ID in the queried mesh.
- class pyvcad.MeshPath#
A shortest path copied from a SurfaceMesh edge graph.
- property edges#
Ordered source vertex-index pairs along the path.
- property length#
Total mesh-edge path length in millimetres.
- property points#
Ordered world-space mesh vertices along the path.
- to_curve(self: pyvcad.pyvcad.MeshPath) PolylineCurve#
Return the path as a curve: an open PolylineCurve through its points.
Use it as a Tube or Sweep path, or for distance fields along the surface path.
Example
>>> path = mesh.shortest_surface_path(start_vertex, end_vertex) >>> rib = pv.Tube(path.to_curve(), 1.0)
- property vertex_ids#
Ordered source vertex IDs along the path.
- class pyvcad.CADModel#
A topology-preserving CAD model shared by selected faces and implicit CAD nodes.
- __init__(*args, **kwargs)#
- face(self: pyvcad.pyvcad.CADModel, index: SupportsInt | SupportsIndex) pyvcad.pyvcad.CADFace#
Return one face by stable index.
- Parameters:
index (int) – Zero-based face index.
- Raises:
IndexError – If the index is out of range.
Example
>>> face = model.face(0)
- property faces#
All faces in stable model order.
- static from_brep(path: str) pyvcad.pyvcad.CADModel#
Load an ASCII BREP model.
- Parameters:
path (str) – BREP file path.
Example
>>> model = pv.CADModel.from_brep('part.brep')
- static from_brep_bytes(data: bytes) pyvcad.pyvcad.CADModel#
Load in-memory ASCII BREP bytes.
- Parameters:
data (bytes) – ASCII BREP stream contents.
Example
>>> model = pv.CADModel.from_brep_bytes(data)
- static from_cadquery(value: object) pyvcad.pyvcad.CADModel#
Convert a CadQuery workplane, shape, or shape selection into a topology-preserving CAD model.
CadQuery is optional. Install OpenVCAD[cad] before calling this method.
- Parameters:
value (object) – CadQuery workplane, shape, or iterable of shapes to retain.
Example
>>> import cadquery as cq >>> model = pv.CADModel.from_cadquery(cq.Workplane('XY').box(10, 10, 10))
- static from_iges(path: str) pyvcad.pyvcad.CADModel#
Load an IGES model.
- Parameters:
path (str) – IGES or IGS file path.
Example
>>> model = pv.CADModel.from_iges('part.iges')
- static from_step(path: str) pyvcad.pyvcad.CADModel#
Load a STEP model.
- Parameters:
path (str) – STEP or STP file path.
Example
>>> model = pv.CADModel.from_step('part.step')
- select_faces(self: pyvcad.pyvcad.CADModel, indices: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], surface_type: object = None, normal: object = None, min_dot: SupportsFloat | SupportsIndex = -1.0, area_range: object = None, bounding_box_intersection: object = None) list[pyvcad.pyvcad.CADFace]#
Select imported CAD faces using stable geometric filters.
- Parameters:
indices (list[int]) – Optional stable indices.
surface_type (str | None) – Canonical surface type.
normal (Vec3 | None) – Requested representative direction.
min_dot (float) – Minimum normal-direction dot product.
area_range (tuple[float, float] | None) – Inclusive area limits.
bounding_box_intersection (tuple[Vec3, Vec3] | None) – Required box overlap.
- Returns:
The faces that pass every given filter, in index order.
- Return type:
list[CADFace]
- Raises:
RuntimeError – If min_dot is outside [-1, 1], normal is zero, an area limit is negative, or the area range is inverted.
Example
>>> upward = model.select_faces(normal=pv.Vec3(0, 0, 1), min_dot=0.8)
- to_node(self: pyvcad.pyvcad.CADModel, use_fast_mode: bool = False, fast_sdf_voxel_size: SupportsFloat | SupportsIndex | None = None) CAD#
Convert the retained CAD model into an implicit CAD node without reparsing.
- Parameters:
use_fast_mode (bool) – Build a discretized accelerated SDF during prepare.
fast_sdf_voxel_size (float | None) – Optional uniform SDF cache spacing in millimetres. Only valid with use_fast_mode=True. None uses the smallest sampling voxel dimension.
- Returns:
The CAD node, sharing this model’s geometry.
- Return type:
- Raises:
RuntimeError – If fast_sdf_voxel_size is given without use_fast_mode, or is not finite and positive.
Example
>>> node = model.to_node(use_fast_mode=True, fast_sdf_voxel_size=0.05)
- to_surface_mesh(self: pyvcad.pyvcad.CADModel, deflection: SupportsFloat | SupportsIndex = 0.1, angular_deflection: SupportsFloat | SupportsIndex = 20.0, relative: bool = False) pyvcad.pyvcad.SurfaceMesh#
Tessellate the exact CAD surfaces into a SurfaceMesh labelled by face.
mesh.triangle_labels[i] is the stable index of the CAD face triangle i came from (the same index as model.faces). Triangles follow the face orientation and shared edges are welded, so a closed solid gives a closed, outward-facing mesh. No voxel resampling.
- Parameters:
deflection (float) – Largest distance in millimetres between triangles and the surface.
angular_deflection (float) – Largest angle in degrees between neighbouring triangle normals along a curved face.
relative (bool) – Treat deflection as relative to edge size instead of millimetres.
- Raises:
RuntimeError – If deflection is not positive, angular_deflection is not between 0 and 180, or tessellation fails.
Example
>>> mesh = model.to_surface_mesh(deflection=0.05) >>> faces_seen = set(mesh.triangle_labels)
- class pyvcad.CADFace#
A stable topology-preserving face selected from a CADModel.
A CADFace is a ParametricSurface backed by the exact OCCT surface, so it can drive a CellMap. Its outward_orientation_validated is False both when the normal points into the owning solid and when the check is inconclusive (for example an open shell).
- __init__(*args, **kwargs)#
- property area#
Face area in square millimetres.
- property boundary_loop_count#
Number of boundary wires (the outer loop plus any holes).
- property centroid#
Area centroid in world coordinates.
- property index#
Stable zero-based face index within the parent model.
- property is_trimmed#
Whether the face is trimmed, that is, not bounded by its surface’s natural UV limits.
- property normal#
Representative oriented unit normal, taken at the sample nearest the UV centre that lies on the trimmed face. Reading it raises RuntimeError if no sample has a defined normal.
- property surface_type#
‘plane’, ‘cylinder’, ‘cone’, ‘sphere’, ‘torus’, ‘bezier’, ‘bspline’, ‘revolution’, ‘extrusion’, ‘offset’, or ‘other’.
- Type:
Canonical CAD surface type name
- class pyvcad.ParametricSurface#
Abstract surface evaluated on a rectangular UV domain, shared by CADFace and TriangleMeshSurface so either can drive a CellMap.
- property bounding_box#
World-space bounding box of the selected surface.
- contains(self: pyvcad.pyvcad.ParametricSurface, u: SupportsFloat | SupportsIndex, v: SupportsFloat | SupportsIndex, tolerance: SupportsFloat | SupportsIndex = 1e-07) bool#
Test whether native UV coordinates lie on the surface.
- Parameters:
u (float) – Native U coordinate.
v (float) – Native V coordinate.
tolerance (float) – Parametric tolerance for near-boundary coordinates.
Example
>>> inside = surface.contains(0.5, 0.5)
- normal_at(self: pyvcad.pyvcad.ParametricSurface, u: SupportsFloat | SupportsIndex, v: SupportsFloat | SupportsIndex) pyvcad.pyvcad.Vec3#
Evaluate the oriented unit normal at native UV coordinates.
- Parameters:
u (float) – Native U coordinate.
v (float) – Native V coordinate.
Example
>>> direction = surface.normal_at(0.5, 0.5)
- property outward_orientation_validated#
Whether positive normal orientation was validated against a source solid.
- point(self: pyvcad.pyvcad.ParametricSurface, u: SupportsFloat | SupportsIndex, v: SupportsFloat | SupportsIndex) pyvcad.pyvcad.Vec3#
Evaluate the surface position at native UV coordinates.
- Parameters:
u (float) – Native U coordinate.
v (float) – Native V coordinate.
Example
>>> position = surface.point(0.5, 0.5)
- property u_periodic#
Whether the native U direction wraps through a seam.
- property uv_bounds#
Native parameter rectangle as (minimum, maximum) UV corners.
- property v_periodic#
Whether the native V direction wraps through a seam.
- class pyvcad.TriangleMeshSurface#
An immutable triangle-mesh disk patch flattened into a UV chart so it can drive a CellMap like a CAD face. The patch may contain holes (vents): the longest boundary loop is the outer edge and every other loop is filled internally for flattening and then treated as trimmed. The flattening method is selectable: ‘lscm’ (default, free-boundary near-conformal), ‘arap’ (free-boundary as-rigid-as-possible), or ‘authalic’ (circular-border iterative area-preserving). Free-boundary charts keep the patch’s natural outline inside their UV bounding rectangle; contains() reports the real boundary so CellMap trimming stops the lattice at the patch edge. If the requested map folds, a guaranteed-injective convex-border mean-value parameterization is used instead.
- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: pyvcad.pyvcad.TriangleMeshSurface, surface_mesh: pyvcad.pyvcad.SurfaceMesh, u_axis_hint: pyvcad.pyvcad.Vec3 | None = None, method: str = ‘lscm’) -> None
Parameterize an existing SurfaceMesh disk patch.
- Parameters:
surface_mesh (SurfaceMesh) – Source disk patch; its data is copied.
u_axis_hint (Vec3, optional) – World-space direction the chart’s u-axis should follow across the patch.
method (str) – Flattening method: ‘lscm’, ‘arap’, or ‘authalic’.
Example
>>> surface = pv.TriangleMeshSurface(mesh, method='arap')
__init__(self: pyvcad.pyvcad.TriangleMeshSurface, path: str, u_axis_hint: pyvcad.pyvcad.Vec3 | None = None, method: str = ‘lscm’) -> None
Load and parameterize a disk patch from a mesh file.
- Parameters:
path (str) – Mesh file path. The mesh must be an open, genus-0 patch (holes allowed).
u_axis_hint (Vec3, optional) – World-space direction the chart’s u-axis should follow across the patch.
method (str) – Flattening method: ‘lscm’, ‘arap’, or ‘authalic’.
Example
>>> surface = pv.TriangleMeshSurface('patch.obj')
__init__(self: pyvcad.pyvcad.TriangleMeshSurface, vertices: collections.abc.Sequence[pyvcad.pyvcad.Vec3], triangles: collections.abc.Sequence[typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], “FixedSize(3)”]], u_axis_hint: pyvcad.pyvcad.Vec3 | None = None, method: str = ‘lscm’) -> None
Parameterize a disk patch from raw vertices and indexed triangles.
- Parameters:
Example
>>> surface = pv.TriangleMeshSurface(vertices, triangles)
- filled_mesh(self: pyvcad.pyvcad.TriangleMeshSurface) pyvcad.pyvcad.SurfaceMesh#
Return the patch with its holes filled, exactly as it was flattened. The input vertices and triangles come first, followed by the fill.
Example
>>> flattened = surface.filled_mesh()
- property filled_triangle_count#
Number of triangles added internally to fill holes for the parameterization.
- static from_selection(source_mesh: pyvcad.pyvcad.SurfaceMesh, triangle_ids: collections.abc.Sequence[SupportsInt | SupportsIndex], u_axis_hint: pyvcad.pyvcad.Vec3 | None = None) pyvcad.pyvcad.TriangleMeshSurface#
Extract and parameterize an explicitly selected open patch from a closed outward-oriented source mesh. Source triangle winding is preserved.
- Parameters:
source_mesh (SurfaceMesh) – Watertight source mesh retained unchanged.
triangle_ids (list[int]) – Stable source triangle indices.
u_axis_hint (Vec3, optional) – World-space chart U direction.
- Returns:
The selected patch, with outward_orientation_validated True.
- Return type:
- Raises:
RuntimeError – If the source mesh is not watertight or not outward oriented, if triangle_ids is empty, out of range, or repeats an ID, or if the patch is rejected.
- property hole_count#
Number of interior openings (boundary loops other than the longest, outer one). Holes are filled internally only to flatten the patch; contains() treats them as trimmed, so cell maps keep the lattice out of them.
- mesh(self: pyvcad.pyvcad.TriangleMeshSurface) pyvcad.pyvcad.SurfaceMesh#
Return an immutable copy of the patch as a SurfaceMesh.
Example
>>> patch_mesh = surface.mesh()
- property minimum_trim_feature#
Smallest hole width estimate in chart units (2 x area / perimeter), or 0 without holes. Cell-map trimming refines its sampling grid to resolve it.
- property parameterization_method#
‘free_boundary_lscm’, ‘free_boundary_arap’, or ‘convex_border_iterative_authalic’ for the requested primary map, or ‘convex_border_mean_value’ when the guaranteed-injective fallback was used.
- property source_triangle_ids#
Selected source triangle IDs, or an empty list for a standalone patch.
- property triangle_count#
Number of patch triangles.
- property uv_coordinates#
Per-vertex chart coordinates inside the reported UV bounds.
- property vertex_count#
Number of patch vertices.
- vertex_field(self: pyvcad.pyvcad.TriangleMeshSurface, values: collections.abc.Sequence[SupportsFloat | SupportsIndex]) FloatAttribute#
Return a FloatAttribute that interpolates one value per patch vertex.
A world point is projected to the closest point on the input patch (never onto a hole fill) and that triangle’s corner values are blended barycentrically, so points over holes or past the edge take the nearest patch value. Pass it as a cell-map height for a per-vertex variable height.
- Parameters:
values (list[float]) – One finite value per vertex, in vertex order.
Example
>>> height = surface.vertex_field(gaps)
- property vertex_normals#
Per-vertex angle-weighted unit normals.
- property vertices#
Patch vertices.
- class pyvcad.HeightField#
Base class for a normalized UV scalar field that returns physical relief height in mm.
- class pyvcad.ImageHeightField#
Mip-filtered grayscale/luminance PNG height map. Image values map to [0, amplitude_mm], and normalized (u, v) = (0, 0) is the lower-left image corner.
- __init__(self: pyvcad.pyvcad.ImageHeightField, path: str, amplitude_mm: SupportsFloat | SupportsIndex, channel: str = 'luminance', mapping: str = 'fit', repeats: Annotated[collections.abc.Sequence[SupportsInt | SupportsIndex], 'FixedSize(2)'] = [1, 1]) None#
Load a PNG as a height map.
The PNG is read at 16 bits per channel and box-filtered into a mip chain, so relief finer than the voxel size is averaged rather than aliased.
- Parameters:
path (str) – Path to the PNG file.
amplitude_mm (float) – Height in mm of a full-scale pixel; finite and non-negative.
channel (str) – ‘luminance’ (Rec. 709 weights), ‘red’, ‘green’ or ‘blue’. Default ‘luminance’.
mapping (str) – ‘fit’ stretches the image once over the UV square and clamps outside it; ‘repeat’ tiles it. Default ‘fit’.
repeats (tuple[int, int]) – Tile counts along u and v for ‘repeat’; must be (1, 1) for ‘fit’.
- Raises:
RuntimeError – If an argument is invalid or the PNG cannot be decoded.
Example
>>> import pyvcad as pv >>> relief = pv.ImageHeightField('texture.png', amplitude_mm=0.5, mapping='repeat', repeats=(4, 2))
- property amplitude_mm#
- property channel#
- property height#
- property mapping#
- property mip_level_count#
- property path#
- property repeats#
- sample(self: pyvcad.pyvcad.ImageHeightField, u: SupportsFloat | SupportsIndex, v: SupportsFloat | SupportsIndex, millimeters_per_u: SupportsFloat | SupportsIndex = 1.0, millimeters_per_v: SupportsFloat | SupportsIndex = 1.0, voxel_size: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x10471f570>) float#
Sample the filtered physical height at normalized UV coordinates.
- property width#
- class pyvcad.FunctionalHeightField#
Height source backed by a FloatAttribute sampled at normalized UV coordinates (x=u, y=v, z=0, d=0). The result is clamped to [0, 1] then scaled by amplitude_mm.
- __init__(self: pyvcad.pyvcad.FunctionalHeightField, function: FloatAttribute, amplitude_mm: SupportsFloat | SupportsIndex) None#
Create a height field from a FloatAttribute.
The attribute is sampled at (x=u, y=v, z=0) with d=0, where u and v are normalized surface coordinates. Its value is clamped to [0, 1] and multiplied by amplitude_mm.
- Parameters:
function (FloatAttribute) – The normalized height function.
amplitude_mm (float) – Height in mm of a value of 1; finite and non-negative.
- Raises:
RuntimeError – If function is None or amplitude_mm is invalid.
Example
>>> import pyvcad as pv >>> relief = pv.FunctionalHeightField(pv.FloatAttribute("x*y"), amplitude_mm=0.4)
- property amplitude_mm#
- sample(self: pyvcad.pyvcad.FunctionalHeightField, u: SupportsFloat | SupportsIndex, v: SupportsFloat | SupportsIndex, millimeters_per_u: SupportsFloat | SupportsIndex = 1.0, millimeters_per_v: SupportsFloat | SupportsIndex = 1.0, voxel_size: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x10471faf0>) float#
Sample the clamped physical height at normalized UV coordinates.
- class pyvcad.TrimMode#
Strategy for restricting a surface-built cell map to the surface’s true domain.
Members:
none : Keep the full rectangular logical domain; nothing is removed.
cells : Deactivate whole logical elements outside the surface domain (blocky).
boundary : Clip smoothly at the surface’s true boundary curve (default).
- boundary = <TrimMode.boundary: 2>#
- cells = <TrimMode.cells: 1>#
- TrimMode.name -> str
- none = <TrimMode.none: 0>#
- property value#
- class pyvcad.CellMap#
An immutable structured curvilinear coordinate map.
- __init__(*args, **kwargs)#
- static between_cad_faces(first: pyvcad.pyvcad.CADFace, second: pyvcad.pyvcad.CADFace, cells: typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], "FixedSize(3)"], linear: bool = False, trim: pyvcad.pyvcad.TrimMode = <TrimMode.boundary: 2>, auto_align: bool = True, flip_u: bool = False, flip_v: bool = False, exchange_uv: bool = False, first_origin: typing.Annotated[collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex], "FixedSize(2)"] | None = None, second_origin: typing.Annotated[collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex], "FixedSize(2)"] | None = None, standoff: typing.SupportsFloat | typing.SupportsIndex = 0.0) pyvcad.pyvcad.CellMap#
Construct a curvilinear volume between two CAD faces.
- Parameters:
first (CADFace) – First boundary face.
second (CADFace) – Second boundary face.
cells (tuple[int, int, int]) – Positive U/V/W counts.
linear (bool) – Use linear rather than midpoint-sampled curved cells.
trim (TrimMode) – How to restrict the map to the faces’ common true domain.
auto_align (bool) – Search compatible UV symmetries.
flip_u (bool) – Flip the second U direction in advanced mode.
flip_v (bool) – Flip the second V direction in advanced mode.
exchange_uv (bool) – Exchange second-face U and V in advanced mode.
first_origin (tuple[float, float] | None) – Normalized periodic UV origin shift.
second_origin (tuple[float, float] | None) – Normalized periodic UV origin shift.
standoff (float) – Signed shift of the first surface along its oriented normal in millimetres before interpolating; 0 leaves the map unchanged.
Example
>>> cell_map = pv.CellMap.between_cad_faces(first, second, (12, 8, 3))
- static between_surfaces(first: pyvcad.pyvcad.ParametricSurface, second: pyvcad.pyvcad.ParametricSurface, cells: typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], "FixedSize(3)"], linear: bool = False, trim: pyvcad.pyvcad.TrimMode = <TrimMode.boundary: 2>, auto_align: bool = True, flip_u: bool = False, flip_v: bool = False, exchange_uv: bool = False, first_origin: typing.Annotated[collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex], "FixedSize(2)"] | None = None, second_origin: typing.Annotated[collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex], "FixedSize(2)"] | None = None, standoff: typing.SupportsFloat | typing.SupportsIndex = 0.0) pyvcad.pyvcad.CellMap#
Construct a curvilinear volume between two parametric surfaces of any type.
- Parameters:
first (ParametricSurface) – First boundary surface.
second (ParametricSurface) – Second boundary surface.
cells (tuple[int, int, int]) – Positive U/V/W counts.
linear (bool) – Use linear rather than midpoint-sampled curved cells.
trim (TrimMode) – How to restrict the map to the surfaces’ common true domain.
auto_align (bool) – Search compatible UV symmetries.
flip_u (bool) – Flip the second U direction in advanced mode.
flip_v (bool) – Flip the second V direction in advanced mode.
exchange_uv (bool) – Exchange second-surface U and V in advanced mode.
first_origin (tuple[float, float] | None) – Normalized periodic UV origin shift.
second_origin (tuple[float, float] | None) – Normalized periodic UV origin shift.
standoff (float) – Signed shift of the first surface along its oriented normal in millimetres before interpolating; 0 leaves the map unchanged.
Example
>>> cell_map = pv.CellMap.between_surfaces(first, second, (12, 8, 3))
- property bounds#
World-coordinate bounding box.
- property cell_index#
Deterministically owned integer cell index as a Vec3Attribute adapter.
- property cells#
Positive logical U/V/W cell counts.
- static cylindrical(center: pyvcad.pyvcad.Vec3, inner_radius: typing.SupportsFloat | typing.SupportsIndex, outer_radius: typing.SupportsFloat | typing.SupportsIndex, height: typing.SupportsFloat | typing.SupportsIndex, cells: typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], "FixedSize(3)"], axis: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x10472a930>, reference_direction: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x10472a970>, start_angle_degrees: typing.SupportsFloat | typing.SupportsIndex = 0.0, sweep_degrees: typing.SupportsFloat | typing.SupportsIndex = 360.0, linear: bool = False) pyvcad.pyvcad.CellMap#
Construct an analytic annular-cylinder map.
U follows azimuth, V follows the cylinder axis from lower to upper, and W follows radius from the inner to the outer boundary.
- Parameters:
center (Vec3) – Axial midpoint in millimetres.
inner_radius (float) – Positive inner radius in millimetres.
outer_radius (float) – Outer radius in millimetres.
height (float) – Positive total axial height in millimetres.
cells (tuple[int, int, int]) – Circumferential, axial, and radial counts.
axis (Vec3) – Cylinder axis and positive V direction.
reference_direction (Vec3) – Projected direction defining the zero-angle seam.
start_angle_degrees (float) – Angular position of U = 0.
sweep_degrees (float) – Positive angular sweep up to 360 degrees.
linear (bool) – Use linear rather than midpoint-refined curved cells.
Example
>>> cell_map = pv.CellMap.cylindrical(pv.Vec3(0, 0, 0), 16.0, 20.0, 30.0, (16, 6, 1))
- domain_signed_distance(self: pyvcad.pyvcad.CellMap, world: pyvcad.pyvcad.Vec3) float#
Return signed distance to the finite active CellMap domain.
- Parameters:
world (Vec3) – World-coordinate query point.
Example
>>> distance = cell_map.domain_signed_distance(world)
- forward(self: pyvcad.pyvcad.CellMap, logical: pyvcad.pyvcad.Vec3) pyvcad.pyvcad.Vec3#
Map a logical point into world space.
- Parameters:
logical (Vec3) – Logical U/V/W coordinate.
Example
>>> world = cell_map.forward(pv.Vec3(0.5, 0.5, 0.5))
- static from_cad_face(face: pyvcad.pyvcad.CADFace, cells: typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], "FixedSize(3)"], height: typing.SupportsFloat | typing.SupportsIndex, linear: bool = False, trim: pyvcad.pyvcad.TrimMode = <TrimMode.boundary: 2>, standoff: typing.SupportsFloat | typing.SupportsIndex = 0.0) pyvcad.pyvcad.CellMap#
Construct a signed-height map from one CAD face.
- Parameters:
face (CADFace) – Source CAD face.
cells (tuple[int, int, int]) – Positive U/V/W counts.
height (float) – Total signed normal height in millimetres.
linear (bool) – Use linear rather than midpoint-sampled curved cells.
trim (TrimMode) – How to restrict the map to the trimmed face’s true domain.
standoff (float) – Signed stand-off distance along the face normal at which the map begins.
Example
>>> cell_map = pv.CellMap.from_cad_face(face, (8, 8, 1), 2.0)
- static from_surface(surface: pyvcad.pyvcad.ParametricSurface, cells: typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], "FixedSize(3)"], height: object, linear: bool = False, trim: pyvcad.pyvcad.TrimMode = <TrimMode.boundary: 2>, standoff: typing.SupportsFloat | typing.SupportsIndex = 0.0) pyvcad.pyvcad.CellMap#
Construct a signed-height map from any parametric surface.
The height may vary: a FloatAttribute is sampled once per cell-map column at the column’s base point on the surface, and a per-vertex sequence on a TriangleMeshSurface is interpolated across the patch (see TriangleMeshSurface.vertex_field). A variable height must be finite, non-zero, and of one sign everywhere; a constant field reproduces the constant-height map exactly.
- Parameters:
surface (ParametricSurface) – Source CAD face or triangle-mesh patch.
cells (tuple[int, int, int]) – Positive U/V/W counts.
height (float | FloatAttribute | list[float]) – Total signed normal height in millimetres: a constant, a field, or one value per TriangleMeshSurface vertex.
linear (bool) – Use linear rather than midpoint-sampled curved cells.
trim (TrimMode) – How to restrict the map to the surface’s true domain.
standoff (float) – Signed stand-off distance along the surface normal at which the map begins, so it spans [standoff, standoff + height].
Example
>>> cell_map = pv.CellMap.from_surface(surface, (12, 12, 1), 2.0, standoff=4.0)
- property has_boundary_trim#
Whether the map carries an implicit true-boundary clip.
- in_coordinates(self: pyvcad.pyvcad.CellMap, attribute: Attribute, coordinates: str) Attribute#
Wrap an attribute so its x, y, and z inputs use this CellMap.
- Parameters:
attribute (Attribute) – Attribute to sample in mapped coordinates.
coordinates (str) – ‘node’ (the consuming node’s own coordinates, no reframing), ‘map’ (logical coordinates divided by the cell counts, in [0, 1]), ‘logical’ (measured in cells), ‘cell_index’ (integer index of the containing cell), or ‘cell’ (position inside the unit cell, in [0, 1) per axis).
- Raises:
RuntimeError – If coordinates is not one of the names above.
Example
>>> color = cell_map.in_coordinates(pv.Vec4Attribute('x', '1-x', 'z', '1'), 'cell')
- inverse(self: pyvcad.pyvcad.CellMap, world: pyvcad.pyvcad.Vec3, tolerance: SupportsFloat | SupportsIndex = 1e-06, max_iterations: SupportsInt | SupportsIndex = 24) object#
Invert a world point into logical coordinates.
- Parameters:
world (Vec3) – World-coordinate point.
tolerance (float) – Requested Newton convergence tolerance; a scale-aware numerical floor is applied.
max_iterations (int) – Maximum damped Newton iterations.
Example
>>> logical = cell_map.inverse(world)
- jacobian(self: pyvcad.pyvcad.CellMap, logical: pyvcad.pyvcad.Vec3) Annotated[list[pyvcad.pyvcad.Vec3], 'FixedSize(3)']#
Return world derivatives with respect to U, V, and W.
Raises RuntimeError when the logical coordinate lies outside the map or in a trimmed (inactive) element, for example at a chart corner of a TrimMode.boundary map.
- Parameters:
logical (Vec3) – Logical U/V/W coordinate.
Example
>>> du, dv, dw = cell_map.jacobian(pv.Vec3(0.5, 0.5, 0.5))
- jacobian_determinant(self: pyvcad.pyvcad.CellMap, logical: pyvcad.pyvcad.Vec3) float#
Evaluate the local map Jacobian determinant.
- Parameters:
logical (Vec3) – Logical U/V/W coordinate.
Example
>>> determinant = cell_map.jacobian_determinant(pv.Vec3(0.5, 0.5, 0.5))
- property jacobian_determinant_field#
Jacobian determinant as a world-sampled float attribute.
- property logical_position#
Logical lattice position as an explicit Vec3Attribute adapter.
- property maximum_principal_stretch_field#
Maximum principal stretch as a world-sampled float attribute.
- property middle_principal_stretch_field#
Middle principal stretch as a world-sampled float attribute.
- property minimum_principal_stretch_field#
Minimum principal stretch as a world-sampled float attribute.
- property periodic_axes#
Periodic U/V/W connectivity flags.
- principal_stretches(self: pyvcad.pyvcad.CellMap, logical: pyvcad.pyvcad.Vec3) pyvcad.pyvcad.Vec3#
Return ascending directional stretch estimates.
- Parameters:
logical (Vec3) – Logical U/V/W coordinate.
Example
>>> stretches = cell_map.principal_stretches(pv.Vec3(0.5, 0.5, 0.5))
- static rectangular(minimum: pyvcad.pyvcad.Vec3, maximum: pyvcad.pyvcad.Vec3, cells: Annotated[collections.abc.Sequence[SupportsInt | SupportsIndex], 'FixedSize(3)'], linear: bool = True) pyvcad.pyvcad.CellMap#
Construct a rectangular map.
- Parameters:
Example
>>> cell_map = pv.CellMap.rectangular(pv.Vec3(0, 0, 0), pv.Vec3(10, 10, 10), (2, 2, 2))
- static spherical(center: pyvcad.pyvcad.Vec3, inner_radius: typing.SupportsFloat | typing.SupportsIndex, outer_radius: typing.SupportsFloat | typing.SupportsIndex, latitude_bounds_degrees: typing.Annotated[collections.abc.Sequence[typing.SupportsFloat | typing.SupportsIndex], "FixedSize(2)"], cells: typing.Annotated[collections.abc.Sequence[typing.SupportsInt | typing.SupportsIndex], "FixedSize(3)"], north_axis: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x1046ea230>, reference_direction: pyvcad.pyvcad.Vec3 = <pyvcad.pyvcad.Vec3 object at 0x10472ab30>, start_longitude_degrees: typing.SupportsFloat | typing.SupportsIndex = 0.0, longitude_sweep_degrees: typing.SupportsFloat | typing.SupportsIndex = 360.0, linear: bool = False) pyvcad.pyvcad.CellMap#
Construct an analytic spherical-shell band map.
U follows longitude, V follows latitude from south to north, and W follows radius from the inner to the outer boundary.
- Parameters:
center (Vec3) – Sphere center in millimetres.
inner_radius (float) – Positive inner radius in millimetres.
outer_radius (float) – Outer radius in millimetres.
latitude_bounds_degrees (tuple[float, float]) – South/north bounds inside (-90, 90).
cells (tuple[int, int, int]) – Longitude, latitude, and radial counts.
north_axis (Vec3) – North direction and positive V orientation.
reference_direction (Vec3) – Projected direction defining the zero-longitude seam.
start_longitude_degrees (float) – Longitude of U = 0.
longitude_sweep_degrees (float) – Positive longitude sweep up to 360 degrees.
linear (bool) – Use linear rather than midpoint-refined curved cells.
Example
>>> cell_map = pv.CellMap.spherical(pv.Vec3(0, 0, 0), 18.0, 22.0, (-60.0, 60.0), (16, 8, 1))
- to_cell_frame(self: pyvcad.pyvcad.CellMap, vector: Vec3Attribute) Vec3Attribute#
Convert a raw Cartesian vector attribute through the inverse CellMap Jacobian.
- Parameters:
vector (Vec3Attribute) – Raw direction or displacement in consuming coordinates.
Example
>>> local_direction = cell_map.to_cell_frame(direction)
- to_map_direction(self: pyvcad.pyvcad.CellMap, vector: Vec3Attribute) Vec3Attribute#
Convert a world-space vector through the inverse CellMap Jacobian.
This is the direction-focused alias of to_cell_frame(). The result is not normalized.
- to_world_direction(self: pyvcad.pyvcad.CellMap, vector: Vec3Attribute) Vec3Attribute#
Convert a vector expressed in logical map coordinates through the CellMap Jacobian.
The result is not normalized, so it can represent either a direction or a displacement.
- Parameters:
vector (Vec3Attribute) – Direction or displacement in logical U/V/W coordinates.
Example
>>> world_direction = cell_map.to_world_direction(pv.Vec3Attribute(1, 0, 0)).normalized()
- property trim_mode#
The TrimMode the map was built with.
- property u_field#
Logical U coordinate as a float attribute.
- property unit_cell_phase#
Fractional unit-cell phase as an explicit Vec3Attribute adapter.
- property v_field#
Logical V coordinate as a float attribute.
- validate(self: pyvcad.pyvcad.CellMap) pyvcad.pyvcad.CellMapDiagnostics#
Validate Jacobians, inverse lookup, trim statistics, and aspect ratio.
Example
>>> diagnostics = cell_map.validate()
- property w_field#
Logical W coordinate as a float attribute.
- static warp(base: pyvcad.pyvcad.CellMap, u_scale: object = None, v_scale: object = None, w_scale: object = None, lock_u_bounds: bool = True, lock_v_bounds: bool = True, lock_w_bounds: bool = True) pyvcad.pyvcad.CellMap#
Return a new map with the same cells but a graded cell spacing along U, V, and/or W.
Along each axis, every element’s logical width is weighted by exp(clamp(s, -4, 4)), where s is the scale attribute sampled at the element’s midpoint on the base map. The scale is a natural-log exponent, not a relative weight: 0 (or None) keeps the spacing uniform, +1 makes a cell about 2.7 times wider than a cell at 0, and -1 about 2.7 times narrower. The attribute is sampled with the base map’s unwarped world position as x, y, z, and with the base map’s logical and cell coordinates available for cell-map attributes. It must return a finite scalar.
With a locked axis, the weights are normalized so the axis still spans its full logical range and both opposite boundaries stay where they are; only the distribution of cells changes. With an unlocked axis, each cell’s width is multiplied by its weight, so the far boundary moves (the map is continued linearly past the base map’s end) while the logical-0 boundary stays fixed.
The requested spacing is smoothed. If the result folds the map (fails validate()), the warp is blended back toward the base map, halving its strength each time, until the map is valid.
Maps clipped by a boundary trim (has_boundary_trim is True) cannot be warped. TrimMode.boundary is the default for the surface factories, so build the base map with trim=TrimMode.none or TrimMode.cells before warping.
- Parameters:
base (CellMap) – Base map.
u_scale (FloatAttribute | float | None) – Log-scale exponent for U cell widths. None means 0.
v_scale (FloatAttribute | float | None) – Log-scale exponent for V cell widths. None means 0.
w_scale (FloatAttribute | float | None) – Log-scale exponent for W cell widths. None means 0.
lock_u_bounds (bool) – Keep both U boundaries fixed and only redistribute the cells.
lock_v_bounds (bool) – Keep both V boundaries fixed and only redistribute the cells.
lock_w_bounds (bool) – Keep both W boundaries fixed and only redistribute the cells.
- Returns:
The warped map, with the base map’s cells, periodicity, active elements, and trim mode.
- Return type:
- Raises:
TypeError – If a scale is not a FloatAttribute, a number, or None.
RuntimeError – If the base map has a boundary trim, a scale attribute returns a non-finite or non-scalar value, or the warp still folds the map after being scaled down to 1e-4 strength.
Example
>>> import pyvcad as pv >>> cell_map = pv.CellMap.rectangular(pv.Vec3(0, 0, 0), pv.Vec3(10, 10, 10), (5, 5, 5)) >>> # Cells grow along x: narrow near x = 0, wide near x = 10. >>> warped = pv.CellMap.warp(cell_map, u_scale=pv.FloatAttribute("x / 10"))
- class pyvcad.CellMapCollection#
An immutable, non-empty collection of independently parameterized cell maps.
Each map keeps its own logical coordinates, for example one map per CAD face or surface patch.
- __init__(self: pyvcad.pyvcad.CellMapCollection, maps: collections.abc.Sequence[pyvcad.pyvcad.CellMap]) None#
Construct a map collection.
- Parameters:
maps (list[CellMap]) – Independent cell maps.
- Raises:
RuntimeError – If maps is empty or contains None.
Example
>>> collection = pv.CellMapCollection([first, second])
- property maps#
Independent maps in collection order.
- validate(self: pyvcad.pyvcad.CellMapCollection) list[pyvcad.pyvcad.CellMapDiagnostics]#
Validate every independent map.
Example
>>> diagnostics = collection.validate()
- class pyvcad.CellMapDiagnostics#
Validation evidence for a structured curvilinear cell map, returned by CellMap.validate().
The Jacobian is sampled at the eight corners and the centre of every active structured element.
- property active_element_count#
Number of active structured elements.
- property inverse_solver_failures#
Active elements whose world-space centre does not invert back to its logical centre.
- property inverted_cell_count#
Active elements with a non-positive or non-finite sampled Jacobian determinant.
- property maximum_aspect_ratio#
Largest ratio of the longest to the shortest Jacobian column over all samples.
- property maximum_jacobian_determinant#
Largest sampled Jacobian determinant (0 when no element is active).
- property minimum_jacobian_determinant#
Smallest sampled Jacobian determinant (0 when no element is active).
- property non_neighbor_overlap_count#
Pairs of non-adjacent elements that overlap in world space (only counted when no element is inverted).
- property trimmed_element_count#
Number of inactive (trimmed) structured elements.
- property valid#
Whether all mandatory validation checks passed.
- pyvcad.ray_distances(origins: collections.abc.Sequence[pyvcad.pyvcad.Vec3], directions: collections.abc.Sequence[pyvcad.pyvcad.Vec3], target: object, max_distance: SupportsFloat | SupportsIndex, tolerance: SupportsFloat | SupportsIndex = 0.001, voxel_size: SupportsFloat | SupportsIndex = 0.25) list[float]#
Measure the distance along each ray to its first hit on a target.
A SurfaceMesh or TriangleMeshSurface target is hit by exact ray-triangle intersection, so open meshes such as a shell’s inner surface work. Any other node is sphere-traced against its signed distance field: a private clone is prepared with voxel_size and a bandwidth of max_distance, a hit is a field value within tolerance of zero or a sign change refined by bisection. Rays run in parallel. Units are mm.
- Parameters:
origins (list[Vec3]) – Ray start points.
directions (list[Vec3]) – Non-zero ray directions, normalized internally.
target (Node | SurfaceMesh | TriangleMeshSurface) – What the rays hit.
max_distance (float) – Longest ray.
tolerance (float) – Hit tolerance for sphere-traced node targets.
voxel_size (float) – Voxel size used to prepare a node target.
- Returns:
One distance per ray, NaN where nothing is hit.
- Return type:
list[float]
- Raises:
TypeError – If target is not a Node, SurfaceMesh or TriangleMeshSurface.
Example
>>> import pyvcad as pv >>> sphere = pv.Sphere(pv.Vec3(0, 0, 0), 10.0) >>> gaps = pv.ray_distances([pv.Vec3(0, 0, 0)], [pv.Vec3(1, 0, 0)], sphere, 60.0)
- class pyvcad.ImplicitUnitCell#
A custom periodic implicit unit cell in normalized coordinates.
- __init__(self: pyvcad.pyvcad.ImplicitUnitCell, value: object, gradient: object = None, name: str = 'custom') None#
Construct a custom periodic implicit unit cell.
- Parameters:
value (callable) – Scalar callback over normalized u, v, w; numba.cfunc is the native fast path.
gradient (callable | None) – Optional analytic gradient f(u, v, w) returning a Vec3. When None, central finite differences are used.
name (str) – Diagram and inspection name.
Example
>>> cell = pv.ImplicitUnitCell(lambda u, v, w: math.sin(2 * math.pi * u))
- static mixed(first: pyvcad.pyvcad.ImplicitUnitCell, second: pyvcad.pyvcad.ImplicitUnitCell, weight: object) pyvcad.pyvcad.ImplicitUnitCell#
Mix two periodic implicit cells with a scalar attribute.
The weight is clamped to [0, 1] and the two raw fields are interpolated linearly. Both source cells must pass validate_periodicity(); the mixed cell is not periodic.
- Parameters:
first (ImplicitUnitCell) – Cell selected by a zero weight.
second (ImplicitUnitCell) – Cell selected by a one weight.
weight (float | FloatAttribute | ScalarParameter | numba.cfunc | callable) – Transition weight, sampled with the consuming map’s context.
Example
>>> weight = pv.FloatAttribute(0.5) >>> cell = pv.ImplicitUnitCell.mixed(first, second, weight)
- property name#
Inspection name.
- static standard(name: str) pyvcad.pyvcad.ImplicitUnitCell#
Return a standard TPMS unit cell by name.
- Parameters:
name (str) – One of ‘gyroid’, ‘schwarz_p’, ‘schwarz_d’, ‘neovius’, ‘iwp’, ‘lidinoid’, ‘fischer_koch_s’, ‘frd’ or ‘split_p’. Hyphens may replace underscores.
- Raises:
RuntimeError – If the name is unknown.
Example
>>> cell = pv.ImplicitUnitCell.standard('gyroid')
- validate_periodicity(self: pyvcad.pyvcad.ImplicitUnitCell, tolerance: SupportsFloat | SupportsIndex = 1e-06) bool#
Compare opposite unit-cell boundaries.
Samples a 5x5 grid on each pair of opposite faces. Mixed cells always pass.
- Parameters:
tolerance (float) – Maximum scalar mismatch.
- Returns:
True when every sample pair agrees within the tolerance.
- Return type:
bool
Example
>>> assert cell.validate_periodicity()
- class pyvcad.GraphUnitCell#
A normalized indexed graph unit cell with optional tags.
- __init__(self: pyvcad.pyvcad.GraphUnitCell, vertices: collections.abc.Sequence[pyvcad.pyvcad.Vec3], edges: collections.abc.Sequence[tuple[SupportsInt | SupportsIndex, SupportsInt | SupportsIndex]], vertex_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], edge_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], orientation_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], material_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = []) None#
Construct a normalized graph unit cell.
- Parameters:
vertices (list[Vec3]) – Normalized vertices in [0, 1].
edges (list[tuple[int, int]]) – Indexed edges.
vertex_tags (list[int]) – Optional per-vertex tags.
edge_tags (list[int]) – Optional per-edge tags.
orientation_tags (list[int]) – Optional per-edge orientation tags.
material_tags (list[int]) – Optional per-edge material IDs in [0, 255], or -1 for none.
Example
>>> cell = pv.GraphUnitCell([pv.Vec3(0, 0, 0), pv.Vec3(1, 1, 1)], [(0, 1)])
- property edge_tags#
Per-edge tags.
- property edges#
Indexed edges.
- property material_tags#
Per-edge material tags.
- property orientation_tags#
Per-edge orientation tags.
- property vertex_tags#
Per-vertex tags.
- property vertices#
Normalized vertices.
- class pyvcad.FaceUnitCell#
A reusable normalized indexed triangle-and-quad face unit cell.
- __init__(self: pyvcad.pyvcad.FaceUnitCell, vertices: collections.abc.Sequence[pyvcad.pyvcad.Vec3], faces: collections.abc.Sequence[collections.abc.Sequence[SupportsInt | SupportsIndex]], vertex_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], face_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], orientation_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = [], material_tags: collections.abc.Sequence[SupportsInt | SupportsIndex] = []) None#
Construct a static face unit cell.
- Parameters:
vertices (list[Vec3]) – Finite normalized vertices in [0, 1].
faces (list[list[int]]) – Indexed triangular or quadrilateral faces.
vertex_tags (list[int]) – Optional per-vertex tags.
face_tags (list[int]) – Optional per-face tags.
orientation_tags (list[int]) – Optional per-face orientation tags.
material_tags (list[int]) – Optional per-face material IDs in [0, 255], or -1 for none.
Example
>>> cell = pv.FaceUnitCell([pv.Vec3(0, 0, 0), pv.Vec3(1, 0, 0), pv.Vec3(1, 1, 0), pv.Vec3(0, 1, 0)], [[0, 1, 2, 3]])
- property face_tags#
Per-face tags.
- property faces#
Indexed triangular and quadrilateral faces.
- property material_tags#
Per-face material IDs.
- property orientation_tags#
Per-face orientation tags.
- property period#
Read-only tiling period on logical axes.
- property vertex_tags#
Per-vertex tags.
- property vertices#
Normalized vertices.
- class pyvcad.PlateUnitCell#
The native period-two folded plate cell with legacy eccentricity semantics.
- __init__(self: pyvcad.pyvcad.PlateUnitCell, eccentricity: object) None#
Construct a folded plate unit cell.
Eccentricity is sampled at undeformed logical cell centers. A value of 1.0 is flat; all sampled values must be positive and finite.
- Parameters:
eccentricity (float | FloatAttribute | ScalarParameter | numba.cfunc | callable) – Positive eccentricity field.
Example
>>> cell = pv.PlateUnitCell(0.7)
- property eccentricity#
Legacy eccentricity field sampled at cell centers.
Seed points and surface Voronoi diagrams#
- pyvcad.sample_poisson_seeds(host: pyvcad.pyvcad.Node, spacing: object, seed: SupportsInt | SupportsIndex = 0, max_count: SupportsInt | SupportsIndex = 0, boundary_clearance: SupportsFloat | SupportsIndex = 0.0, attempts_per_point: SupportsInt | SupportsIndex = 30) pyvcad.pyvcad.PoissonSeedResult#
Sample variable-spacing Poisson-disk seed points inside a prepared host.
Two points are accepted together when their distance is at least the mean of their local spacings. Growth starts from random darts and fills the host front by front, so it scales to 10^5 points. Results depend only on the inputs.
- Parameters:
host (Node) – Prepared host; points satisfy SDF <= -boundary_clearance.
spacing (float | FloatAttribute | ScalarParameter | numba.cfunc | callable) – Positive local spacing in millimetres.
seed (int) – Random seed.
max_count (int) – Maximum number of points, or 0 for no limit.
boundary_clearance (float) – Distance kept from the host surface.
attempts_per_point (int) – Candidates tried around each active point.
Example
>>> host.prepare(pv.Vec3(0.5, 0.5, 0.5), 1.0) >>> seeds = pv.sample_poisson_seeds(host, 4.0, seed=3)
- class pyvcad.PoissonSeedResult#
Seed points from sample_poisson_seeds() with sampling statistics.
- property candidate_count#
Number of candidate positions tested.
- property points#
Accepted world-space seed points.
- property rejected_count#
Number of rejected candidates.
- property spacings#
Local spacing sampled at each accepted point.
- pyvcad.sample_surface_poisson_seeds(mesh: pyvcad.pyvcad.SurfaceMesh, spacing: object, seed: SupportsInt | SupportsIndex = 0, max_count: SupportsInt | SupportsIndex = 0, attempts_per_point: SupportsInt | SupportsIndex = 30) pyvcad.pyvcad.SurfaceSeedResult#
Sample variable-spacing Poisson-disk seed points on a triangle surface.
Darts land uniformly by area and are kept when their straight-line distance to every kept point is at least the mean of their local spacings, until a long run of darts finds no room. Each dart needs only its own triangle, so open, non-manifold and noisy scanned meshes work. The spacing field is sampled on the surface with d = 0. Keep the spacing below the thickness of thin walls. Results depend only on the inputs.
- Parameters:
mesh (SurfaceMesh) – The triangle surface.
spacing (float | FloatAttribute | ScalarParameter | numba.cfunc | callable) – Positive local spacing in millimetres.
seed (int) – Random seed.
max_count (int) – Maximum number of points, or 0 for no limit.
attempts_per_point (int) – Rejected darts allowed per kept point before stopping.
Example
>>> mesh = pv.SurfaceMesh(pv.Sphere(pv.Vec3(0, 0, 0), 20.0), 0.5) >>> seeds = pv.sample_surface_poisson_seeds(mesh, 5.0, seed=2)
- class pyvcad.SurfaceSeedResult#
Seed points on a triangle surface from sample_surface_poisson_seeds().
- property candidate_count#
Number of candidate positions tested.
- property points#
Accepted seed points on the surface.
- property rejected_count#
Number of rejected candidates.
- property spacings#
Local spacing sampled at each accepted point.
- property triangle_ids#
Index of the triangle each point lies on.
- pyvcad.restricted_voronoi(mesh: pyvcad.pyvcad.SurfaceMesh, seeds: object) pyvcad.pyvcad.SurfaceVoronoi#
Compute the Voronoi diagram of seed points restricted to a triangle surface.
This is the 3D Voronoi diagram of the seeds cut by the surface: each seed owns the part of the surface closer to it (in a straight line) than to any other seed. Every triangle is clipped on its own, exactly, so open, non-manifold and noisy scanned meshes work. Seeds from sample_surface_poisson_seeds() give even cells.
- Parameters:
mesh (SurfaceMesh) – The triangle surface.
seeds (list[Vec3] | numpy.ndarray) – Seed points, (N, 3).
Example
>>> import pyvcad as pv >>> seeds = pv.sample_surface_poisson_seeds(mesh, 4.0, seed=1) >>> diagram = pv.restricted_voronoi(mesh, seeds.points) >>> diagram.segments.shape
- class pyvcad.SurfaceVoronoi#
The Voronoi diagram of seed points restricted to a triangle surface.
Each seed owns the part of the surface closer to it than to any other seed. The boundaries between those regions are returned as straight pieces, one per triangle they cross, in triangle order.
- property cell_areas#
Surface area in mm^2 owned by each seed, as an array.
- property seed_pairs#
The two seeds whose cells meet along each piece, as an (N, 2) array (smaller first).
- property segments#
Boundary pieces as an (N, 2, 3) array of end points in millimetres.
- property triangle_ids#
The triangle that contains each piece, as an (N,) array.
- pyvcad.select_points_in_host(host: pyvcad.pyvcad.Node, points: collections.abc.Sequence[pyvcad.pyvcad.Vec3], boundary_clearance: SupportsFloat | SupportsIndex = 0.0) list[int]#
Return the indices of points inside a prepared host.
- Parameters:
Example
>>> kept = pv.select_points_in_host(host, points)
- pyvcad.blend_seed_sets(host: pyvcad.pyvcad.Node, random_points: collections.abc.Sequence[pyvcad.pyvcad.Vec3], regular_points: collections.abc.Sequence[pyvcad.pyvcad.Vec3], regularity: object, match_radius: SupportsFloat | SupportsIndex, minimum_separation: SupportsFloat | SupportsIndex = 0.0, boundary_clearance: SupportsFloat | SupportsIndex = 0.0) pyvcad.pyvcad.SeedBlendResult#
Morph random seeds into regular lattice sites with a regularity field.
Sites with regularity w > 0 are paired with nearby random seeds (shortest pairs first, within match_radius). Each pair becomes one seed at q + w (r - q), so the seed count is preserved while seeds slide onto the sites as w rises to 1. Unpaired sites are kept where w >= 0.5 and unpaired random seeds where w < 0.5. Seeds closer than minimum_separation to a more regular seed are dropped.
- Parameters:
host (Node | None) – Optional prepared host for a containment check.
random_points (list[Vec3]) – Random seeds.
regular_points (list[Vec3]) – Regular lattice sites.
regularity (float | FloatAttribute | ScalarParameter | numba.cfunc | callable) – 0 keeps random seeds, 1 keeps sites.
match_radius (float) – Maximum pairing distance in millimetres.
minimum_separation (float) – Minimum distance between output seeds.
boundary_clearance (float) – Host clearance for the containment check.
Example
>>> blend = pv.blend_seed_sets(host, random, sites, weight, 3.0, 1.2)
- class pyvcad.SeedBlendResult#
Seeds that change from a random point set into a regular point set.
- property matched_count#
Number of random points paired with a regular site.
- property points#
Output world-space seed points.
- property random_index#
Source random point of each point, or -1.
- property regular_index#
Source regular site of each point, or -1.
- property regularity#
Regularity weight in [0, 1] that placed each output point.
- property separation_dropped_count#
Number of points removed by the minimum-separation check.
- pyvcad.jitter_seed_sites(host: pyvcad.pyvcad.Node, regular_points: collections.abc.Sequence[pyvcad.pyvcad.Vec3], regularity: object, amplitude: SupportsFloat | SupportsIndex, seed: SupportsInt | SupportsIndex = 0, minimum_separation: SupportsFloat | SupportsIndex = 0.0, boundary_clearance: SupportsFloat | SupportsIndex = 0.0) pyvcad.pyvcad.SeedBlendResult#
Randomly displace regular sites by (1 - w) * amplitude.
Sites where the regularity w is 1 stay exactly in place; elsewhere each site moves uniformly within a ball whose radius grows as w falls (a perturbed lattice).
- Parameters:
host (Node | None) – Optional prepared host for a containment check.
regular_points (list[Vec3]) – Regular lattice sites.
regularity (float | FloatAttribute | ScalarParameter | numba.cfunc | callable) – Regularity field in [0, 1].
amplitude (float) – Maximum displacement in millimetres where w = 0.
seed (int) – Random seed.
minimum_separation (float) – Minimum distance between output seeds.
boundary_clearance (float) – Host clearance for the containment check.
Example
>>> jittered = pv.jitter_seed_sites(host, sites, weight, 2.0, seed=1)