Map lattices onto triangle meshes#
Use this guide when the surface you want to lattice is a scan, an STL region, or a mesh made by your own script rather than CAD. A triangle mesh is simply a list of points connected by triangles. TriangleMeshSurface turns one open mesh patch into a surface that OpenVCAD can follow: it creates a flat internal coordinate system for the patch, then mm.cell_map_from_surface(...) and mm.cell_map_between_surfaces(...) can use it just as they use a CADFace in the CAD guide. You do not need CadQuery for this workflow.
If your input is a complete mesh rather than an already extracted patch, see Selecting
triangle-mesh patches. OpenVCAD provides an auxiliary interactive picker as
well as advanced Python APIs for connected, angle-limited, geodesic, constrained, and
boundary-defined selection. The result converts directly to the TriangleMeshSurface used here.
surface = pv.TriangleMeshSurface(vertices, triangles)
cell_map = mm.cell_map_from_surface(surface, cells=(12, 12, 1), height=4.0)
root = mm.gyroid(cell_map, wall_thickness=0.7)
Here, vertices is a list of pv.Vec3 points and triangles is a list of triples of integer indexes that point into vertices. An imported SurfaceMesh exposes the same two arrays.
What the patch must be#
The patch must be one connected, open piece of surface with consistently ordered triangles: a single sheet cut from the surface, not a complete solid. It has one outer edge and may also have holes – vents, cut-outs, or a ring shape – which OpenVCAD treats as trims (see Patches with holes). The top of a part, a scanned region, the inside of a shell with vents, or a height-field strip usually qualifies. A closed solid, a patch with a handle (like a punctured torus), or two separate pieces does not; each produces a specific error described in Troubleshooting. You can make a closed solid usable by extracting one open region, as shown below.
The patch’s shape is unrestricted. Circular, elongated, off-center, and irregular outlines all work — the boundary does not need to be square, straight-edged, or convex.
Two practical freedoms follow:
Mesh detail and lattice cells are separate. A 14 × 14-vertex patch can drive a
(12, 10, 1)cell map, while a 100 × 100-vertex scan can drive a(6, 6, 2)map. More mesh triangles help the map follow the source surface; thecellssetting controls the lattice count.Triangle order sets the height direction. The order of the three indexes in each triangle defines which side is outward. Positive
heightgrows the map along that side. If it grows the wrong way, reverse the triangle order or use a negativeheight. OpenVCAD smooths the direction across triangle edges, so the offset does not step from facet to facet.
How the patch becomes a chart#
To place cells on an irregular surface, OpenVCAD first makes a 2D chart: a flat coordinate system for the patch. This flattening approximately preserves local angles and keeps the patch’s natural outline. A circular patch becomes a round chart and a long strip becomes a long chart. The chart sits inside the rectangle reported by surface.uv_bounds; its longer side is normalized to 1 and its aspect ratio is preserved. That helps cells remain close to square instead of stretching the patch into a forced square.
This process preserves angles better than areas. Wall thickness and beam radius stay in millimeters everywhere, but strongly curved patches such as deep pockets or nearly closed caps can still make cells vary in size. The map validates the resulting volume when you create it.
Choosing the flattening method#
The method argument of pv.TriangleMeshSurface(...) selects how the patch is flattened. All three methods produce the same kind of chart and feed the same mapping pipeline; they trade angle fidelity against area fidelity differently:
"lscm"(the default) — free-boundary least-squares conformal maps. Local angles are preserved best and the chart keeps the patch’s natural outline, but strongly curved patches can make cells vary in size."arap"— free-boundary as-rigid-as-possible flattening. It balances angle and area distortion, which often keeps cell sizes more even on deep or strongly domed patches while still keeping the natural outline."authalic"— iterative area-preserving flattening on a circular border. Cells keep near-uniform area at the cost of angle distortion, and the chart outline becomes a disk rather than the patch’s natural shape.
surface = pv.TriangleMeshSurface(vertices, triangles, method="arap")
Whichever method you request, surface.parameterization_method reports what actually produced the chart. If the requested flattening folds, the guaranteed-injective mean-value fallback is used and reported as "convex_border_mean_value".
Trimming to the true boundary#
A non-rectangular chart leaves unused space inside its bounding rectangle. The trim argument of cell_map_from_surface(...) chooses what happens at that margin. It accepts a pv.TrimMode value or the matching string:
"boundary"(the default) — clips the lattice at the patch’s actual edge. Partial edge cells are cut where the surface ends, so a circular patch has a clean round rim."cells"— keeps or removes each complete cell. The result has a stepped edge, but every surviving boundary cell stays whole."none"— keeps the full rectangular grid, including cells beyond the patch boundary.
All three options start from the same chart. In the two trimming modes, cells entirely outside the outline are removed. At cells that cross the edge, "cells" keeps the whole cell and "boundary" cuts it to the real curve; "none" keeps everything.
For cell_map_between_surfaces(...), the same trim choice applies. A point is kept only where it falls on both patches, so the lattice fills their shared footprint. To inspect the result, use cell_map.trim_mode, cell_map.has_boundary_trim, and cell_map.validate().trimmed_element_count (the number of fully removed cells).
One restriction: warp_cell_map(...) cannot warp a map made with trim="boundary", because the warp could move cells past the stored edge. Warp an untrimmed map instead, or use trim="cells" when changing cell spacing matters more than a smooth edge.
Standing the lattice off the surface#
By default the mapped volume starts on the surface and extends height along its normal. The standoff argument of cell_map_from_surface(...) (and cell_map_from_cad_face(...)) lifts the whole map off the surface first, so it spans [standoff, standoff + height] along the oriented normal. Use it when the lattice must keep a clearance from the surface it follows – a helmet liner floating a stand-off distance above the head form, for example:
cell_map = mm.cell_map_from_surface(surface, cells=(15, 15, 4), height=25.0, standoff=4.0)
standoff shares the sign convention of height: both follow the surface’s oriented normal, so a negative stand-off on a positive-height map starts the volume behind the surface.
cell_map_between_surfaces(...) accepts a standoff too. It moves only the first surface along its oriented normal before the two surfaces are interpolated, so the lattice keeps a clearance from the first surface and still ends on the second. Zero (the default) leaves the map unchanged. 29_paired_surfaces_with_standoff.py fills the space between two saddles 2 mm above the lower one:
lower = grid_surface(40.0, 40.0, 21, 21, lower_saddle)
upper = grid_surface(40.0, 40.0, 21, 21, upper_saddle)
cell_map = mm.cell_map_between_surfaces(lower, upper, cells=(6, 6, 2), standoff=2.0)
root = mm.octet(cell_map, beam_radius=0.6)
Interpolating between two surfaces depends on how well their charts correspond. When the second surface is really just “the end of the cells”, a variable-height map from the first surface is often more robust.
Sealing the cropped edge with a rim#
Trimming a lattice at the patch’s true edge leaves the boundary cells open. mm.rim(cell_map, width=...) builds a solid band that seals them: a signed distance field from the map’s edge wall – the cropped chart boundary swept through the full map height. The band follows the cropped edge exactly and extends width inward, so unioning it with any lattice built on the same map closes the open edge cells:
root = pv.Union(
mm.gyroid(cell_map, wall_thickness=0.7),
mm.rim(cell_map, width=2.0),
)
The rim is an ordinary node (pv.MappedRim), so materials and attributes attach to it like any other leaf, and width may be a pv.FloatAttribute to grade the band. For maps without a boundary trim the band follows the lateral sides of the cell grid instead; only the map’s base and offset surfaces are never treated as edges. Stand-off, rim, and flattening-method choices can be combined on the same mapped patch.
Patches with holes#
A patch may have openings: vents in the inside of a shell, cut-outs, or a ring-shaped region. OpenVCAD treats each opening as a trim, the way a trimmed CAD face is mapped through its untrimmed parent surface:
The longest boundary loop is the outer edge; every other loop is a hole.
Each hole is filled internally with a smooth, faired patch, only so the whole patch can be flattened as one disk. The fill keeps the chart smooth across the opening, so the cells around a vent are not distorted.
The filled area is then reported as off the surface. The default
trim="boundary"cuts the lattice at every hole edge exactly as it cuts the outer edge, andmm.rim(...)seals the hole walls as well as the outer edge.
surface = pv.TriangleMeshSurface(vertices, triangles) # a patch with five vents
surface.hole_count # 5
cell_map = mm.cell_map_from_surface(surface, cells=(10, 10, 1), height=5.0)
root = pv.Union(
mm.gyroid(cell_map, wall_thickness=0.6),
mm.rim(cell_map, width=1.2),
)
27_vented_dome_holes_as_trims.py builds a domed patch with five round vents. The helper indexed_holed_grid(...) in _triangle_surface_examples.py makes such patches procedurally; an imported shell surface with vents works the same way.
Things to know about holes:
trim="cells"removes whole cells that lie inside a hole and keeps cells that only overlap one.trim="none"keeps the fill, so the lattice runs across the openings.surface.vertices,triangles,uv_coordinates, andmesh()still describe your input patch.surface.filled_mesh()returns the patch plus its internal fill, andsurface.filled_triangle_countreports how many triangles were added.Small holes are resolved automatically: the map refines its trim sampling until each hole is cut, down to holes about 1/1000 of the patch’s longer side across (0.3 mm on a 300 mm patch). Smaller holes are not cut.
A hole that touches the outer edge at a single vertex pinches the patch and is rejected as a non-manifold vertex. A cut-out that opens onto the edge along a whole edge is simply part of the outer boundary and needs nothing special.
An open tube has two boundary loops of similar length. It is accepted, but one end is filled as a “hole”, which flattens like a deep cup and can make cells uneven. Cut the tube open along its length instead.
End the cells on another surface#
A constant height grows every column of cells by the same distance. When the lattice must fill the gap between a surface and something else – an inner surface and an outer shell – give height a value that varies over the patch instead. cell_map_from_surface(...) accepts:
a number: one constant height;
a
pv.FloatAttribute(or a numba callable): sampled once per column of cells, at the column’s base point on the surface;for a
TriangleMeshSurface, a list or NumPy array with one value per vertex, interpolated across the patch.
The height must stay non-zero and keep one sign over the whole map. To end the cells on a target, measure the gap along the surface normal with mm.surface_gap(surface, target, max_distance). It casts a ray from every vertex along its normal and returns the distances as an array:
inner = disk_surface(30.0, 12, 48, inner_dome)
outer = pv.Sphere(pv.Vec3(6.0, 0.0, -60.0), 69.0) # off-centre: the gap varies
gap = mm.surface_gap(inner, outer, max_distance=40.0) # one distance per vertex, in mm
cell_map = mm.cell_map_from_surface(inner, cells=(10, 10, 2), height=gap)
root = pv.Union(mm.gyroid(cell_map, wall_thickness=0.7), mm.rim(cell_map, width=1.5))
In 28_variable_height_to_outer_surface.py the gap varies from about 6 to 12 mm, and the outer cells end on the sphere everywhere:
The target can be:
a
pv.TriangleMeshSurfaceorpv.SurfaceMesh, hit by exact ray-triangle intersection. Open and non-watertight meshes work, so the inside surface of a shell exported from CAD can be used directly;any other OpenVCAD node, which is sphere-traced against its signed distance field.
Pass offset= to subtract a clearance, or combine the gap with standoff (subtract the stand-off from the gap so the cells still end on the target). Rays that miss the target raise an error by default; missing="nearest" copies the nearest hit instead, and a number fills misses with that value. Very uneven heights on a strongly curved patch can still fold the volume; construction reports that as a map validation error.
Use the map volume as a solid#
mm.domain(cell_map) returns the map’s trimmed volume as an ordinary solid node, pv.CellMapDomain. Its signed distance is negative inside the mapped volume and positive outside it, in trimmed margins, and in holes. Use it to:
clip another node to the mapped shell:
pv.Intersection(node, mm.domain(cell_map));keep other geometry out of it:
pv.Difference(node, mm.domain(cell_map));host a stochastic lattice that follows the curved shell.
30_liner_volume_voronoi_host.py fills a vented dome shell with a random Voronoi strut lattice:
cell_map = mm.cell_map_from_surface(surface, cells=(10, 10, 1), height=8.0)
host = mm.domain(cell_map)
host.prepare(pv.Vec3(0.5, 0.5, 0.5), 1.0)
seeds = mm.sample_points_in_host(host, spacing=5.0, seed=7, boundary_clearance=0.5)
root = pv.Union(
mm.voronoi_graph_lattice(host, seeds, beam_thickness=0.9),
mm.rim(cell_map, width=1.2),
)
The stochastic-lattices guide covers seeds, spacing, and boundary options in detail.
Wrap flat geometry onto the map#
mm.map_node(cell_map, node) evaluates any node in the map’s own coordinates, so geometry designed flat follows the curved map: pads, bosses, labels, or cut-outs on a liner. With the default space="physical", map coordinates are scaled to approximate millimetres. pv.MappedNode(...).child_bounds gives the flat box that covers the whole map; X runs along U, Y along V, and Z through the map’s thickness:
cell_map = pv.CellMap.cylindrical(pv.Vec3(0, 0, 0), 30.0, 36.0, 40.0, (24, 6, 1))
lower, upper = pv.MappedNode(cell_map, pv.Sphere(pv.Vec3(0, 0, 0), 1.0)).child_bounds
length, height, thickness = upper.x, upper.y, upper.z # about 207 x 40 x 6 mm
pad = pv.RectPrism(pv.Vec3(0.25 * length, 0.5 * height, 0.5 * thickness),
pv.Vec3(24.0, 14.0, thickness + 2.0))
boss = pv.Cylinder(pv.Vec3(0.5 * length, 0.5 * height, 0.5 * thickness), 7.0, thickness + 2.0)
root = pv.Union(mm.gyroid(cell_map, wall_thickness=0.7),
mm.map_node(cell_map, pv.Union(pad, boss)))
31_wrap_pads_through_a_cell_map.py places two pads and a round boss on a cylindrical gyroid shell:
Keep in mind:
The wrapped node exists only inside the map volume; anything outside it is clipped away, just like a mapped lattice.
space="logical"uses cell units instead of millimetres, andscale=(sx, sy, sz)sets explicit child units per cell.The returned distance is a first-order estimate that uses the map’s local stretch. It is accurate near the surface, which is what meshing needs, but not a true distance far from it, so do not use a wrapped node where exact distances matter (for example as a distance-graded body).
Periodic directions wrap, so a node crossing a cylinder’s seam is cut there; place features away from the seam or shift it with the map’s start angle.
Choosing the chart orientation#
The chart’s U axis becomes the lattice’s first logical direction. It controls the direction of beams, plates, and grading fields on the surface. You can either accept the default or choose it explicitly:
Default: U follows the patch’s long direction. An elongated strip therefore gets U along its length. Near-round patches receive a repeatable automatic direction.
Explicit: pass
u_axis_hint=pv.Vec3(...). The world-space direction is projected onto the patch and U is rotated to follow it.
surface = pv.TriangleMeshSurface(vertices, triangles, u_axis_hint=pv.Vec3(1.0, 0.0, 0.0))
Use the hint whenever the lattice direction matters. Always use it when pairing a mesh with a CAD face, as shown below.
Map a procedural patch#
The procedural examples use helpers in _triangle_surface_examples.py: disk_surface(...) makes a round patch, while grid_surface(...) and indexed_grid(...) make rectangular patches. This first example creates a round dome mesh and covers it with a gyroid lattice:
import math
import pyvcad as pv
import pyvcad_metamaterials as mm
import pyvcad_rendering as viz
from _triangle_surface_examples import disk_surface
RADIUS = 15.0
def spherical_cap(x, y):
r2 = (x * x + y * y) / (RADIUS * RADIUS)
return 8.0 * math.sqrt(max(0.0, 1.0 - 0.75 * r2))
surface = disk_surface(RADIUS, 10, 36, spherical_cap)
cell_map = mm.cell_map_from_surface(surface, cells=(12, 12, 1), height=4.0)
root = mm.gyroid(cell_map, wall_thickness=0.7)
viz.Render(root)
Each comparison keeps the camera fixed: drag the divider to see the input patch replaced by its lattice. 18_triangle_mesh_dome_gyroid.py turns a shallow, round dome into a gyroid shell. Its TRIM_MODE variable lets you try the three trimming modes with a one-line edit.
Input patch
Trimmed gyroid
19_triangle_mesh_saddle_octet.py turns a saddle-shaped patch, which rises in one direction and falls in the other, into an FCC beam lattice:
Input patch
FCC beam lattice
20_triangle_mesh_organic_plate.py turns a long, wavy 3:1 strip into a plate lattice. Its chart keeps the 3:1 aspect ratio, and u_axis_hint keeps U along the long world-space direction:
Input patch
Plate lattice
Select a region of an imported mesh#
An imported mesh is often a closed solid with several surface regions, not the one open patch this workflow needs. 21_imported_triangle_mesh_patch.py starts with a domed tile: a domed top, four sides, and a flat bottom. It uses a geometric seed and local face-angle growth to keep only the top:
nearest_triangle(...)finds a seed from a point above the model.select_linked_by_face_angle(...)follows the smooth dome and stops at the side-wall crease.to_triangle_mesh_surface(...)extracts, reindexes, and validates the open disk.
The extracted top is an open disk, so it can go straight into TriangleMeshSurface. The example then makes the gyroid walls thicker from one side of the top to the other with cell_map.logical_position.x. Because the chart keeps the selected outline, the lattice follows the true boundary; the selection does not need to be square or convex.
Choose the selection rule that matches the region boundary. The advanced mesh-selection guide covers interactive selection, ring refinement, data delimiters, surface-distance patches, and path-defined outlines. The result must still be one connected patch (holes are fine) before it can drive conformal mapping.
Pair a mesh with a CAD surface#
CADFace and TriangleMeshSurface can both act as a surface boundary, so cell_map_between_surfaces(...) can fill the space between either combination. 22_between_mesh_and_cad_surfaces.py builds an octet lattice between a wavy triangle-mesh floor and a smooth CAD dome above it. The map’s W direction runs from the mesh at w = 0 to the CAD surface at w = 1.
When one boundary is a mesh and the other is CAD, align their U axes in world space. Automatic alignment can flip directions or swap U and V, but it cannot correct every rotation. In this example the mesh would otherwise be 45° out of step with the dome, which would twist the lattice. u_axis_hint pins the mesh U direction to the CAD face’s U direction:
floor_surface = pv.TriangleMeshSurface( # lower: triangle mesh
floor_vertices, floor_triangles, u_axis_hint=pv.Vec3(1.0, 0.0, 0.0)
)
engineered_surface = pv.CADModel.from_cadquery(engineered_cad).faces[0] # upper: CAD patch
cell_map = mm.cell_map_between_surfaces(floor_surface, engineered_surface, cells=(12, 12, 3))
root = mm.octet(cell_map, beam_radius=0.65)
The two boundaries need compatible surface coordinates for the interpolation to remain valid. Patches over the same footprint align cleanly. A periodic CAD cylinder and a non-periodic mesh patch, for example, are not compatible and are rejected.
Once built, these lattices are ordinary OpenVCAD nodes. You can grade them as in the previous guide, combine them in heterogeneous lattices, or send them to a compatible compiler.
Build a lattice from the mesh cells themselves#
Every lattice so far repeats one unit cell through a cell map. Some parts are easier to mesh than to map. In that case, the cells of the mesh can be the lattice cells instead, and you do not need a cell map at all.
A volume mesh splits the inside of a part into small solid cells: tetrahedra (four triangular faces) or hexahedra (six faces, like voxels). A surface mesh covers only the outside, with triangles. mm.mesh_lattice(...) places struts in the cells of either kind of mesh, so the lattice fills whatever shape the mesher can fill. It returns a pv.BeamLattice, a node made of round struts joined at their ends.
A rule chooses where the struts go in each mesh cell. These are the same rules the tessellation builders use in Custom unit cells:
Rule |
Struts on mesh cells |
|---|---|
|
every mesh edge |
|
each cell’s centre joined to its corners (BCC in hexahedra) |
|
each face’s centre joined to its corners |
|
the centres of cells that share a face; on a triangle surface, a strut across every interior edge |
|
each cell’s centre joined to the centres of its faces |
The example meshes one part, body (two overlapping spheres), in three ways and builds a lattice from each:
the edges of a tetrahedral mesh, with struts that get thicker towards the bottom,
the
"dual"of the surface triangles, which gives a cell-like net on the skin, andeach voxel of a hexahedral mesh joined from its centre to its corners (BCC in voxels).
settings = pv.TetrahedralMeshFixedSettings()
settings.cell_size = 5.0
settings.facet_size = 5.0
settings.facet_distance = 0.5
tets = pv.TetrahedralMesh.from_tree(body, settings)
tet_struts = mm.mesh_lattice(tets, "edges", beam_radius=lambda x, y, z, d: 0.7 - 0.012 * z)
surface = pv.SurfaceMesh(body, 0.5).remeshed(4.0) # even 4 mm triangles
skin_net = mm.mesh_lattice(surface, "dual", beam_radius=0.5)
hex_settings = pv.HexahedralMeshSettings()
hex_settings.voxel_size = pv.Vec3(5.0, 5.0, 5.0)
voxel_bcc = mm.mesh_lattice(pv.HexahedralMesh.from_tree(body, hex_settings),
"cell_vertex_centroid", beam_radius=0.5)
You can give beam_radius in three ways: one number, a list with one value per mesh vertex, or a field such as the lambda above, which is sampled at both ends of every strut. With per-vertex values, a strut end at a cell or face centre takes the average of that cell’s or face’s vertex values. The optional node_radius adds a ball at every joint and accepts the same three forms.
To combine rules, pass a list of them. You get the struts of every rule in the list, and a strut that two neighbouring cells share appears only once.
The struts are centred on the mesh, so the ones that run along the part’s surface stick halfway out of it. To trim them, intersect the lattice with the part, as the example does.
The mesh also sets the cell size. Smaller mesh cells give shorter struts, so a mesh with smaller tetrahedra near curved surfaces gives a finer lattice there.
For foams grown from seed points, and Voronoi ribs on a surface, see Stochastic lattices.
Run 33_lattices_from_meshes.py to see all three lattices in the interactive preview.
Limitations and troubleshooting#
Rejected input topology#
OpenVCAD reports each invalid input with a specific RuntimeError rather than guessing how to repair it:
Input |
Error |
|---|---|
Closed solid (a sphere) |
“the mesh is closed and has no boundary loop” |
Punctured torus (a handle) |
“requires a genus-0 patch … carries at least one handle” |
A hole touching the outer edge at one vertex |
“has a non-manifold vertex” |
Two disconnected disks |
“requires a single connected patch” |
Three triangles on one edge |
“has a non-manifold edge” |
Two fans joined at a point |
“has a non-manifold vertex” |
Repair or extract the patch before construction. For closed solids and multi-region meshes, use the region-selection workflow.
When the flattening cannot keep the natural outline#
Some patches cannot be laid flat without overlapping themselves; a helical strip that wraps more than once is a typical case. Instead of rejecting it immediately, TriangleMeshSurface switches to a fallback mapping that puts the boundary on a circle. The fallback is valid but distorts the shape more, so cells may be less uniform. Its chart outline is also no longer the original patch outline, which means trimming follows the circular chart rather than the mesh edge. Check which mapping was used with:
surface.parameterization_method # "free_boundary_lscm" or "convex_border_mean_value"
If a patch you expected to flatten cleanly uses the fallback, it is usually more curved or twisted than intended. Splitting it into flatter regions often restores the natural-outline chart. Only when both mappings fail is the patch rejected; the error includes both reasons.
Map validation errors#
Making a valid chart does not guarantee that the offset or interpolated volume is valid. Construction always checks the volume for folds or collapsed cells:
“Surface CellMap is folded or singular” —
heightis too large for a concave surface and the offset intersects itself, or a distorted fallback chart collapses cells at the requested resolution. Reduceheight, add cells, or split the patch.“height field must be finite and non-zero” or “must keep one sign” — a variable
heightreached zero or changed sign somewhere on the map (including the trimmed margin, where the field is sampled at extrapolated points). Keep the field strictly positive or strictly negative.“No valid paired-surface correspondence was found” — the two surfaces in
between_surfacescannot be aligned, or their charts slide against each other. The message lists the checks it tried. Use surfaces over a common footprint and make sure both normals point along the intended W direction.
Other limits to keep in mind#
A twisted shell between a mesh and a CAD face usually means the U axes differ by an angle automatic alignment cannot fix. Pin the mesh chart with
u_axis_hint(see the pairing section).Sharp creases become rounded because vertex normals are smoothed. Split the patch at a hard edge when preserving that edge matters.
Deep pockets and nearly closed caps can leave cells uneven even when the map validates. Inspect
cell_map.validate()aspect-ratio diagnostics if uniformity matters.













