Geometry — 3D#
Typedefs
-
typedef CGAL::Exact_predicates_exact_constructions_kernel EX_K#
-
typedef CGAL::Simple_cartesian<double> SC_Kernel#
-
typedef openvdb::FloatGrid SDF_Grid#
-
struct Indexed_Triangle#
- #include <primitives.h>
Triangle representation capturing integer-based references mapping shared indices into a global vertex pool.
-
class SurfaceMesh : public std::enable_shared_from_this<SurfaceMesh>#
- #include <surface_mesh.h>
A triangle mesh stored in OpenVCAD’s canonical vertex/index representation.
SurfaceMesh stores vertices, indexed triangles, and a bounding box. It can be constructed from explicit mesh data, files, VTK data, implicit trees, and SDF data. Derived data is built lazily and cached on the mesh: the geometry fingerprint, the selection topology, and an AABB tree used by ray, closest-point, and visibility queries. Signed-distance sampling accelerators remain in the compiler and sampler layers. CGAL closed-mesh validation is disabled by default; pass disable_validation=false to opt in.
Public Functions
-
double area() const#
Returns the total triangle area in square millimetres.
- Returns:
The area in mm^2.
-
size_t boundary_loop_count() const#
Counts the closed loops formed by open (single-triangle) edges.
0 for a watertight mesh, 1 for a disk patch, 2 for an open cylinder.
- Returns:
The number of boundary loops.
-
std::vector<std::shared_ptr<PolylineCurve>> boundary_loops() const#
Returns the open-edge loops (holes and patch borders) as closed curves.
Each loop follows the triangles’ winding; chains that do not close (at non-manifold edges) are left out.
- Returns:
One closed PolylineCurve per loop.
-
std::pair<glm::vec3, glm::vec3> bounding_box() const#
Returns the bounding box of the mesh.
- Returns:
The minimum and maximum mesh coordinates.
-
void center()#
Centers the mesh around the origin.
Clips the mesh by the zero level of a node’s signed distance field.
Triangles that cross the zero level are split at the crossing, which is located on the node itself, so plane, primitive, and expression cuts leave a clean open boundary. The node is prepared by this call.
- Parameters:
node – Any OpenVCAD node; inside is where its signed distance is negative.
keep – “inside” keeps the part where the node is negative, “outside” the rest.
voxel_size – Voxel size in millimetres used to prepare the node. Empty uses the mean mesh edge length.
- Returns:
The clipped open mesh.
-
SDF_Grid::Ptr compute_sdf(glm::vec3 voxel_size, float exterior_band_width = 3.0f, float interior_band_width = 3.0f) const#
Converts the mesh into an OpenVDB signed-distance field.
The grid is isotropic: only the smallest component of
voxel_sizeis used as the spacing. The band widths are converted to voxels with that same spacing.- Parameters:
voxel_size – The voxel size in millimetres; only min(x, y, z) is used.
exterior_band_width – Exterior narrow-band width in millimetres.
interior_band_width – Interior narrow-band width in millimetres.
- Throws:
std::runtime_error – If the mesh is empty.
- Returns:
The generated OpenVDB float grid.
-
std::vector<std::shared_ptr<SurfaceMesh>> connected_components() const#
Splits the mesh into vertex-connected pieces, largest (most triangles) first.
- Returns:
One mesh per connected piece.
-
std::shared_ptr<SurfaceMesh> decimated(const std::optional<size_t> &target_count = std::nullopt, const std::optional<double> &target_ratio = std::nullopt, const std::optional<double> &max_error = std::nullopt) const#
Simplifies the mesh by edge collapse with Garland-Heckbert quadric error.
Give a target face count or ratio, an error bound, or a target plus a bound. Borders and label boundaries are preserved as well as the quadrics allow; label boundaries are never collapsed.
- Parameters:
target_count – Stop once the mesh has at most this many triangles.
target_ratio – Stop once the mesh has at most this fraction of its triangles (0, 1].
max_error – Stop once the cheapest collapse would move the surface farther than about this distance in millimetres from the original face planes.
- Returns:
The simplified mesh.
-
std::shared_ptr<SurfaceMesh> filled_holes(const std::optional<double> &max_hole_size = std::nullopt, bool fair = true) const#
Fills open boundary loops (holes) with new triangles.
Each hole is triangulated, refined to match the surrounding density, and optionally faired to blend smoothly with its neighbourhood.
- Parameters:
max_hole_size – Only fill holes whose boundary bounding-box diagonal is at most this many millimetres. Empty fills every hole.
fair – If true, fair the patch to blend with the surrounding surface.
- Returns:
The repaired mesh.
-
std::string fingerprint() const#
Returns a deterministic fingerprint of ordered vertices and triangles.
Triangle IDs are only reusable while this fingerprint remains unchanged.
- Returns:
The fingerprint string.
-
bool is_closed() const#
Reports whether every edge is shared by exactly two triangles (watertight).
- Returns:
True for a closed mesh.
-
bool is_manifold() const#
Reports whether every edge has at most two triangles and every vertex has a single fan of triangles around it.
- Returns:
True for a manifold mesh.
Merges another mesh into this mesh.
This performs a simple concatenation of vertices and triangles. It may result in non-manifold geometry or duplicate vertices.
- Parameters:
mesh_to_merge – The mesh to merge into this mesh.
-
MeshHit nearest_triangle(const glm::vec3 &point) const#
Finds the closest triangle to a world-space point.
- Parameters:
point – Query point in millimetres.
- Returns:
Closest triangle ID, closest surface point, and Euclidean distance.
-
size_t nearest_vertex(const glm::vec3 &point) const#
Finds the source vertex nearest to a world-space point.
- Parameters:
point – Query point in millimetres.
- Returns:
Zero-based source vertex ID.
-
std::optional<MeshHit> ray_intersection(const glm::vec3 &origin, const glm::vec3 &direction) const#
Finds the first triangle intersected by a world-space ray.
- Parameters:
origin – Ray origin in millimetres.
direction – Non-zero ray direction; it is normalized internally.
- Returns:
Nearest forward hit, or no value when the ray misses.
-
std::shared_ptr<SurfaceMesh> remeshed(double target_edge_length, size_t iterations = 3, const std::optional<double> &feature_angle_degrees = std::nullopt) const#
Isotropically remeshes the surface toward a uniform edge length.
Vertices are projected back onto the input surface. Open borders keep their position and label boundaries stay on their original polylines.
- Parameters:
target_edge_length – Target edge length in millimetres.
iterations – Number of split, collapse, flip, and smooth passes.
feature_angle_degrees – Optional dihedral angle above which edges are kept as sharp feature lines.
- Returns:
The remeshed mesh.
-
std::shared_ptr<SurfaceMesh> remove_small_components(const std::optional<double> &min_volume = std::nullopt, const std::optional<size_t> &min_triangles = std::nullopt, bool keep_largest = false) const#
Removes small disconnected pieces such as floating islands.
Pieces are grouped into bodies first: an inward-facing cavity surface belongs to the smallest outward surface that encloses it, so a hollow part keeps its inner wall and is judged by its material volume.
- Parameters:
min_volume – Remove bodies whose enclosed volume is below this value (mm^3).
min_triangles – Remove bodies with fewer triangles than this.
keep_largest – If true, keep only the body with the largest volume.
- Returns:
The cleaned mesh.
-
std::shared_ptr<MeshSelection> select_by_geodesic_radius(size_t seed_vertex, double radius)#
Selects triangles intersecting an edge-geodesic radius around a seed vertex.
- Parameters:
seed_vertex – Source vertex at the center of the selection.
radius – Maximum shortest edge-path distance in millimetres.
- Returns:
The selection.
-
std::shared_ptr<MeshSelection> select_enclosed_region(const std::vector<std::array<size_t, 2>> &boundary_edges, size_t seed_triangle)#
Selects the side of a closed source-edge loop containing a seed triangle.
- Parameters:
boundary_edges – One connected closed loop of source vertex-index pairs.
seed_triangle – Triangle on the desired side of the loop.
- Returns:
The selection.
-
std::shared_ptr<MeshSelection> select_linked(size_t seed_triangle, bool cross_non_manifold = false)#
Flood-fills the edge-connected component containing a seed triangle.
- Parameters:
seed_triangle – Seed triangle ID.
cross_non_manifold – If true, growth may cross edges shared by more than two faces.
- Returns:
The selection.
-
std::shared_ptr<MeshSelection> select_linked_by_face_angle(size_t seed_triangle, double max_angle_degrees, bool cross_non_manifold = false)#
Flood-fills across shared edges whose local face angle is within a threshold.
The threshold is evaluated between each adjacent face pair, matching a feature-edge flood fill and allowing gradual curvature to grow.
- Parameters:
seed_triangle – Seed triangle ID.
max_angle_degrees – Inclusive local face-angle threshold in degrees.
cross_non_manifold – If true, growth may cross non-manifold shared edges.
- Returns:
The selection.
-
std::shared_ptr<MeshSelection> select_linked_constrained(size_t seed_triangle, const std::optional<double> &max_angle_degrees = std::nullopt, const std::vector<std::array<size_t, 2>> &blocked_edges = {}, const std::vector<int64_t> &triangle_regions = {})#
Flood-fills with explicit feature, edge, and per-triangle region delimiters.
- Parameters:
seed_triangle – Seed triangle ID.
max_angle_degrees – Optional inclusive local face-angle limit.
blocked_edges – Source vertex-index pairs that growth may not cross.
triangle_regions – Optional per-triangle region labels; unequal labels delimit growth.
- Returns:
The selection.
-
std::shared_ptr<MeshSelection> select_triangles(const std::vector<size_t> &triangle_ids)#
Creates an explicit triangle selection.
- Parameters:
triangle_ids – Triangle IDs to select; duplicates are removed.
- Throws:
std::out_of_range – If a triangle ID is outside the mesh.
- Returns:
The selection, tied to this mesh’s current geometry.
Selects triangles visible from seed points spread through a node’s interior.
- Parameters:
region – Node whose inside (negative distance) holds the seeds.
seed_count – Number of seeds, chosen by farthest-point sampling.
facing – “any”, “toward”, or “away”.
max_view_angle_degrees – Optional view-angle limit in degrees.
- Returns:
The selection of visible triangles.
-
std::shared_ptr<MeshSelection> select_visible_from(const std::vector<glm::vec3> &seed_points, const std::string &facing = "any", const std::optional<double> &max_view_angle_degrees = std::nullopt)#
Selects triangles that can be seen from any of the seed points.
A triangle is visible when a straight line from a seed reaches one of its interior sample points before hitting any other triangle. The result crosses sharp creases freely, which makes it suited to picking the inner surface of a shell as seen from points inside it.
- Parameters:
seed_points – Viewpoints in millimetres.
facing – “any”, “toward” (the triangle normal points at the seed), or “away”.
max_view_angle_degrees – Optional largest angle between the triangle normal (or its reverse for “any”) and the direction to the seed.
- Returns:
The selection of visible triangles.
-
void set_triangle_labels(std::vector<int64_t> labels)#
Sets per-triangle labels.
- Parameters:
labels – One label per triangle, or an empty vector to clear the labels.
-
MeshPath shortest_surface_path(size_t start_vertex, size_t end_vertex, const std::vector<std::array<size_t, 2>> &blocked_edges = {}) const#
Finds the shortest path between two vertices along mesh edges.
- Parameters:
start_vertex – First source vertex ID.
end_vertex – Last source vertex ID.
blocked_edges – Optional source edges that the path may not traverse.
- Returns:
Ordered vertices, points, edges, and total path length.
-
SurfaceMesh()#
Default constructor creating an empty mesh.
-
SurfaceMesh(const openvdb::FloatGrid::Ptr &sdf_grid, bool disable_validation = true)#
Constructor that extracts a zero-isosurface from an OpenVDB float grid.
- Parameters:
sdf_grid – The signed-distance OpenVDB grid.
disable_validation – If true (default), bypass CGAL validation on input.
Constructor that extracts a zero-isosurface from a float VDB volume.
- Parameters:
sdf_volume – The signed-distance volume wrapper.
disable_validation – If true (default), bypass CGAL validation on input.
Constructor that meshes a float VDB volume with explicit options.
- Parameters:
sdf_volume – The signed-distance volume wrapper.
options – Meshing options such as adaptivity.
disable_validation – If true (default), bypass CGAL validation on output.
Constructor that samples an OpenVCAD tree, optionally skipping preparation.
- Parameters:
root – The tree root to sample.
voxel_size – Uniform voxel size in millimetres used for the temporary SDF.
disable_validation – If true, bypass CGAL validation on output.
root_already_prepared – If true, the tree is not prepared again.
thread_usage_tracker – Optional tracker that records sampling threads.
Constructor that samples an OpenVCAD tree and extracts its zero-isosurface.
- Parameters:
root – The tree root to sample.
voxel_size – Uniform voxel size used for the temporary SDF.
disable_validation – If true (default), bypass CGAL validation on input.
Constructor that samples an OpenVCAD tree and meshes it with explicit options.
- Parameters:
root – The tree root to sample.
voxel_size – Uniform voxel size in millimetres used for the temporary SDF.
options – Meshing options such as adaptivity.
disable_validation – If true (default), bypass CGAL validation on output.
root_already_prepared – If true, the tree is not prepared again.
thread_usage_tracker – Optional tracker that records sampling threads.
-
SurfaceMesh(const std::string &file_path, bool disable_validation = true)#
Constructor that loads a mesh from a file.
- Parameters:
file_path – The path to the mesh file to load.
disable_validation – If true (default), bypass CGAL validation on input.
-
SurfaceMesh(std::vector<glm::vec3> vertices, std::vector<Indexed_Triangle> triangles, bool disable_validation = true)#
Constructor that creates a mesh from vertices and triangles.
- Parameters:
vertices – The vertices of the mesh.
triangles – The indexed triangular faces of the mesh.
disable_validation – If true (default), bypass CGAL validation on input.
-
SurfaceMesh(vtkSmartPointer<vtkImageData> sdf_image, bool disable_validation = true)#
Constructor that extracts a zero-isosurface from signed-distance image data.
- Parameters:
sdf_image – The vtkImageData containing signed-distance samples.
disable_validation – If true (default), bypass CGAL validation on input.
-
SurfaceMesh(vtkSmartPointer<vtkPolyData> poly_data, bool disable_validation = true)#
Constructor that creates a mesh from VTK polydata.
- Parameters:
poly_data – The vtkPolyData geometry element.
disable_validation – If true (default), bypass CGAL validation on input.
-
void translate(glm::vec3 translation)#
Translates the mesh by a given translation vector.
- Parameters:
translation – The translation vector to apply to the mesh (mm).
-
inline size_t triangle_count() const#
Returns the number of triangles without copying mesh data.
- Returns:
The triangle count.
-
const std::vector<int64_t> &triangle_labels() const#
Returns optional per-triangle integer labels (for example CAD face IDs).
Empty when the mesh carries no labels. Labels do not change the geometry fingerprint. Clipping, component extraction, decimation, remeshing, hole filling (new faces get -1), merging, and selection extraction carry labels along.
- Returns:
One label per triangle, or an empty vector.
-
std::vector<Indexed_Triangle> triangles() const#
Returns the triangles of the mesh.
- Returns:
The triangles of the mesh.
-
inline size_t vertex_count() const#
Returns the number of vertices without copying mesh data.
- Returns:
The vertex count.
-
std::vector<glm::vec3> vertices() const#
Returns the vertices of the mesh.
- Returns:
The vertices of the mesh.
-
double volume() const#
Returns the signed enclosed volume in cubic millimetres.
Positive for closed meshes wound outward. Only meaningful for closed meshes.
- Returns:
The signed volume in mm^3.
-
void write_3mf(const std::string &output_file_name)#
Writes the mesh to a 3MF file.
- Parameters:
output_file_name – The file to write.
-
void write_stl(const std::string &output_file_name)#
Writes the mesh to a binary STL file.
- Parameters:
output_file_name – The file to write.
Public Static Functions
-
static double sdf_lipschitz_bound(const SDF_Grid &grid, const glm::vec3 &box_min, const glm::vec3 &box_max, double bandwidth, double offset = 0.0)#
Measures a Lipschitz bound of a band-clipped, box-capped signed-distance grid.
The field is the one the grid-backed leaves (Mesh, TexturedMesh, CAD in fast mode) return: F(p) = trilinear(p) - offset, the grid read with OpenVDB’s BoxSampler, capped as max(F(p), signed_distance_to_box(p)) inside the box padded by the bandwidth T, and no value (counted as T) beyond it. Inside one grid cell, each partial derivative of the trilinear interpolant is a convex combination of that axis’s four edge differences over the spacing, so |grad F| <= sqrt(rx^2 + ry^2 + rz^2) with r the largest edge difference per axis (at most sqrt(3) times the largest difference between neighbouring values). The bound is the largest of these over every cell a point of the padded box can read, with one cell of slack, using the values the sampler reads: active and inactive voxels, tiles and the background. Cells whose eight values are all at least T (G is T there) or all at most -T (G is the clipped box distance there) are skipped. The box distance and the clamp to [-T, T] are 1-Lipschitz, and at the face of the padded box the box distance is at least T, so the clipped value is continuous into “no value”. Regions of 8^3 voxels with no leaf node hold one tile or background value each, so they are checked as one cell. The result covers the trilinear field exactly; the sampler’s float arithmetic adds a few float ulps of the values and coordinates on top.
- Parameters:
grid – A grid with an axis-aligned scale transform, as compute_sdf() builds.
box_min – The minimum of the node’s bounding box.
box_max – The maximum of the node’s bounding box.
bandwidth – The bandwidth T the node was prepared with.
offset – The amount subtracted from every grid value (a Mesh’s sdf_shim).
- Returns:
The bound (at least 1), or infinity if the grid’s transform is not an axis-aligned scale or a value is not finite.
Returns evenly spread points inside a node (negative signed distance).
Samples a grid over the node bounding box, keeps the inside points, and picks a deterministic farthest-point subset. The node is prepared by this call.
- Parameters:
region – Node to sample.
seed_count – Number of points to return (fewer if the node is very small).
- Returns:
The seed points in world coordinates.
-
static double signed_distance_to_box(double x, double y, double z, const glm::vec3 &box_min, const glm::vec3 &box_max)#
Returns the signed Euclidean distance from a point to an axis-aligned box.
Positive outside (the distance to the nearest box point), negative inside (minus the distance to the nearest face). It is 1-Lipschitz and at least the per-axis distance to the box outside it.
- Parameters:
x – The x coordinate.
y – The y coordinate.
z – The z coordinate.
box_min – The box minimum.
box_max – The box maximum.
- Returns:
The signed distance.
Private Functions
-
void initialize_from_file(const std::string &file_path, bool disable_validation)#
-
void initialize_from_float_grid(const openvdb::FloatGrid::Ptr &sdf_grid, bool disable_validation, const VolumeMeshingOptions &options = VolumeMeshingOptions())#
-
void initialize_from_image_data(vtkSmartPointer<vtkImageData> sdf_image, bool disable_validation, bool allow_empty = false)#
-
void initialize_from_mesh_data(std::vector<glm::vec3> vertices, std::vector<Indexed_Triangle> triangles, bool disable_validation, bool allow_empty = false)#
-
void initialize_from_poly_data(vtkSmartPointer<vtkPolyData> poly_data, bool disable_validation, bool allow_empty = false)#
-
std::vector<size_t> nearest_candidates(const glm::dvec3 &point) const#
Returns the IDs (ascending) of triangles that may be nearest to a point.
-
std::vector<size_t> ray_candidates(const glm::dvec3 &origin, const glm::dvec3 &direction) const#
Returns the IDs (ascending) of triangles the tree reports as hit by a ray.
-
std::shared_ptr<SurfaceMeshRayTree> ray_tree() const#
Returns the lazily built AABB tree used by ray and closest-point queries.
-
std::shared_ptr<MeshSelectionCache> selection_cache() const#
-
std::shared_ptr<SurfaceMesh> selection_source()#
Private Members
-
mutable std::optional<std::string> m_fingerprint#
-
glm::vec3 m_max = glm::vec3(0.0f)#
-
glm::vec3 m_min = glm::vec3(0.0f)#
-
mutable std::shared_ptr<SurfaceMeshRayTree> m_ray_tree#
-
mutable std::shared_ptr<MeshSelectionCache> m_selection_cache#
-
std::vector<int64_t> m_triangle_labels#
-
std::vector<Indexed_Triangle> m_triangles#
-
std::vector<glm::vec3> m_vertices#
Private Static Functions
-
static std::pair<glm::vec3, glm::vec3> compute_bounding_box(const std::vector<glm::vec3> &vertices)#
-
static vtkSmartPointer<vtkPolyData> contour_sdf_image(vtkSmartPointer<vtkImageData> sdf_image)#
-
static vtkSmartPointer<vtkImageData> create_sdf_image_from_grid(const openvdb::FloatGrid::Ptr &sdf_grid)#
-
static void fill_from_volume_to_mesh(const openvdb::FloatGrid::Ptr &sdf_grid, std::vector<glm::vec3> &vertices, std::vector<Indexed_Triangle> &triangles, const VolumeMeshingOptions &options = VolumeMeshingOptions())#
-
static std::tuple<std::vector<glm::vec3>, std::vector<Indexed_Triangle>, glm::vec3, glm::vec3> load_mesh_from_file(const std::string &file_path)#
-
static vtkSmartPointer<vtkPolyData> normalize_poly_data(vtkSmartPointer<vtkPolyData> poly_data)#
-
static std::shared_ptr<CGAL::Surface_mesh<SC_Point>> to_cgal_mesh(const std::vector<glm::vec3> &vertices, const std::vector<Indexed_Triangle> &triangles)#
-
static void validate_mesh(const std::vector<glm::vec3> &vertices, const std::vector<Indexed_Triangle> &triangles)#
Friends
- friend class MeshSampler
- friend class MeshSelection
- friend class TriangleMeshSurface
-
double area() const#
-
struct VolumeMeshingOptions#
- #include <surface_mesh.h>
Controls how a signed-distance volume is turned into triangles.
The defaults reproduce OpenVCAD’s uniform meshing, where every voxel the surface passes through contributes polygons.
Public Members
-
double adaptivity = 0.0#
OpenVDB surface adaptivity from 0 (uniform) to 1 (most simplified).
Voxels inside one 8^3 block merge into one polygon vertex when their 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 regions merge at any value, sharp detail keeps voxel resolution, and the surface stays closed.
-
bool relax_disoriented_triangles = true#
Relaxes triangles whose orientation disagrees with the field gradient.
Only used when adaptivity is greater than zero.
-
double adaptivity = 0.0#
-
struct MeshHit#
- #include <mesh_selection.h>
A geometric query hit on one triangle of a SurfaceMesh.
The triangle ID is stable only while the source mesh fingerprint remains unchanged.
-
struct MeshPath#
- #include <mesh_selection.h>
A shortest path along the source mesh edge graph.
Points are copied from the source mesh, so the path remains inspectable even if the source later changes. Vertex IDs are only reusable while the source fingerprint matches.
Public Functions
-
std::shared_ptr<PolylineCurve> to_curve() const#
Returns the path as a curve: an open PolylineCurve through its points.
- Throws:
std::runtime_error – if the path has fewer than 2 points.
- Returns:
The curve.
Public Members
-
std::vector<std::array<size_t, 2>> edges#
Consecutive source vertex-index pairs along the path.
-
double length = 0.0#
Total path length in mm.
-
std::vector<glm::vec3> points#
World positions of vertex_ids, copied from the source.
-
std::vector<size_t> vertex_ids#
Source vertex indices along the path, in order.
-
std::shared_ptr<PolylineCurve> to_curve() const#
-
class MeshSelection#
- #include <mesh_selection.h>
An immutable set of triangle IDs tied to one SurfaceMesh state.
MeshSelection keeps the source mesh alive and records its geometry fingerprint when the selection is created. Operations fail if the source is later mutated, preventing stale triangle IDs from being applied to different geometry. Selection operations are intentionally permissive about patch topology; conversion to TriangleMeshSurface is the boundary that validates the connected, manifold, genus-0 open patch (holes allowed) that flattening requires.
Public Functions
-
double area() const#
Returns the total selected triangle area in square millimetres.
- Returns:
The area in mm^2.
-
std::vector<std::array<size_t, 2>> boundary_edges() const#
Returns source vertex-index pairs along the selected patch boundary.
An edge is returned whenever the selection has other than two incident faces, so open and non-manifold selection boundaries remain visible to callers.
- Returns:
The boundary edges as source vertex-index pairs.
-
std::vector<std::shared_ptr<PolylineCurve>> boundary_loops() const#
Returns the boundary of the selection as closed curves, one per loop.
Loops follow the selected triangles’ winding; chains that do not close (at non-manifold edges) are left out.
- Returns:
One closed PolylineCurve per boundary loop.
-
bool contains(size_t triangle_id) const#
Reports whether a triangle ID belongs to this selection.
- Parameters:
triangle_id – The source triangle ID.
- Returns:
True if the triangle is selected.
-
std::shared_ptr<MeshSelection> grown(size_t rings = 1, bool cross_non_manifold = false) const#
Adds edge-adjacent triangle rings around the selection.
- Parameters:
rings – Number of neighboring rings to add.
cross_non_manifold – If true, growth may cross edges used by more than two faces.
- Throws:
std::runtime_error – If the source mesh changed.
- Returns:
A new selection.
-
std::shared_ptr<MeshSelection> inverted() const#
Returns every source triangle not currently selected.
- Throws:
std::runtime_error – If the source mesh changed.
- Returns:
A new selection.
-
std::shared_ptr<SurfaceMesh> mesh() const#
Extracts a compact, reindexed open SurfaceMesh containing the selection.
Triangle winding and source triangle labels are kept.
- Throws:
std::runtime_error – If the source mesh changed or the selection is empty.
- Returns:
The extracted mesh.
Creates a selection from explicit triangle IDs.
- Parameters:
source_mesh – Source mesh retained by the selection.
triangle_ids – Triangle IDs to select; duplicates are removed.
- Throws:
std::runtime_error – If source_mesh is null.
std::out_of_range – If a triangle ID is outside the source mesh.
-
std::shared_ptr<MeshSelection> set_difference(const MeshSelection &other) const#
Returns the triangles in this selection but not another selection.
- Parameters:
other – The selection to subtract.
- Throws:
std::runtime_error – If either source changed or the source geometries differ.
- Returns:
A new selection.
-
std::shared_ptr<MeshSelection> set_intersection(const MeshSelection &other) const#
Returns the set intersection with another selection on the same source geometry.
- Parameters:
other – The other selection.
- Throws:
std::runtime_error – If either source changed or the source geometries differ.
- Returns:
A new selection.
-
std::shared_ptr<MeshSelection> set_union(const MeshSelection &other) const#
Returns the set union with another selection on the same source geometry.
- Parameters:
other – The other selection.
- Throws:
std::runtime_error – If either source changed or the source geometries differ.
- Returns:
A new selection.
-
std::shared_ptr<MeshSelection> shrunk(size_t rings = 1) const#
Removes triangle rings from every open or unselected selection boundary.
- Parameters:
rings – Number of boundary rings to remove.
- Throws:
std::runtime_error – If the source mesh changed.
- Returns:
A new selection (possibly empty).
-
const std::string &source_fingerprint() const#
Returns the source fingerprint captured at selection creation.
- Returns:
The fingerprint string.
-
bool source_is_current() const#
Reports whether the retained source mesh still matches the captured fingerprint.
- Returns:
True if the source is unchanged.
-
std::shared_ptr<SurfaceMesh> source_mesh() const#
Returns the retained source mesh.
- Returns:
The source mesh.
-
std::shared_ptr<TriangleMeshSurface> to_triangle_mesh_surface(const std::optional<glm::vec3> &u_axis_hint = std::nullopt, const std::string &method = "lscm") const#
Converts the selection into a parametric triangle-mesh surface.
Builds a TriangleMeshSurface from mesh(), which validates that the patch is a connected, manifold, genus-0 open patch. Interior holes are allowed and treated as trims. Only the default “lscm” method is near-conformal; “arap” balances angle and area distortion, and “authalic” preserves area. The result does not carry outward-orientation evidence; use TriangleMeshSurface::from_selection() for that.
- Parameters:
u_axis_hint – Optional world-space chart U direction.
method – Flattening method: “lscm”, “arap”, or “authalic”.
- Returns:
Validated parametric surface.
-
size_t triangle_count() const#
Returns the number of selected triangles.
- Returns:
The triangle count.
-
const std::vector<size_t> &triangle_ids() const#
Returns sorted, unique triangle IDs.
- Returns:
The triangle IDs.
Private Functions
-
void verify_compatible(const MeshSelection &other) const#
-
void verify_source() const#
Private Members
-
std::string m_source_fingerprint#
-
std::shared_ptr<SurfaceMesh> m_source_mesh#
-
std::vector<size_t> m_triangle_ids#
-
double area() const#
Functions
-
std::vector<double> ray_distances_to_mesh(const std::vector<glm::vec3> &origins, const std::vector<glm::vec3> &directions, const std::vector<glm::vec3> &vertices, const std::vector<Indexed_Triangle> &triangles, double max_distance)#
Measures the distance along each ray to its first intersection with a triangle mesh.
The mesh may be open and need not be oriented (for example a shell’s inner surface exported from CAD). Intersections are exact ray-triangle tests accelerated by an AABB tree; hits at the ray origin (distance zero) count.
- Parameters:
- Throws:
std::runtime_error – if the counts differ, a ray is not finite or has a zero direction, max_distance is not positive and finite, or the mesh is empty, degenerate or indexes out of range.
- Returns:
One distance per ray, or NaN where nothing is hit within max_distance.
Measures the distance along each ray to the first zero crossing of a node’s field.
The target is cloned and the clone is prepared with voxel_size and a bandwidth of max_distance, so the caller’s node is untouched. Each ray is marched with sphere tracing: steps are the absolute field value (never smaller than tolerance), a hit is a value within tolerance of zero or a sign change, and a sign change is refined by bisection to tolerance. Sign-change detection keeps the march robust for approximate distance fields. Rays are traced in parallel with one target clone per thread.
Typical use: the gap from every vertex of a head patch along its normal to a helmet shell, to drive a variable-height CellMap.
- Parameters:
origins – Ray start points in mm.
directions – Ray directions; normalized internally and required to be non-zero.
target – The node whose zero level set is hit.
max_distance – Positive maximum ray length in mm.
tolerance – Positive hit tolerance in mm.
voxel_size – Positive voxel size in mm used to prepare the target clone.
- Throws:
std::runtime_error – if the counts differ, a ray is not finite or has a zero direction, target is null, or max_distance, tolerance or voxel_size is not positive and finite.
- Returns:
One distance per ray, or NaN where nothing is hit within max_distance.
-
class TriangleMeshSurface : public ParametricSurface#
- #include <triangle_mesh_surface.h>
An immutable triangle-mesh disk patch exposed as a near-conformally parameterized surface with a trimmed, natural-shape chart.
TriangleMeshSurface takes an open triangle mesh that is topologically a disk and flattens it into a 2D chart so a discrete mesh can drive the same structured CellMap machinery as an exact CAD face.
Parameterization: the flattening method is selectable. The default “lscm” flattens with free-boundary least-squares conformal maps (LSCM, Levy et al. 2002) pinning only two vertices, so the chart takes the patch’s natural outline instead of being forced onto a square. “arap” flattens with the as-rigid-as-possible energy (Liu et al. 2008), which balances angle and area distortion on a free boundary. “authalic” flattens with the iterative area-preserving parameterizer (Jain et al. 2019) on a circular arc-length border, trading angle fidelity for near-uniform area. Whichever method is chosen, the chart is then fitted into its axis-aligned bounding rectangle, which uv_bounds() reports with the longer side normalized to exactly 1. The chart does not fill that rectangle: the region between the chart boundary and the rectangle is outside the surface, and contains() reports it as such so CellMap trimming can deactivate it.
Injective fallback: none of the primary methods guarantees a one-to-one chart. When the requested chart folds (flipped or collapsed chart triangles, or a failed global overlap check), the surface automatically falls back to Floater mean-value coordinates on a circular arc-length border (Floater 2003, Tutte 1963), whose positive convex-combination weights on a convex border guarantee an injective chart at the cost of more shape distortion. parameterization_method() reports which parameterizer produced the chart. Only when both fail is the patch rejected.
Orientation control: the chart’s u-axis becomes the lattice’s first logical direction, so it is chosen deliberately instead of inheriting the solver’s arbitrary rotation. By default the chart is rotated so its principal axis (area-weighted covariance of the flattened triangles) runs along +u with a deterministic sign, which gives elongated patches an elongated, axis-aligned chart rectangle; near-isotropic charts keep the solver’s orientation. Alternatively an optional world-space hint direction is projected onto the patch and the chart is rotated so that direction runs along +u.
Input requirements: the mesh must be a single connected, edge-manifold and vertex-manifold component with consistent winding, at least one boundary loop, and genus 0 (Euler characteristic V - E + F = 2 - boundary loops). Closed meshes, handles, disconnected components, and non-manifold configurations are each rejected with a distinct message.
Holes are trims: a patch may carry interior openings (vents, cut-outs), which makes it a genus-0 patch with several boundary loops. The longest boundary loop (by world-space length) is the outer edge; every other loop is a hole. Each hole is filled internally, for the parameterization only, with a refined and faired patch (CGAL hole filling, which keeps tangent continuity with the surrounding surface), so the whole patch flattens like a disk and the chart stays smooth across the opening. This mirrors how a trimmed CAD face maps its untrimmed parent surface. The filled triangles are trimmed: point() and normal() evaluate on the fill so CellMap cells spanning a hole stay well-conditioned, but contains() reports every chart coordinate inside a hole as off the surface. CellMap trimming therefore removes the lattice from the openings and seals their walls exactly as it handles the outer edge. If faired filling fails for a hole, a refined unfaired fill is used, then a centroid fan as a last resort. The accessors vertices(), triangles(), uv_coordinates(), vertex_normals(), and mesh() always describe the input patch; fill vertices are appended internally after the input vertices.
Orientation: input triangle winding defines the positive normal direction, and therefore the positive height direction of any CellMap built from this surface. Normals are angle-weighted vertex normals interpolated barycentrically, so the offset direction stays continuous across triangle edges. Smooth normals deliberately round sharp creases, and large offsets can still self-intersect; CellMap’s own Jacobian diagnostics remain the authoritative check on the final volume.
Public Functions
-
virtual std::pair<glm::vec3, glm::vec3> bounding_box() const override#
Returns the world-space bounding box of the selected surface.
- Returns:
The box as (minimum, maximum) corners.
-
virtual bool contains(double u, double v, double tolerance = 1e-7) const override#
Tests whether chart coordinates lie on the parameterized patch.
This is a real point-in-chart test against the flattened triangles, so the empty region between the chart outline and the bounding rectangle reports false. Chart coordinates inside a filled hole also report false, because only the input triangles count as the surface. CellMap trimming uses exactly this predicate to deactivate cells beyond the patch’s true boundary and inside its holes.
- Parameters:
u – Chart U coordinate.
v – Chart V coordinate.
tolerance – Chart-space distance within which a near-boundary point is accepted.
- Returns:
True when the coordinates lie on or within tolerance of the chart.
-
virtual std::shared_ptr<PreparedSurfaceProjector> create_projector(const glm::vec3 &voxel_size, double support_mm) const override#
Builds the accelerated world-space triangle projector used by relief geometry.
- Parameters:
voxel_size – Unused; accepted for the ParametricSurface interface.
support_mm – Maximum normal/lateral query support required by the consumer.
- Throws:
std::runtime_error – If support_mm is negative or not finite.
- Returns:
Prepared cloneable projector.
-
std::shared_ptr<SurfaceMesh> filled_mesh() const#
Returns the patch with its holes filled, exactly as it was flattened.
The first vertex_count() vertices and triangle_count() triangles are the input patch; the fill vertices and triangles follow. Useful to inspect the fill.
- Returns:
An immutable copy of the filled patch as an open SurfaceMesh.
-
size_t filled_triangle_count() const#
Returns the number of triangles added to fill holes for the parameterization.
- Returns:
Zero for a simple disk patch.
-
size_t hole_count() const#
Returns the number of interior boundary loops (holes) filled for parameterization.
- Returns:
Zero for a simple disk patch.
-
std::shared_ptr<SurfaceMesh> mesh() const#
Returns an immutable copy of the patch as a SurfaceMesh.
- Returns:
The input patch (without hole fills).
-
virtual double minimum_trim_feature() const override#
Returns the smallest chart-space feature the trim must resolve.
For a patch with holes this is the smallest hole width estimate, twice the hole’s chart area divided by its chart perimeter (half the diameter of a round hole, about the width of a slot). Zero for a patch without holes, so CellMap trimming keeps its default resolution.
- Returns:
Feature size in chart units (the longer chart side spans 1).
-
virtual glm::vec3 normal(double u, double v) const override#
Evaluates the interpolated unit normal at chart coordinates.
- Parameters:
u – Chart U coordinate.
v – Chart V coordinate.
- Returns:
Normalized barycentric blend of the angle-weighted vertex normals.
-
virtual bool outward_orientation_validated() const override#
Reports whether this patch was selected from a validated outward source solid.
- Returns:
True only for patches built by from_selection().
-
const std::string ¶meterization_method() const#
Reports which parameterizer produced the chart.
- Returns:
“free_boundary_lscm”, “free_boundary_arap”, or “convex_border_iterative_authalic” for the requested primary method, or “convex_border_mean_value” when the guaranteed-injective fallback was used.
-
virtual glm::vec3 point(double u, double v) const override#
Evaluates the patch position at chart coordinates.
Coordinates inside the chart interpolate barycentrically within the owning parameter triangle. Coordinates outside the chart continue the nearest chart triangle’s affine map, mirroring how a trimmed CAD face extends its underlying surface, so CellMap cells that straddle the trim boundary stay well-conditioned.
- Parameters:
u – Chart U coordinate.
v – Chart V coordinate.
- Returns:
World-space position on the patch.
-
const std::vector<size_t> &source_triangle_ids() const#
Returns stable source triangle IDs for a selected patch, or an empty list.
- Returns:
The IDs passed to from_selection(), or empty for other constructors.
-
size_t triangle_count() const#
Returns the number of patch triangles.
- Returns:
The input triangle count.
Constructs a parameterized patch from an existing surface mesh.
The mesh data is copied, so later edits to the source do not affect this surface.
- Parameters:
mesh – The source mesh, which must be a triangle-mesh disk.
u_axis_hint – Optional world-space direction the chart’s u-axis should follow.
method – The flattening method: “lscm”, “arap”, or “authalic”.
-
explicit TriangleMeshSurface(const std::string &file_path, const std::optional<glm::vec3> &u_axis_hint = std::nullopt, const std::string &method = "lscm")#
Constructs a parameterized patch from a mesh file.
The file is loaded as a SurfaceMesh (without its optional closed-mesh check) and then validated against the patch requirements described in the class details.
- Parameters:
file_path – The path to the mesh file to load.
u_axis_hint – Optional world-space direction the chart’s u-axis should follow.
method – The flattening method: “lscm”, “arap”, or “authalic”.
-
TriangleMeshSurface(const std::vector<glm::vec3> &vertices, const std::vector<Indexed_Triangle> &triangles, const std::optional<glm::vec3> &u_axis_hint = std::nullopt, const std::string &method = "lscm")#
Constructs a parameterized patch from raw vertices and indexed triangles.
- Parameters:
vertices – The patch vertices.
triangles – The indexed triangular faces, consistently wound.
u_axis_hint – Optional world-space direction the chart’s u-axis should follow.
method – The flattening method: “lscm”, “arap”, or “authalic”.
-
const std::vector<Indexed_Triangle> &triangles() const#
Returns the patch triangles.
- Returns:
The input patch triangles (hole fill triangles are not included).
-
inline virtual bool u_periodic() const override#
A mesh chart never wraps, so the U parameter is not periodic.
- Returns:
Always false.
-
virtual std::pair<glm::vec2, glm::vec2> uv_bounds() const override#
Returns the chart’s axis-aligned bounding rectangle.
The chart is normalized so its minimum corner is (0, 0) and its longer side spans exactly 1, preserving the chart’s aspect ratio. The chart itself is the patch’s natural outline and does not fill this rectangle; use contains() to test whether a coordinate actually lies on the patch.
- Returns:
The minimum and maximum UV corners of the chart bounding rectangle.
-
const std::vector<glm::vec2> &uv_coordinates() const#
Returns the per-vertex chart coordinates inside the reported UV bounds.
- Returns:
One chart coordinate per input vertex.
-
inline virtual bool v_periodic() const override#
A mesh chart never wraps, so the V parameter is not periodic.
- Returns:
Always false.
-
size_t vertex_count() const#
Returns the number of patch vertices.
- Returns:
The input vertex count.
-
std::shared_ptr<FloatAttribute> vertex_field(const std::vector<double> &values) const#
Interpolates per-vertex values of the input patch at a world-space point.
The point is projected to the closest point on the input patch triangles (never onto a hole fill) and the values of that triangle’s corners are blended barycentrically. Points over a hole or beyond the outer edge therefore take the value at the nearest patch point. Passed as a CellMap height, which samples at base points on the surface, this interpolates the values across the chart.
- Parameters:
values – One finite value per input vertex, in input vertex order.
- Returns:
A thread-safe scalar FloatAttribute sampled in world coordinates.
-
const std::vector<glm::vec3> &vertex_normals() const#
Returns the per-vertex angle-weighted unit normals.
- Returns:
One unit normal per input vertex.
-
const std::vector<glm::vec3> &vertices() const#
Returns the patch vertices.
- Returns:
The input patch vertices (hole fill vertices are not included).
-
~TriangleMeshSurface() override#
Destructor.
Public Static Functions
Extracts and parameterizes an explicitly selected triangle patch.
Selected triangles are copied and reindexed without changing their winding. The source is revalidated as a closed outward-oriented volume so the resulting surface carries positive-normal orientation evidence for relief geometry.
- Parameters:
source_mesh – Watertight source mesh retained unchanged.
triangle_ids – Stable indices into source_mesh.triangles().
u_axis_hint – Optional world-space chart U direction.
- Throws:
std::runtime_error – If the source is null, not watertight, or not outward oriented, if triangle_ids is empty, out of range, or repeats an ID, or if the patch is rejected.
- Returns:
Validated selected patch.
Private Functions
-
void initialize(std::vector<glm::vec3> vertices, std::vector<Indexed_Triangle> triangles, const std::optional<glm::vec3> &u_axis_hint, const std::string &method)#
Private Members
-
std::unique_ptr<Impl> m_impl#
-
virtual std::pair<glm::vec3, glm::vec3> bounding_box() const override#
-
class ParametricSurface#
- #include <parametric_surface.h>
Abstract contract for a surface that can be evaluated on a rectangular UV domain.
Implementations expose a bounded parameter rectangle, an oriented point map, and an oriented unit normal. This is the minimum surface interface required to build a structured curvilinear CellMap, and it is shared by exact CAD faces and by parameterized triangle-mesh patches.
Coordinates: uv_bounds() reports the native parameter rectangle. Callers sample the rectangle by linear interpolation between its corners, so implementations must accept any coordinate inside those bounds. Implementations backed by a trimmed or non-rectangular domain report the enclosing rectangle and use contains() to report which coordinates actually lie on the surface.
Tolerance: contains() accepts a parametric tolerance so callers can treat boundary coordinates as inside. Implementations must remain stable and deterministic for coordinates exactly on a boundary.
Orientation: normal() returns the oriented unit normal that defines the positive offset direction of the surface. CellMap extrudes along this direction, so the sign convention of an implementation determines the sign convention of a signed-height map.
Subclassed by CADFace, TriangleMeshSurface
Public Functions
-
virtual std::pair<glm::vec3, glm::vec3> bounding_box() const = 0#
Returns the world-space bounding box of the selected surface.
- Returns:
The box as (minimum, maximum) corners.
-
virtual bool contains(double u, double v, double tolerance = 1e-7) const = 0#
Tests whether native UV coordinates lie on the surface.
- Parameters:
u – Native U coordinate to test.
v – Native V coordinate to test.
tolerance – Parametric tolerance used to accept near-boundary coordinates.
- Returns:
True when the coordinates lie on the surface.
-
virtual std::shared_ptr<PreparedSurfaceProjector> create_projector(const glm::vec3 &voxel_size, double support_mm) const = 0#
Builds a reusable world-space projector for a finite support neighborhood.
- Parameters:
voxel_size – Requested downstream sampling resolution in millimetres.
support_mm – Maximum normal/lateral query support required by the consumer.
- Returns:
Prepared cloneable projector.
-
inline virtual double minimum_trim_feature() const#
Returns the smallest native-UV feature that a boundary trim must resolve.
CellMap samples contains() on a grid to build its implicit boundary trim. A surface with small interior trims (holes) reports their size here so the grid is refined until each one is resolved. The default of zero keeps the standard trim resolution.
- Returns:
Feature size in native UV units, or zero when no refinement is needed.
-
virtual glm::vec3 normal(double u, double v) const = 0#
Evaluates the oriented unit normal at native UV coordinates.
- Parameters:
u – Native U coordinate inside the reported bounds.
v – Native V coordinate inside the reported bounds.
- Returns:
Oriented unit normal defining the positive offset direction.
-
virtual bool outward_orientation_validated() const = 0#
Reports whether positive normal orientation was validated against a source solid.
Surface relief requires this evidence so raised geometry cannot silently grow into a solid because of ambiguous standalone patch winding.
- Returns:
True when the normal is known to point out of the source solid.
-
virtual glm::vec3 point(double u, double v) const = 0#
Evaluates the surface position at native UV coordinates.
- Parameters:
u – Native U coordinate inside the reported bounds.
v – Native V coordinate inside the reported bounds.
- Returns:
World-space position on the surface.
-
virtual bool u_periodic() const = 0#
Reports whether the U parameter wraps through a seam.
- Returns:
True when U is periodic.
-
virtual std::pair<glm::vec2, glm::vec2> uv_bounds() const = 0#
Returns the native parameter rectangle as (minimum, maximum) UV corners.
- Returns:
The minimum and maximum UV coordinates of the parameter rectangle.
-
virtual bool v_periodic() const = 0#
Reports whether the V parameter wraps through a seam.
- Returns:
True when V is periodic.
-
virtual ~ParametricSurface() = default#
Virtual destructor.
-
virtual std::pair<glm::vec3, glm::vec3> bounding_box() const = 0#
-
class PreparedSurfaceProjector#
- #include <surface_projector.h>
Cloneable prepared world-to-surface projector.
Implementations build expensive acceleration state once and answer repeated queries without scanning surface triangles or CAD topology.
Public Functions
-
virtual std::shared_ptr<PreparedSurfaceProjector> clone() const = 0#
Clones mutable query state while sharing immutable prepared data where safe.
- Returns:
A projector that can be queried from another thread.
-
virtual SurfaceProjection project(const glm::vec3 &world) = 0#
Projects one world point onto the prepared surface support.
- Parameters:
world – World-space query point.
- Returns:
Closest surface data and patch-boundary classification.
-
virtual ~PreparedSurfaceProjector() = default#
Virtual destructor.
-
virtual std::shared_ptr<PreparedSurfaceProjector> clone() const = 0#
-
struct SurfaceProjection#
- #include <surface_projector.h>
Prepared closest-surface query result used by conformal relief geometry.
boundary_signed_distance is negative inside the selected patch, zero on its true boundary, and positive outside. millimeters_per_u and millimeters_per_v are local metric estimates for one native parameter unit.
Public Members
-
double boundary_signed_distance = 0.0#
Signed distance to the patch boundary (negative inside), in mm.
-
double millimeters_per_u = 1.0#
World length of one native U unit at that point.
-
double millimeters_per_v = 1.0#
World length of one native V unit at that point.
-
glm::vec3 normal = {0.0f, 0.0f, 1.0f}#
Oriented unit normal at that point.
-
glm::vec3 point = {0.0f}#
Closest point on the surface, in world space.
-
glm::vec2 uv = {0.0f}#
Native UV coordinates of that point.
-
double boundary_signed_distance = 0.0#
-
class FunctionalHeightField : public HeightField#
- #include <height_field.h>
FloatAttribute-backed normalized height function.
The attribute receives normalized surface coordinates as (x, y), z=0, d=0. Its result is clamped to [0, 1] and multiplied by amplitude_mm.
Public Functions
-
inline double amplitude_mm() const#
Returns the amplitude.
- Returns:
The height in millimetres of a normalized value of 1.
-
virtual std::shared_ptr<HeightField> clone() const override#
Clones mutable sampling state.
- Returns:
An independent copy that can be sampled from another thread.
Constructor.
- Parameters:
function – The normalized height function, sampled at (u, v, 0) with d = 0.
amplitude_mm – Height in millimetres of a normalized value of 1; finite and non-negative.
- Throws:
std::runtime_error – if function is null or amplitude_mm is invalid.
-
virtual double maximum_height() const override#
Returns the conservative maximum height in millimetres.
- Returns:
The upper bound on sample(); equal to the amplitude for the built-in fields.
-
virtual double sample(double u, double v, double millimeters_per_u, double millimeters_per_v, const glm::vec3 &voxel_size) override#
Samples physical height in millimetres.
The UV metric and voxel size are ignored; the function is not filtered.
- Parameters:
u – Normalized horizontal coordinate.
v – Normalized vertical coordinate.
millimeters_per_u – Local world distance for one normalized U unit.
millimeters_per_v – Local world distance for one normalized V unit.
voxel_size – Requested downstream voxel size.
- Throws:
std::runtime_error – if the function returns a non-finite value.
- Returns:
Non-negative relief height in millimetres.
-
inline double amplitude_mm() const#
-
class HeightField#
- #include <height_field.h>
Scalar source of non-negative physical relief height.
Coordinates are normalized over the selected surface UV bounds. Implementations return millimetres and are sampled in constant time after construction.
Subclassed by FunctionalHeightField, ImageHeightField
Public Functions
-
virtual std::shared_ptr<HeightField> clone() const = 0#
Clones mutable sampling state.
- Returns:
An independent copy that can be sampled from another thread.
-
virtual double maximum_height() const = 0#
Returns the conservative maximum height in millimetres.
- Returns:
The upper bound on sample(); equal to the amplitude for the built-in fields.
-
virtual double sample(double u, double v, double millimeters_per_u, double millimeters_per_v, const glm::vec3 &voxel_size) = 0#
Samples physical height in millimetres.
- Parameters:
u – Normalized horizontal coordinate.
v – Normalized vertical coordinate.
millimeters_per_u – Local world distance for one normalized U unit.
millimeters_per_v – Local world distance for one normalized V unit.
voxel_size – Requested downstream voxel size.
- Returns:
Non-negative relief height in millimetres.
-
virtual ~HeightField() = default#
Virtual destructor.
-
virtual std::shared_ptr<HeightField> clone() const = 0#
-
class ImageHeightField : public HeightField#
- #include <height_field.h>
Immutable mip-filtered PNG height map.
PNG values are converted from the requested channel to [0, 1], then multiplied by amplitude_mm. (0, 0) is the lower-left image corner. The PNG is decoded at 16 bits per channel, and a box-filtered mip chain is built down to 1x1. sample() picks the level whose texel size matches the largest voxel edge and blends bilinear lookups of two levels. Clones share the immutable image data.
Public Functions
-
const std::string &channel() const#
Returns the channel read from the image.
- Returns:
“luminance”, “red”, “green” or “blue”.
-
virtual std::shared_ptr<HeightField> clone() const override#
Clones mutable sampling state.
- Returns:
An independent copy that can be sampled from another thread.
-
size_t height() const#
Returns the image height in pixels.
- Returns:
The height of the full-resolution level.
-
ImageHeightField(const std::string &path, double amplitude_mm, const std::string &channel = "luminance", const std::string &mapping = "fit", const std::array<size_t, 2> &repeats = {1, 1})#
Loads a PNG height map.
- Parameters:
path – Path to the PNG file.
amplitude_mm – Height in millimetres of a full-scale (1.0) pixel; finite and non-negative.
channel – The channel read: “luminance” (Rec. 709 weights), “red”, “green” or “blue”.
mapping – “fit” stretches the image once over [0, 1] x [0, 1] and clamps outside it; “repeat” tiles it.
repeats – Tile counts along u and v for “repeat”; must be (1, 1) for “fit”.
- Throws:
std::runtime_error – if an argument is invalid or the PNG cannot be decoded.
-
const std::string &mapping() const#
Returns the UV mapping mode.
- Returns:
“fit” or “repeat”.
-
virtual double maximum_height() const override#
Returns the conservative maximum height in millimetres.
- Returns:
The upper bound on sample(); equal to the amplitude for the built-in fields.
-
size_t mip_level_count() const#
Returns the number of mip levels, including the full-resolution image.
- Returns:
The mip level count.
-
const std::string &path() const#
Returns the PNG path.
- Returns:
The path given to the constructor.
-
const std::array<size_t, 2> &repeats() const#
Returns the tile counts along u and v.
- Returns:
The repeats given to the constructor.
-
virtual double sample(double u, double v, double millimeters_per_u, double millimeters_per_v, const glm::vec3 &voxel_size) override#
Samples physical height in millimetres.
- Parameters:
u – Normalized horizontal coordinate.
v – Normalized vertical coordinate.
millimeters_per_u – Local world distance for one normalized U unit.
millimeters_per_v – Local world distance for one normalized V unit.
voxel_size – Requested downstream voxel size.
- Throws:
std::runtime_error – if u, v or the UV metric is not finite, or the metric is not positive.
- Returns:
Non-negative relief height in millimetres.
-
size_t width() const#
Returns the image width in pixels.
- Returns:
The width of the full-resolution level.
-
~ImageHeightField() override#
Destructor.
Private Functions
Private Members
-
std::shared_ptr<const Impl> m_impl#
-
const std::string &channel() const#
-
class CADPart#
- #include <cad_part.h>
A CAD geometry primitive.
Holds an OCCT shape in memory and provides a signed distance adapter to the surface.
Note
The path constructor reads STEP (.step, .stp) and IGES (.iges, .igs) files, chosen by the extension (case-insensitive). Any other OCCT shape, such as a BREP read by CADModel, can be passed to the TopoDS_Shape constructor.
Public Functions
-
std::pair<glm::vec3, glm::vec3> bounding_box()#
Returns the shape’s axis-aligned bounding box, computed when the part is constructed.
- Returns:
The [min, max] corners in mm.
-
CADPart() = default#
Creates an empty part with no shape.
-
CADPart(const std::string &path)#
Loads a STEP or IGES file.
- Parameters:
path – The path to the CAD file to load (.step, .stp, .iges or .igs; case-insensitive).
- Throws:
std::runtime_error – If the extension is not supported or the file cannot be read.
-
CADPart(TopoDS_Shape part)#
Wraps an existing OpenCascade shape.
- Parameters:
part – The shape. Any OCCT shape is accepted, whatever file format it came from.
-
std::shared_ptr<CADPart> clone()#
Copies the part.
The OCCT shape and any fast-mode grid are shared, not deep-copied.
- Returns:
The copy.
-
void export_as_stl(const std::string &path, double deflection = 0.1)#
Tessellates the shape and writes it as a binary STL file.
- Parameters:
path – Destination file; it must end in .stl.
deflection – Largest distance in mm between a triangle and the surface.
- Throws:
std::runtime_error – If the extension is not .stl or meshing or writing fails.
-
inline openvdb::FloatGrid::ConstPtr fast_sdf_grid() const#
Returns the signed-distance grid fast mode samples, or null outside fast mode.
- Returns:
The grid built by set_fast_mode().
-
void set_fast_mode(bool fast_mode, glm::vec3 voxel_size, double interior_bandwidth, double exterior_bandwidth, double deflection = 0.1)#
Turns fast mode on or off.
In fast mode, the part is tessellated and converted to a narrow-band OpenVDB signed-distance grid (SurfaceMesh::compute_sdf()), and signed_distance_to_surface() samples that grid trilinearly instead of querying the exact OCCT geometry.
- Parameters:
fast_mode – True to build the grid and use it; false to use the exact geometry.
voxel_size – Grid spacing in mm. The grid is isotropic, so only the smallest component is used.
interior_bandwidth – Narrow-band width inside the surface, in mm.
exterior_bandwidth – Narrow-band width outside the surface, in mm.
deflection – Tessellation deflection in mm used to build the mesh the grid comes from.
-
inline const TopoDS_Shape &shape() const#
Returns the topology-preserving OCCT shape owned by this part.
The returned handle shares OCCT’s underlying shape data and is intended for internal topology adapters such as CADModel and CADFace.
- Returns:
The loaded OCCT shape.
-
double signed_distance_to_surface(double x, double y, double z)#
Returns the signed distance to the surface of the CAD geometry.
- Parameters:
x – The x coordinate
y – The y coordinate
z – The z coordinate
- Returns:
The signed distance in mm, negative inside the solid. In fast mode it is the trilinear grid value, which saturates at the band edge outside the narrow band.
-
std::shared_ptr<SurfaceMesh> tessellate(double deflection, double angular_deflection = 0.5, bool relative = false, bool disable_validation = true)#
Tessellates every face into one welded, consistently oriented SurfaceMesh.
Triangles of reversed faces are flipped so solids face outward, nodes shared by neighbouring faces are welded within a small tolerance, and each triangle’s label is the index of its face in TopExp_Explorer order (CADModel::faces() order).
- Parameters:
deflection – Largest distance in millimetres between a triangle and the surface.
angular_deflection – Largest angle in radians between neighbouring triangle normals.
relative – If true, deflection is relative to each edge’s size.
disable_validation – If true, bypass CGAL closure validation on the generated mesh.
- Returns:
The labelled triangle mesh.
-
std::shared_ptr<SurfaceMesh> to_surface_mesh(double deflection = 0.1, bool disable_validation = false)#
Tessellates the shape into a SurfaceMesh.
Same as tessellate() with a 0.5 rad angular deflection.
- Parameters:
deflection – Largest distance in mm between a triangle and the surface.
disable_validation – If true, bypass CGAL closure validation on the generated mesh.
- Returns:
The triangle mesh.
Private Types
-
typedef openvdb::FloatGrid GridType#
The type of grid used by OpenVDB.
Private Functions
-
void compute_bbox()#
Generates local Bnd_box parameters from the base CAD shape definition array bounds.
-
void prepare_classification()#
Prepares standard inside classification elements for the underlying part structure limits.
-
void prepare_fast_classification(glm::vec3 voxel_size, double interior_bandwidth, double exterior_bandwidth, double deflection = 0.1)#
Formats accelerated grid memory block samplers caching classification bounds using an implicit volume conversion.
Private Members
-
BRepClass3d_SolidClassifier m_classifier#
The explicit solid shape volume mapper.
-
bool m_fast_mode = false#
Toggles state flags enabling rapid sampling parameters utilizing discrete blocks over true geometry projection evaluation matrices.
-
glm::vec3 m_max#
Evaluation limit mapping the upper coordinate bounds marking shape scope regions.
-
glm::vec3 m_min#
Evaluation limit mapping the lower coordinate block geometry limits.
-
TopoDS_Shape m_part#
Base representation shape generated from initial files.
-
openvdb::tools::GridSampler<GridType, openvdb::tools::BoxSampler>::Ptr m_sampler#
Sampling structure mapped linearly over grid data mapping boolean interpolation boundaries.
-
TopoDS_Shape m_shell#
Unused shell container wrapping representation evaluation definitions.
-
std::pair<glm::vec3, glm::vec3> bounding_box()#
-
class CADFace : public ParametricSurface#
- #include <cad_model.h>
A stable topology-preserving face handle owned by a CADModel.
Metadata and native UV evaluation are derived directly from the retained OCCT face. CADFace satisfies the ParametricSurface contract using the exact OCCT surface, so it can be mapped by CellMap interchangeably with a parameterized triangle-mesh patch.
Public Functions
-
double area() const#
Returns the area of the trimmed face.
- Returns:
The area in mm^2.
-
size_t boundary_loop_count() const#
Returns the number of boundary wires (outer loop plus holes).
- Returns:
The wire count.
-
virtual std::pair<glm::vec3, glm::vec3> bounding_box() const override#
Returns the world-space bounding box of the selected surface.
- Returns:
The box as (minimum, maximum) corners.
Wraps one face of a model.
Normally created by CADModel::faces().
- Parameters:
model – The owning model, kept alive by the face.
face – The OCCT face.
index – The face’s stable index in the model (TopExp_Explorer order).
-
glm::vec3 centroid() const#
Returns the area centroid of the trimmed face.
- Returns:
The centroid in world coordinates.
-
virtual bool contains(double u, double v, double tolerance = 1e-7) const override#
Tests whether native UV coordinates lie within the trimmed face.
- Parameters:
u – Native U coordinate to test.
v – Native V coordinate to test.
tolerance – Parametric tolerance passed to the OCCT face classifier.
- Returns:
True when the coordinates are inside or on the boundary of the trimmed face.
-
virtual std::shared_ptr<PreparedSurfaceProjector> create_projector(const glm::vec3 &voxel_size, double support_mm) const override#
Builds a reusable world-space projector for a finite support neighborhood.
- Parameters:
voxel_size – Requested downstream sampling resolution in millimetres.
support_mm – Maximum normal/lateral query support required by the consumer.
- Returns:
Prepared cloneable projector.
-
inline size_t index() const#
Returns the face’s stable index in its model, matching CADModel::faces().
- Returns:
The face index.
-
bool is_trimmed() const#
Reports whether the face is trimmed, that is, not bounded by its surface’s natural UV limits.
- Returns:
True for a trimmed face.
-
glm::vec3 normal() const#
Returns a representative oriented unit normal.
Samples a 5 x 5 UV grid from the centre outward and returns the normal at the first sample that lies on the trimmed face and has a defined normal.
- Throws:
std::runtime_error – If no sample has a defined normal.
- Returns:
The oriented unit normal.
-
virtual glm::vec3 normal(double u, double v) const override#
Evaluates the oriented unit normal at native UV coordinates.
The normal is flipped for reversed faces, so it follows the face orientation.
- Parameters:
u – Native U coordinate.
v – Native V coordinate.
- Throws:
std::runtime_error – If the normal is singular at (u, v).
- Returns:
The oriented unit normal.
-
virtual bool outward_orientation_validated() const override#
Reports whether positive normal orientation was validated against a source solid.
Surface relief requires this evidence so raised geometry cannot silently grow into a solid because of ambiguous standalone patch winding.
Probes points just above and below the face against the owning solid. Returns false both when the normal points inward and when no probe is conclusive (for example an open shell). The result is cached.
- Returns:
True when the normal is known to point out of the source solid.
-
virtual glm::vec3 point(double u, double v) const override#
Evaluates the exact CAD surface at native UV coordinates.
- Parameters:
u – Native U coordinate.
v – Native V coordinate.
- Returns:
World-space position on the underlying surface (trimming is not applied).
-
inline const TopoDS_Face &shape() const#
Returns the underlying OCCT face.
- Returns:
The face.
-
std::string surface_type() const#
Returns the underlying surface type.
- Returns:
One of “plane”, “cylinder”, “cone”, “sphere”, “torus”, “bezier”, “bspline”, “revolution”, “extrusion”, “offset”, or “other”.
-
virtual bool u_periodic() const override#
Reports whether the U parameter wraps through a seam.
- Returns:
True when U is periodic.
-
virtual std::pair<glm::vec2, glm::vec2> uv_bounds() const override#
Returns the native parameter rectangle as (minimum, maximum) UV corners.
- Throws:
std::runtime_error – If the bounds are not finite.
- Returns:
The minimum and maximum UV coordinates of the parameter rectangle.
-
virtual bool v_periodic() const override#
Reports whether the V parameter wraps through a seam.
- Returns:
True when V is periodic.
-
double area() const#
-
class CADModel : public std::enable_shared_from_this<CADModel>#
- #include <cad_model.h>
A topology-preserving CAD model parsed once and shared by faces and implicit nodes.
Public Functions
Wraps a loaded CAD part.
- Parameters:
part – The part.
- Throws:
std::runtime_error – If part is null or its shape is empty.
-
std::shared_ptr<CADFace> face(size_t index)#
Returns one face by stable index.
- Parameters:
index – The face index, as in faces().
- Throws:
std::out_of_range – If the index is out of range.
- Returns:
The face.
-
std::vector<std::shared_ptr<CADFace>> faces()#
Returns every face, in stable TopExp_Explorer order.
New CADFace handles are created on every call; their indices are stable.
- Returns:
The faces.
-
inline const std::shared_ptr<CADPart> &part() const#
Returns the CAD part that owns the OCCT shape.
- Returns:
The part.
-
std::vector<std::shared_ptr<CADFace>> select_faces(const FaceSelection &selection)#
Returns the faces that pass every filter in
selection, in index order.- Parameters:
selection – The filters.
- Throws:
std::runtime_error – If min_dot is outside [-1, 1], normal is zero, an area bound is negative, or min_area is greater than max_area.
- Returns:
The selected faces (possibly empty).
-
std::shared_ptr<CAD> to_node(bool use_fast_mode = false, std::optional<double> fast_sdf_voxel_size = std::nullopt)#
Converts the retained CAD model into an implicit CAD node.
- Parameters:
use_fast_mode – Whether preparation should construct an accelerated SDF grid.
fast_sdf_voxel_size – Optional uniform SDF cache spacing in millimetres. Only valid with use_fast_mode; the CAD constructor throws std::runtime_error if it is set without fast mode or is not finite and positive. An empty value uses the smallest downstream sampling voxel component.
- Returns:
The CAD node, sharing this model’s part.
-
std::shared_ptr<SurfaceMesh> to_surface_mesh(double deflection = 0.1, double angular_deflection_degrees = 20.0, bool relative = false)#
Tessellates the exact CAD surfaces into a SurfaceMesh labelled by face.
Each triangle’s label (SurfaceMesh::triangle_labels) is the stable index of the CAD face it came from, matching faces(). Triangles follow the face orientation, so a closed solid gives an outward-facing mesh, and vertices on shared edges are welded so neighbouring faces connect. No voxel resampling is involved.
- Parameters:
deflection – Largest distance in millimetres between a triangle and the surface.
angular_deflection_degrees – Largest angle between neighbouring triangle normals along a curved face, in degrees.
relative – If true, deflection is relative to each edge’s size instead of absolute.
- Returns:
The labelled triangle mesh.
Public Static Functions
-
static std::shared_ptr<CADModel> from_brep(const std::string &path)#
Reads an ASCII OCCT BREP file.
- Parameters:
path – The file path.
- Throws:
std::runtime_error – If the file cannot be opened or holds an empty shape.
- Returns:
The model.
-
static std::shared_ptr<CADModel> from_brep_bytes(const std::string &data)#
Reads ASCII OCCT BREP data from memory.
- Parameters:
data – The BREP text.
- Throws:
std::runtime_error – If the data holds an empty shape.
- Returns:
The model.
-
struct FaceSelection#
- #include <cad_model.h>
Filters for select_faces().
A face is selected only when it passes every set filter.
Public Members
-
std::optional<std::pair<glm::vec3, glm::vec3>> bounds#
World box the face’s bounding box must intersect.
-
std::vector<size_t> indices#
Face indices to consider; empty means all faces.
-
std::optional<double> max_area#
Largest accepted face area in mm^2 (non-negative, not below min_area).
-
std::optional<double> min_area#
Smallest accepted face area in mm^2 (non-negative).
-
double min_dot = -1.0#
Smallest accepted dot product with
normal, in [-1, 1].
-
std::optional<glm::vec3> normal#
Direction compared with CADFace::normal(); normalized, must be non-zero.
-
std::optional<std::string> surface_type#
Required CADFace::surface_type(), compared case-insensitively.
-
std::optional<std::pair<glm::vec3, glm::vec3>> bounds#
-
class CellMap#
- #include <cell_map.h>
Immutable structured curvilinear map from logical unit cells to world space.
Logical coordinates cover [0, nu] x [0, nv] x [0, nw]. Linear maps use one trilinear element per cell; curved maps use eight sub-elements per cell so midpoint CAD samples are retained without runtime OCCT queries.
Public Types
-
enum class TrimMode#
Strategy for restricting a surface-built map to the surface’s true domain.
Surfaces backed by a trimmed or non-rectangular chart do not fill their UV bounding rectangle. TrimMode selects how the map treats the empty margin: keep it, remove whole logical elements, or clip implicitly at the true boundary curve.
Values:
-
enumerator none#
Keep the full rectangular logical domain; nothing is removed.
-
enumerator cells#
Deactivate whole structured elements outside the surface domain.
-
enumerator boundary#
Clip smoothly at the surface’s true boundary curve (default).
-
enumerator none#
Public Functions
-
inline const std::vector<bool> &active_elements() const#
Returns the per-element activity mask, in element order.
- Returns:
The activity mask.
-
CellMap(const glm::ivec3 &cells, int subdivisions, const std::vector<glm::vec3> &control_points, const std::array<bool, 3> &periodic = {false, false, false}, const std::vector<bool> &active_elements = {})#
Builds a map from explicit control points.
The map has cells * subdivisions structured elements per axis, each a trilinear hexahedron. Control points are ordered with U fastest, then V, then W. The world bounding box, the element BVH, and the boundary mesh are built here.
- Parameters:
cells – Positive logical cell counts along U, V, and W.
subdivisions – Positive number of structured elements per cell along each axis.
control_points – (cells * subdivisions + 1) control points per axis, all finite.
periodic – Whether U, V, and W wrap through a seam.
active_elements – Per-element activity mask in element order, or empty for all active.
- Throws:
std::runtime_error – If a count is not positive, the control-point or mask size does not match, or a control point is not finite.
-
inline const glm::ivec3 &cells() const#
Returns the logical cell counts along U, V, and W.
- Returns:
The cell counts.
-
bool contains_logical(const glm::vec3 &logical) const#
Reports whether a logical point lies inside the logical bounds and in an active element.
Boundary-trim clipping inside an active element is not applied here.
- Parameters:
logical – Logical U/V/W coordinate.
- Returns:
True if the point is in an active element.
-
inline const std::vector<glm::vec3> &control_points() const#
Returns the control points, U fastest, then V, then W.
- Returns:
The control points.
-
double domain_signed_distance(const glm::vec3 &world) const#
Return signed distance to the finite active CellMap domain.
The boundary is represented by an accelerated triangle mesh extracted from exposed structured-element faces. Distance is negative inside the active map, zero on its boundary, and positive outside. Periodic seams are not boundaries.
- Parameters:
world – World-coordinate query point.
- Returns:
Signed distance to the active map domain.
-
double domain_unsigned_distance(const glm::vec3 &world) const#
Return the unsigned distance to the finite active CellMap boundary.
Like locate(), the result for the most recent query point is cached per thread, because a lattice and its rim query the same point back to back.
- Parameters:
world – World-coordinate query point.
- Returns:
Unsigned distance to the active map boundary.
-
double edge_unsigned_distance(const glm::vec3 &world) const#
Return the unsigned distance to the map’s edge wall.
The edge wall is the side boundary of the active domain: the exposed element faces along the logical U and V perimeter and, for boundary-trimmed maps, the smooth trim wall swept from the surface’s cropped edge through the map height. The base and offset surfaces of the map are deliberately excluded, so this measures distance to the cropped lattice edges only.
- Parameters:
world – World-coordinate query point.
- Returns:
Unsigned distance to the edge wall.
-
inline const glm::ivec3 &element_counts() const#
Returns the structured element counts (cells * subdivisions).
- Returns:
The element counts.
-
glm::vec3 forward(const glm::vec3 &logical) const#
Maps a logical point into world space.
- Parameters:
logical – Logical U/V/W coordinate, measured in cells.
- Throws:
std::runtime_error – If the coordinate is outside the logical bounds or in an inactive element.
- Returns:
The world-space position.
-
glm::vec3 forward_extended_reference(const glm::vec3 &logical) const#
Continue the reference map beyond its finite logical bounds.
Periodic coordinates wrap through their seam. Nonperiodic coordinates use trilinear continuation of the nearest boundary element. Trim activity is not applied. This specialized preparation operation does not change the finite domain semantics of forward(), locate(), or the domain-distance methods.
- Parameters:
logical – Logical reference coordinate, which may lie outside the finite domain.
- Returns:
Continued world-space coordinate.
-
glm::vec3 forward_reference(const glm::vec3 &logical) const#
Map an in-bounds logical reference point without applying trim activity.
This is used while preparing parametric cells whose fields are sampled on the undeformed structured domain, including cells adjacent to a trim.
- Parameters:
logical – Logical U/V/W coordinate inside the finite logical bounds.
- Throws:
std::runtime_error – If the coordinate is outside the logical bounds.
- Returns:
The world-space position.
-
inline bool has_boundary_trim() const#
Report whether the map carries an implicit true-boundary clip.
True only for TrimMode::boundary maps whose chart does not fill its logical rectangle; a rectangular chart has no boundary margin to clip.
- Returns:
True when a boundary trim is installed.
-
inline bool has_edge_wall() const#
Report whether the map has a finite edge wall to measure against.
False only when every lateral direction is periodic and untrimmed, so the domain has no side boundary.
- Returns:
True when the map has an edge wall.
-
std::optional<glm::vec3> inverse(const glm::vec3 &world, double tolerance = 1e-6, size_t max_iterations = 24) const#
Invert a world-space point into logical cell coordinates.
The requested tolerance is clamped to a scale-aware numerical floor because CellMap control points and interpolation use single-precision coordinates.
- Parameters:
world – World-space point to invert.
tolerance – Requested Newton convergence tolerance.
max_iterations – Maximum damped Newton iterations per candidate element.
- Returns:
Logical coordinates, or std::nullopt when the point is outside the active map.
-
glm::mat3 jacobian(const glm::vec3 &logical) const#
Returns the world-space derivatives of the map with respect to U, V, and W.
- Parameters:
logical – Logical U/V/W coordinate.
- Throws:
std::runtime_error – If the coordinate is outside the logical bounds or in an inactive element.
- Returns:
A matrix whose columns are d(world)/dU, d(world)/dV, and d(world)/dW, per logical cell.
-
double jacobian_determinant(const glm::vec3 &logical) const#
Returns the determinant of jacobian() (world volume per logical cell volume).
- Parameters:
logical – Logical U/V/W coordinate.
- Throws:
std::runtime_error – As jacobian().
- Returns:
The Jacobian determinant; positive for a valid, non-inverted map.
-
std::optional<CellMapLocation> locate(const glm::vec3 &world, double tolerance = 1e-6, size_t max_iterations = 24) const#
Locate a world-space point and retain its deterministic cell ownership.
The answer for the most recent query (point, tolerance, iterations) is cached per thread and per map, so several mapped nodes sharing one map (a lattice unioned with its rim, a domain, attribute adapters) invert each sample point once. Cached answers are the exact same values, so results are bit-identical with or without the cache. Boundary-trimmed regions are rejected.
- Parameters:
world – World-space point to locate.
tolerance – Requested Newton convergence tolerance, clamped as in inverse().
max_iterations – Maximum damped Newton iterations per candidate element.
- Throws:
std::runtime_error – If tolerance is not positive and finite.
- Returns:
The location, or std::nullopt when the point is outside the active map.
-
inline const glm::vec3 &maximum() const#
Returns the maximum corner of the control points’ world bounding box.
- Returns:
The maximum corner.
-
inline const glm::vec3 &minimum() const#
Returns the minimum corner of the control points’ world bounding box.
- Returns:
The minimum corner.
-
inline const std::array<bool, 3> &periodic() const#
Returns whether U, V, and W wrap through a seam.
- Returns:
The periodic flags.
-
glm::vec3 principal_stretches(const glm::vec3 &logical) const#
Returns the principal stretches of the map, the singular values of jacobian().
- Parameters:
logical – Logical U/V/W coordinate.
- Throws:
std::runtime_error – As jacobian().
- Returns:
The three stretches in ascending order (x <= y <= z).
-
inline int subdivisions() const#
Returns the number of structured elements per cell along each axis (1 for linear maps).
- Returns:
The subdivision count.
-
inline TrimMode trim_mode() const#
Return the trim strategy the map was built with.
- Returns:
The trim mode.
-
CellMapDiagnostics validate() const#
Checks the Jacobians, inverse lookup, element overlaps, and aspect ratio of the map.
- Returns:
The diagnostics; CellMapDiagnostics::valid() summarizes them.
Public Static Functions
CAD-named compatibility wrapper delegating to between_surfaces(), standoff included.
- Parameters:
first – The face at logical w = 0.
second – The face at logical w = 1.
cells – Logical cell counts along U, V, and the interpolation direction.
linear – True for one trilinear element per cell.
trim – How to restrict the map to the faces’ common valid domain.
auto_align – True to search flips, exchanges, and periodic origins for the best map.
flip_u – Manual U reversal applied to the second face when auto_align is false.
flip_v – Manual V reversal applied to the second face when auto_align is false.
exchange_uv – Manual UV exchange applied to the second face when auto_align is false.
first_origin – Optional periodic seam origin for the first face.
second_origin – Optional periodic seam origin for the second face.
standoff – Signed shift of the first face along its oriented normal before interpolating.
- Returns:
The validated structured map.
Builds a map by interpolating between two parametric surfaces.
Any ordering of CAD faces and triangle-mesh patches is accepted. Surfaces whose periodicity is incompatible, or whose pairing folds the interpolated volume, still fail alignment or Jacobian validation with diagnostics.
- Parameters:
first – The surface at logical w = 0.
second – The surface at logical w = 1.
cells – Logical cell counts along U, V, and the interpolation direction.
linear – True for one trilinear element per cell.
trim – How to restrict the map to the surfaces’ common valid domain.
auto_align – True to search flips, exchanges, and periodic origins for the best map.
flip_u – Manual U reversal applied to the second surface when auto_align is false.
flip_v – Manual V reversal applied to the second surface when auto_align is false.
exchange_uv – Manual UV exchange applied to the second surface when auto_align is false.
first_origin – Optional periodic seam origin for the first surface.
second_origin – Optional periodic seam origin for the second surface.
standoff – Signed distance along the first surface’s oriented normal by which the first surface is shifted before interpolating, so the map starts off it (for example a clearance above a head form). Zero leaves the map unchanged. The second surface is not moved.
- Returns:
The validated structured map.
-
static std::shared_ptr<CellMap> cylindrical(const glm::vec3 ¢er, double inner_radius, double outer_radius, double height, const glm::ivec3 &cells, const glm::vec3 &axis = glm::vec3(0.0f, 0.0f, 1.0f), const glm::vec3 &reference_direction = glm::vec3(1.0f, 0.0f, 0.0f), double start_angle_degrees = 0.0, double sweep_degrees = 360.0, bool linear = false)#
Builds an analytic annular-cylinder map without a CAD dependency.
Logical U follows azimuth, V follows the cylinder axis from the lower end to the upper end, and W follows radius from the inner to the outer boundary.
- Parameters:
center – Center of the cylinder at its axial midpoint.
inner_radius – Positive inner radius.
outer_radius – Outer radius, greater than inner_radius.
height – Positive total axial height.
cells – Logical circumferential, axial, and radial cell counts.
axis – Cylinder axis and positive V direction.
reference_direction – Direction projected normal to axis to define the U seam.
start_angle_degrees – Angular position of logical U = 0 in degrees.
sweep_degrees – Positive angular sweep no greater than 360 degrees.
linear – True for one trilinear element per cell, false for midpoint refinement.
- Returns:
The validated structured map.
CAD-named compatibility wrapper delegating to from_surface().
- Parameters:
face – The CAD face to extrude.
cells – Logical cell counts along U, V, and the height direction.
height – Signed offset distance along the face normal.
linear – True for one trilinear element per cell, false to retain midpoint samples.
trim – How to restrict the map to the face’s valid domain.
standoff – Signed stand-off distance along the face normal at which the map begins.
- Returns:
The validated structured map.
Builds a variable-height map by extruding a parametric surface along its normal.
Identical to the constant-height factory except that the height is a scalar field. It is sampled once per control column, at the column’s base point on the surface (world coordinates, signed-distance argument 0), so the map spans [standoff, standoff + height(p)] along the oriented normal at every column. A constant field reproduces the constant-height map exactly. The field must be finite, non-zero, and of one sign at every column; the sign selects the side of the surface exactly as a constant height does. Use TriangleMeshSurface::vertex_field() for per-vertex heights, for example the ray-cast gap from a head patch to a shell (see ray_distances_to_mesh()), so the cells end on the target. Strongly varying heights can still fold the volume, which the Jacobian validation reports.
- Parameters:
surface – The surface to extrude.
cells – Logical cell counts along U, V, and the height direction.
height – Signed height field in mm sampled at surface base points.
linear – True for one trilinear element per cell, false to retain midpoint samples.
trim – How to restrict the map to the surface’s valid domain.
standoff – Signed stand-off distance along the surface normal at which the map begins, sharing the sign convention of height.
- Returns:
The validated structured map.
Builds a signed-height map by extruding a parametric surface along its normal.
This is the generic implementation shared by exact CAD faces and parameterized triangle-mesh patches. The sign of height follows the surface’s oriented normal, so input orientation determines which side of the surface is filled. A non-zero standoff lifts the whole map off the surface, so it spans [standoff, standoff + height] along the oriented normal.
- Parameters:
surface – The surface to extrude.
cells – Logical cell counts along U, V, and the height direction.
height – Signed offset distance along the surface normal.
linear – True for one trilinear element per cell, false to retain midpoint samples.
trim – How to restrict the map to the surface’s valid domain.
standoff – Signed stand-off distance along the surface normal at which the map begins, sharing the sign convention of height.
- Returns:
The validated structured map.
-
static std::shared_ptr<CellMap> rectangular(const glm::vec3 &minimum, const glm::vec3 &maximum, const glm::ivec3 &cells, bool linear = true)#
Builds an axis-aligned box map.
Logical U, V, and W follow world X, Y, and Z from minimum to maximum.
- Parameters:
minimum – Lower world corner.
maximum – Upper world corner; greater than minimum on every axis.
cells – Positive logical cell counts along U, V, and W.
linear – True for one trilinear element per cell, false for two per cell per axis.
- Throws:
std::runtime_error – If a count is not positive or the box has no extent on an axis.
- Returns:
The structured map.
-
static std::shared_ptr<CellMap> spherical(const glm::vec3 ¢er, double inner_radius, double outer_radius, const glm::dvec2 &latitude_bounds_degrees, const glm::ivec3 &cells, const glm::vec3 &north_axis = glm::vec3(0.0f, 0.0f, 1.0f), const glm::vec3 &reference_direction = glm::vec3(1.0f, 0.0f, 0.0f), double start_longitude_degrees = 0.0, double longitude_sweep_degrees = 360.0, bool linear = false)#
Builds an analytic spherical-shell band map without a CAD dependency.
Logical U follows longitude, V follows latitude from south to north, and W follows radius from the inner to the outer boundary.
- Parameters:
center – Center shared by the spherical boundaries.
inner_radius – Positive inner radius.
outer_radius – Outer radius, greater than inner_radius.
latitude_bounds_degrees – Strictly increasing south/north bounds inside (-90, 90).
cells – Logical longitude, latitude, and radial cell counts.
north_axis – North direction and positive V orientation.
reference_direction – Direction projected onto the equator to define the U seam.
start_longitude_degrees – Longitude of logical U = 0 in degrees.
longitude_sweep_degrees – Positive longitude sweep no greater than 360 degrees.
linear – True for one trilinear element per cell, false for midpoint refinement.
- Returns:
The validated structured map.
Builds a new map with the same cells as
basebut a graded cell spacing.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 (world position from the unwarped base map, with the map’s logical and cell context set). The scale is therefore a natural-log exponent: 0 or a null attribute keeps the spacing uniform. With a locked axis the weights are normalized so both boundaries stay fixed; with an unlocked axis each element’s width is multiplied by its weight, so the far boundary moves (the base map is continued linearly past its end) and logical 0 stays. The requested coordinates are smoothed, and if the result fails validate() the warp is blended back toward the base map, halving its strength each time, until it is valid. The result keeps the base map’s cells, subdivisions, periodicity, active elements, and trim mode.
- Parameters:
base – The map to warp. It must not carry a boundary trim (see has_boundary_trim()).
u_scale – Log-scale exponent field for U element widths, or nullptr for 0.
v_scale – Log-scale exponent field for V element widths, or nullptr for 0.
w_scale – Log-scale exponent field for W element widths, or nullptr for 0.
lock_u_bounds – Keep both U boundaries fixed and only redistribute elements.
lock_v_bounds – Keep both V boundaries fixed and only redistribute elements.
lock_w_bounds – Keep both W boundaries fixed and only redistribute elements.
- Throws:
std::runtime_error – If base is null or has a boundary trim (TrimMode::boundary, the default for the surface factories), if a scale attribute returns a non-finite or non-scalar value, or if the warp still folds the map at 1e-4 of its strength.
- Returns:
The warped map.
Private Functions
-
void append_boundary_face(int i, int j, int k, int axis, int side)#
-
void build_boundary_mesh()#
-
int build_bvh(size_t begin, size_t end)#
-
size_t control_index(int i, int j, int k) const#
-
size_t count_non_neighbor_overlaps() const#
-
size_t element_index(int i, int j, int k) const#
-
bool element_is_active(const glm::ivec3 &element) const#
-
bool elements_are_neighbors(size_t first, size_t second) const#
-
void install_boundary_trim(BoundaryTrim &&trim)#
-
glm::vec3 interpolate(int i, int j, int k, const glm::vec3 &local) const#
-
glm::mat3 local_jacobian(int i, int j, int k, const glm::vec3 &local) const#
-
std::optional<CellMapLocation> locate_impl(const glm::vec3 &world, double tolerance, size_t max_iterations, bool apply_trim) const#
-
glm::ivec3 logical_to_element(const glm::vec3 &logical) const#
-
bool point_inside_element(size_t flat_index, const glm::vec3 &point, double tolerance) const#
-
double resolved_inverse_tolerance(double requested_tolerance) const#
-
bool trim_allows_logical(const glm::vec3 &logical) const#
-
double trim_field_value(double u_fraction, double v_fraction) const#
Private Members
-
std::vector<bool> m_active_elements#
-
std::vector<BoundaryBVHNode> m_boundary_bvh_nodes#
-
std::vector<size_t> m_boundary_indices#
-
std::vector<BoundaryTriangle> m_boundary_triangles#
-
std::vector<size_t> m_bvh_indices#
-
uint64_t m_cache_key = 0#
Identity of this map’s current geometry for the per-thread query caches.
A fresh value is drawn at construction and whenever the trim changes, so a cached answer can never be reused by another map or by an outdated state of this one.
-
glm::ivec3 m_cells#
-
std::vector<glm::vec3> m_control_points#
-
std::vector<BoundaryBVHNode> m_edge_bvh_nodes#
-
std::vector<size_t> m_edge_indices#
-
std::vector<BoundaryTriangle> m_edge_triangles#
-
glm::ivec3 m_element_counts#
-
glm::vec3 m_maximum#
-
glm::vec3 m_minimum#
-
std::array<bool, 3> m_periodic#
-
int m_subdivisions#
-
BoundaryTrim m_trim#
Private Static Functions
-
static int build_boundary_bvh(std::vector<BoundaryBVHNode> &nodes, const std::vector<BoundaryTriangle> &triangles, std::vector<size_t> &indices, size_t begin, size_t end)#
-
static BoundaryTrim build_boundary_trim(const glm::ivec3 &elements, const std::function<bool(double, double)> &contains, std::vector<bool> &active, const glm::dvec2 &feature_fraction = glm::dvec2(0.0))#
Shared surface extrusion: column_height(u, v, base) returns each column’s height.
-
static void query_boundary_bvh(const std::vector<BoundaryBVHNode> &nodes, const std::vector<BoundaryTriangle> &triangles, const std::vector<size_t> &indices, int node_index, const glm::vec3 &point, double &best_squared_distance)#
-
struct BoundaryBVHNode#
-
struct BoundaryTriangle#
-
struct BoundaryTrim#
Implicit true-boundary clip data in normalized UV fraction space.
signed_field holds a node-sampled signed distance to the chart boundary in fraction units (negative inside the chart); segments is the boundary polyline used to build the world-space trim wall.
-
struct Bounds#
-
struct BVHNode#
-
enum class TrimMode#
-
class CellMapCollection#
- #include <cell_map.h>
Immutable, non-empty collection of independently parameterized cell maps.
Each map keeps its own logical coordinates, for example one map per CAD face.
Public Functions
-
std::shared_ptr<CellMap> at(size_t index) const#
Returns one map.
- Parameters:
index – Zero-based index.
- Throws:
std::out_of_range – If index is out of range.
- Returns:
The map.
Builds a collection.
- Parameters:
maps – The maps, in order.
- Throws:
std::runtime_error – If maps is empty or contains a null map.
-
inline const std::vector<std::shared_ptr<CellMap>> &maps() const#
Returns the maps in collection order.
- Returns:
The maps.
-
inline size_t size() const#
Returns the number of maps.
- Returns:
The map count.
-
std::vector<CellMapDiagnostics> validate() const#
Validates every map.
- Returns:
One CellMapDiagnostics per map, in collection order.
-
std::shared_ptr<CellMap> at(size_t index) const#
-
struct CellMapDiagnostics#
- #include <cell_map.h>
Validation evidence for a structured curvilinear cell map.
Produced by CellMap::validate(). The Jacobian is sampled at the eight corners and the centre of every active structured element.
Public Functions
-
inline bool valid() const#
Reports whether every mandatory check passed.
- Returns:
True when at least one element is active, no element is inverted or overlapping, every inverse check succeeded, and the minimum Jacobian determinant is positive.
Public Members
-
size_t active_element_count = 0#
Number of active structured elements.
-
size_t inverse_solver_failures = 0#
Active elements whose world-space centre does not invert back to its logical centre within 1e-4.
-
size_t inverted_cell_count = 0#
Active elements with a non-positive or non-finite sampled determinant.
-
double maximum_aspect_ratio = 0.0#
Largest ratio of the longest to the shortest Jacobian column over all samples.
-
double maximum_jacobian_determinant = -std::numeric_limits<double>::infinity()#
Largest sampled Jacobian determinant (0 when no element is active).
-
double minimum_jacobian_determinant = std::numeric_limits<double>::infinity()#
Smallest sampled Jacobian determinant (0 when no element is active).
-
size_t non_neighbor_overlap_count = 0#
Pairs of non-adjacent elements that overlap in world space.
Only counted when no element is inverted.
-
size_t trimmed_element_count = 0#
Number of inactive (trimmed) structured elements.
-
inline bool valid() const#
-
struct CellMapLocation#
- #include <cell_map.h>
Authoritative result of locating a world point in a CellMap.
Functions
-
glm::dvec3 sample_vec3(Vec3Attribute &field, const glm::dvec3 &point, double d = 0.0)#
Samples a Vec3Attribute at a point as double precision.
- Parameters:
field – The vector field.
point – The sample point.
d – The signed distance passed to the attribute.
- Throws:
std::runtime_error – if the attribute does not return a vec3.
- Returns:
The sampled vector.
-
class FieldWarpMap : public WarpMap#
- #include <warp_map.h>
A warp given by a vector field: g(p) is the field’s value at p.
The field is any Vec3Attribute (three expressions, numba callbacks, a vector volume, …), sampled with d = 0. It has no closed-form Jacobian or bounds, so a Warp built from it takes central differences and needs explicit bounds. Vec3Attribute returns single precision, so the finite-difference step should stay well above 1e-6 of the coordinate size; Warp picks it from the voxel size.
Public Functions
-
virtual std::shared_ptr<WarpMap> clone() const override#
Returns a copy for another thread; fields are deep-cloned, immutable data is shared.
- Returns:
The copy.
-
inline const std::shared_ptr<Vec3Attribute> &field() const#
Returns the vector field.
- Returns:
The field given to the constructor.
Constructor.
- Parameters:
field – The vector field giving the child point of each world point.
- Throws:
std::runtime_error – if field is null.
-
inline virtual std::string name() const override#
Name shown in tree diagrams and node labels, such as “Warp” or “Twist”.
- Returns:
The map’s display name.
-
virtual std::vector<std::pair<std::string, std::string>> properties() const override#
Authored parameters as (name, value) text pairs for Node::properties().
- Returns:
The parameter pairs; empty by default.
-
virtual glm::dvec3 to_child(const glm::dvec3 &world) const override#
Returns g(p), the child point a world point pulls back to.
- Parameters:
world – The world point.
- Returns:
The child point.
Private Members
-
std::shared_ptr<Vec3Attribute> m_field#
-
virtual std::shared_ptr<WarpMap> clone() const override#
-
class WarpMap : public CoordinateSource#
- #include <warp_map.h>
A deformation of space, described by where each world point pulls back to in its child.
A Warp node samples its child at g(p), the child point that world point p pulls back to. WarpMap is that g. Subclasses implement to_child(); the Warp node does the rest (distance correction, attributes, bounding box, cloning). See deforming_space_architecture.md.
The Jacobian J = dg/dp drives the distance correction. The default jacobian() takes central differences of to_child(); maps with a closed form override it, which is faster and free of finite-difference noise.
Coordinates: every map is a CoordinateSource with “child_x”, “child_y” and “child_z” (where a point pulls back to), followed by the map’s own natural coordinates, named in the constructor, so material and other geometry can be graded along them.
Thread safety: to_child() may sample fields that keep per-call state, so each evaluation thread uses its own clone(). Immutable data (tables, frames) is shared between clones.
Subclassed by BendMap, DisplacementMap, FieldWarpMap, SphereWrapMap, TaperMap, TwistMap
Public Types
-
typedef std::pair<glm::dvec3, glm::dvec3> Box#
An axis-aligned box as (minimum, maximum).
Public Functions
-
virtual std::shared_ptr<WarpMap> clone() const = 0#
Returns a copy for another thread; fields are deep-cloned, immutable data is shared.
- Returns:
The copy.
-
inline virtual std::shared_ptr<CoordinateSource> clone_source() const final#
Returns a copy for another thread (same as clone()).
- Returns:
The copy.
-
virtual double coordinate(size_t index, const glm::dvec3 &point) const final#
Evaluates coordinate
indexat a point.Indices 0-2 are the components of to_child(point); higher indices go to extra_coordinate().
- Parameters:
index – The coordinate index into coordinate_names().
point – The world point.
- Returns:
The coordinate value.
-
virtual const std::vector<std::string> &coordinate_names() const final#
Returns the coordinate names: “child_x”, “child_y”, “child_z”, then the map’s own names.
- Returns:
The names, in index order.
-
inline virtual size_t failed_inversions() const#
Number of points whose pull-back failed to converge (0 for closed-form maps).
- Returns:
The failed-inversion count.
-
virtual glm::dmat3 jacobian(const glm::dvec3 &world, double step) const#
Returns the Jacobian dg/dp at a world point (column j is dg/dp_j).
The default takes central differences of to_child().
- Parameters:
world – The world point.
step – The finite-difference step in world units; maps with a closed form ignore it.
- Returns:
The 3x3 Jacobian matrix.
-
virtual std::string name() const = 0#
Name shown in tree diagrams and node labels, such as “Warp” or “Twist”.
- Returns:
The map’s display name.
-
virtual void prepare(Node &child, const Box &world_box, double voxel, double bandwidth)#
Checks the map against the prepared child before evaluation.
Called from Warp::prepare() after the child is prepared. The default does nothing; a displacement uses it to detect folds.
-
virtual std::vector<std::pair<std::string, std::string>> properties() const#
Authored parameters as (name, value) text pairs for Node::properties().
- Returns:
The parameter pairs; empty by default.
-
virtual glm::dvec3 to_child(const glm::dvec3 &world) const = 0#
Returns g(p), the child point a world point pulls back to.
- Parameters:
world – The world point.
- Returns:
The child point.
-
virtual std::optional<Box> world_bounds(const Box &child_box) const#
Returns a world box holding the warped image of a child box.
Maps that can bound their image analytically override this. The default returns std::nullopt, and the Warp node then needs explicit bounds.
- Parameters:
child_box – The child’s bounding box.
- Returns:
The world box, or std::nullopt when the map cannot bound its image.
Protected Functions
-
virtual double extra_coordinate(size_t index, const glm::dvec3 &world) const#
Evaluates one of the map’s own coordinates.
- Parameters:
index – Index into the extra names given to the constructor.
world – The world point.
- Throws:
std::runtime_error – by default, since the base map has no extra coordinates.
- Returns:
The coordinate value.
-
explicit WarpMap(const std::vector<std::string> &extra_names = {})#
Constructor.
- Parameters:
extra_names – The map’s own coordinate names, listed after child_x, child_y and child_z.
Private Members
-
std::vector<std::string> m_coordinate_names#
-
typedef std::pair<glm::dvec3, glm::dvec3> Box#
Functions
-
glm::dvec3 unit_vector(const glm::dvec3 &vector, const std::string &name)#
Returns a unit vector, or throws if the vector is zero or not finite.
- Parameters:
vector – The vector.
name – The parameter name used in the error message.
- Throws:
std::runtime_error – if the vector is zero or not finite.
- Returns:
The normalized vector.
-
class AxisLaw#
- #include <deformation_maps.h>
The running integral of a rate along an axis: L(h) = integral from 0 to h of rate.
Twist and taper are rates per unit length along an axis. A constant rate gives L(h) = rate * h. A field rate is read along the axis, at origin + h * axis with d = 0, and integrated once (trapezoids on a fine table) over the range it is built for; beyond the table the end rates continue. The law is immutable after construction, so clones of a map share it.
Public Functions
-
AxisLaw(const ScalarParameter &rate, const glm::dvec3 &origin, const glm::dvec3 &axis, double minimum, double maximum)#
Constructor.
- Parameters:
rate – The rate per unit length; a constant or a field.
origin – The point on the axis where h = 0.
axis – The unit axis direction.
minimum – The lowest h the law must cover.
maximum – The highest h the law must cover.
- Throws:
std::runtime_error – if the range is not finite or a field returns a non-finite value.
-
double integral(double h) const#
The integral of the rate from 0 to h.
Beyond the table the end rates continue linearly.
- Parameters:
h – The axial position.
- Returns:
The integral.
-
std::pair<double, double> integral_range(double minimum, double maximum) const#
The smallest and largest integral over [minimum, maximum].
- Parameters:
minimum – The lower end of the range.
maximum – The upper end of the range.
- Returns:
(smallest, largest) integral; interior table points are checked for a field rate.
-
inline const ScalarParameter ¶meter() const#
Returns the rate parameter.
- Returns:
The rate given to the constructor.
-
double rate(double h) const#
The rate at h.
- Parameters:
h – The axial position.
- Returns:
The rate, linearly interpolated from the table for a field rate.
Private Functions
-
std::pair<size_t, double> locate(double h) const#
The table position of h: interval index and fraction within it.
-
AxisLaw(const ScalarParameter &rate, const glm::dvec3 &origin, const glm::dvec3 &axis, double minimum, double maximum)#
-
class BendMap : public WarpMap#
- #include <deformation_maps.h>
Bends space around an axis: straight lines along a direction become circles of a given radius.
The bend happens in a frame (centre line point c, unit vectors e_x, e_y, e_z): a world point is c + rho (sin(theta) e_x - cos(theta) e_z) + y e_y, with rho its distance from the centre line (through c along e_y) and theta its angle. It pulls back to the child point child_origin + (R theta) cx + y cy + (R - rho) cz: arc length at radius R becomes length along cx, and distance inside radius R becomes distance along cz. Lengths on the circle of radius R (the neutral surface) are kept. theta runs over [angle_start, angle_start + 2 pi).
Warp::bend() places the child frame on the bend frame, so the child stays put where theta = 0. Warp::wrap_cylinder() uses a fixed flat-design frame instead.
Coordinates: “angle” (theta, in degrees) and “radius” (rho).
World bounds: exact for the annular sector holding the child’s box.
Public Functions
-
BendMap(double radius, const Frame &bend, const Frame &child, double angle_start, const std::string &name)#
Constructor.
- Parameters:
radius – The bend radius R, positive.
bend – The bend frame: origin is a point c on the centre line, y the centre line direction.
child – The child frame the pulled-back point is expressed in.
angle_start – The lowest angle theta, in radians.
name – The name shown in diagrams.
- Throws:
std::runtime_error – if the radius is not positive and finite.
-
virtual std::shared_ptr<WarpMap> clone() const override#
Returns a copy for another thread; fields are deep-cloned, immutable data is shared.
- Returns:
The copy.
-
virtual glm::dmat3 jacobian(const glm::dvec3 &world, double step) const override#
Returns the Jacobian dg/dp at a world point (column j is dg/dp_j).
The default takes central differences of to_child().
- Parameters:
world – The world point.
step – The finite-difference step in world units; maps with a closed form ignore it.
- Returns:
The 3x3 Jacobian matrix.
-
inline virtual std::string name() const override#
Name shown in tree diagrams and node labels, such as “Warp” or “Twist”.
- Returns:
The map’s display name.
-
virtual std::vector<std::pair<std::string, std::string>> properties() const override#
Authored parameters as (name, value) text pairs for Node::properties().
- Returns:
The parameter pairs; empty by default.
-
inline double radius() const#
Returns the bend radius.
- Returns:
The bend radius R.
-
virtual glm::dvec3 to_child(const glm::dvec3 &world) const override#
Returns g(p), the child point a world point pulls back to.
- Parameters:
world – The world point.
- Returns:
The child point.
-
virtual std::optional<Box> world_bounds(const Box &child_box) const override#
Returns a world box holding the warped image of a child box.
Maps that can bound their image analytically override this. The default returns std::nullopt, and the Warp node then needs explicit bounds.
- Parameters:
child_box – The child’s bounding box.
- Returns:
The world box, or std::nullopt when the map cannot bound its image.
Protected Functions
-
virtual double extra_coordinate(size_t index, const glm::dvec3 &world) const override#
Evaluates one of the map’s own coordinates: “angle” (index 0, degrees) or “radius” (index 1).
- Parameters:
index – Index into the map’s own coordinate names.
world – The world point.
- Returns:
The coordinate value.
Private Functions
-
glm::dvec3 polar(const glm::dvec3 &world) const#
Polar coordinates of a world point in the bend frame: angle, radius and height.
-
struct Frame#
- #include <deformation_maps.h>
An orthonormal frame: origin and three unit axes.
-
BendMap(double radius, const Frame &bend, const Frame &child, double angle_start, const std::string &name)#
-
class SphereWrapMap : public WarpMap#
- #include <deformation_maps.h>
Wraps a flat design onto a sphere: child x and y are arc lengths of longitude and latitude.
A world point at distance r from the centre, longitude lon (counter-clockwise about the north axis from the reference direction, in [0, 2 pi)) and latitude lat (from the equator, in [-pi/2, pi/2]) pulls back to the child point (R lon, R lat, r - R). The design’s z = 0 plane lies on the sphere of radius R and z grows outward. This is the equirectangular wrap: lengths along the equator and along meridians are kept, while parallels shrink by cos(lat), so a design is squeezed narrower toward the poles. Keep it away from them (|y| < R pi / 2), where the longitude is undefined. The Jacobian is analytic.
Coordinates: “longitude” and “latitude” (degrees) and “radius” (r).
World bounds: the sphere holding the child’s outermost layer.
Public Functions
-
virtual std::shared_ptr<WarpMap> clone() const override#
Returns a copy for another thread; fields are deep-cloned, immutable data is shared.
- Returns:
The copy.
-
virtual glm::dmat3 jacobian(const glm::dvec3 &world, double step) const override#
Returns the Jacobian dg/dp at a world point (column j is dg/dp_j).
The default takes central differences of to_child().
- Parameters:
world – The world point.
step – The finite-difference step in world units; maps with a closed form ignore it.
- Returns:
The 3x3 Jacobian matrix.
-
inline virtual std::string name() const override#
Name shown in tree diagrams and node labels, such as “Warp” or “Twist”.
- Returns:
The map’s display name.
-
virtual std::vector<std::pair<std::string, std::string>> properties() const override#
Authored parameters as (name, value) text pairs for Node::properties().
- Returns:
The parameter pairs; empty by default.
-
SphereWrapMap(double radius, const glm::dvec3 ¢er, const glm::dvec3 &north_axis, const glm::dvec3 &reference_direction)#
Constructor.
- Parameters:
radius – The sphere radius R, positive.
center – The sphere centre.
north_axis – The north direction; normalized internally.
reference_direction – The direction of longitude 0; projected onto the equator.
- Throws:
std::runtime_error – if the radius is not positive, a direction is zero, or the reference direction is parallel to the north axis.
-
virtual glm::dvec3 to_child(const glm::dvec3 &world) const override#
Returns g(p), the child point a world point pulls back to.
- Parameters:
world – The world point.
- Returns:
The child point.
-
virtual std::optional<Box> world_bounds(const Box &child_box) const override#
Returns a world box holding the warped image of a child box.
Maps that can bound their image analytically override this. The default returns std::nullopt, and the Warp node then needs explicit bounds.
- Parameters:
child_box – The child’s bounding box.
- Returns:
The world box, or std::nullopt when the map cannot bound its image.
Protected Functions
-
virtual double extra_coordinate(size_t index, const glm::dvec3 &world) const override#
Evaluates one of the map’s own coordinates: “longitude” (index 0, degrees), “latitude” (index 1, degrees) or “radius” (index 2).
- Parameters:
index – Index into the map’s own coordinate names.
world – The world point.
- Returns:
The coordinate value.
Private Functions
-
glm::dvec3 spherical(const glm::dvec3 &world) const#
Longitude, latitude (radians) and radius of a world point.
-
virtual std::shared_ptr<WarpMap> clone() const override#
-
class TaperMap : public WarpMap#
- #include <deformation_maps.h>
Scales the section perpendicular to an axis by a factor that changes along the axis.
The scale at height h = (p - origin) . axis is s(h) = 1 + integral from 0 to h of rate, so a constant rate is a linear taper and s is 1 at the origin. g(p) keeps the height and divides the offset from the axis by s(h). s must stay positive over the child’s axial extent. The Jacobian is analytic.
Coordinates: “scale” (s) and “height” (h).
World bounds: the child’s box corners scaled about the axis by the smallest and largest s.
Public Functions
-
virtual std::shared_ptr<WarpMap> clone() const override#
Returns a copy for another thread; fields are deep-cloned, immutable data is shared.
- Returns:
The copy.
-
virtual glm::dmat3 jacobian(const glm::dvec3 &world, double step) const override#
Returns the Jacobian dg/dp at a world point (column j is dg/dp_j).
The default takes central differences of to_child().
- Parameters:
world – The world point.
step – The finite-difference step in world units; maps with a closed form ignore it.
- Returns:
The 3x3 Jacobian matrix.
-
inline virtual std::string name() const override#
Name shown in tree diagrams and node labels, such as “Warp” or “Twist”.
- Returns:
The map’s display name.
-
virtual std::vector<std::pair<std::string, std::string>> properties() const override#
Authored parameters as (name, value) text pairs for Node::properties().
- Returns:
The parameter pairs; empty by default.
-
TaperMap(const ScalarParameter &rate, const glm::dvec3 &axis, const glm::dvec3 &origin, const Box &child_box)#
Constructor.
- Parameters:
rate – The relative scale change per unit length; a constant or a field read along the axis.
axis – The taper axis direction; normalized internally.
origin – A point on the axis where the scale is 1.
child_box – The child’s box; s is integrated and checked over its axial extent.
- Throws:
std::runtime_error – if the axis is zero or not finite, or s reaches zero over the child.
-
virtual glm::dvec3 to_child(const glm::dvec3 &world) const override#
Returns g(p), the child point a world point pulls back to.
- Parameters:
world – The world point.
- Returns:
The child point.
-
virtual std::optional<Box> world_bounds(const Box &child_box) const override#
Returns a world box holding the warped image of a child box.
Maps that can bound their image analytically override this. The default returns std::nullopt, and the Warp node then needs explicit bounds.
- Parameters:
child_box – The child’s bounding box.
- Returns:
The world box, or std::nullopt when the map cannot bound its image.
Protected Functions
-
virtual double extra_coordinate(size_t index, const glm::dvec3 &world) const override#
Evaluates one of the map’s own coordinates: “scale” (index 0) or “height” (index 1).
- Parameters:
index – Index into the map’s own coordinate names.
world – The world point.
- Returns:
The coordinate value.
-
virtual std::shared_ptr<WarpMap> clone() const override#
-
class TwistMap : public WarpMap#
- #include <deformation_maps.h>
Twists space about an axis: the section at height h turns by the integral of the rate.
The angle at height h = (p - origin) . axis is theta(h) = integral from 0 to h of rate, in degrees, counter-clockwise about the axis; it is zero at the origin. g(p) turns p back by -theta(h) about the axis. The Jacobian is analytic: R(-theta) - theta’(h) (a x q) a^T, where q is the turned-back offset from the axis point.
Coordinates: “angle” (theta, in degrees) and “height” (h).
World bounds: the cylinder about the axis holding the child’s box over its axial extent.
Public Functions
-
virtual std::shared_ptr<WarpMap> clone() const override#
Returns a copy for another thread; fields are deep-cloned, immutable data is shared.
- Returns:
The copy.
-
virtual glm::dmat3 jacobian(const glm::dvec3 &world, double step) const override#
Returns the Jacobian dg/dp at a world point (column j is dg/dp_j).
The default takes central differences of to_child().
- Parameters:
world – The world point.
step – The finite-difference step in world units; maps with a closed form ignore it.
- Returns:
The 3x3 Jacobian matrix.
-
inline virtual std::string name() const override#
Name shown in tree diagrams and node labels, such as “Warp” or “Twist”.
- Returns:
The map’s display name.
-
virtual std::vector<std::pair<std::string, std::string>> properties() const override#
Authored parameters as (name, value) text pairs for Node::properties().
- Returns:
The parameter pairs; empty by default.
-
virtual glm::dvec3 to_child(const glm::dvec3 &world) const override#
Returns g(p), the child point a world point pulls back to.
- Parameters:
world – The world point.
- Returns:
The child point.
-
TwistMap(const ScalarParameter &rate, const glm::dvec3 &axis, const glm::dvec3 &origin, const Box &child_box)#
Constructor.
- Parameters:
rate – The twist rate in degrees per unit length; a constant or a field read along the axis.
axis – The twist axis direction; normalized internally.
origin – A point on the axis where the twist is zero.
child_box – The child’s box; a field rate is integrated over its axial extent.
- Throws:
std::runtime_error – if the axis is zero or not finite.
-
virtual std::optional<Box> world_bounds(const Box &child_box) const override#
Returns a world box holding the warped image of a child box.
Maps that can bound their image analytically override this. The default returns std::nullopt, and the Warp node then needs explicit bounds.
- Parameters:
child_box – The child’s bounding box.
- Returns:
The world box, or std::nullopt when the map cannot bound its image.
Protected Functions
-
virtual double extra_coordinate(size_t index, const glm::dvec3 &world) const override#
Evaluates one of the map’s own coordinates: “angle” (index 0, degrees) or “height” (index 1).
- Parameters:
index – Index into the map’s own coordinate names.
world – The world point.
- Returns:
The coordinate value.
-
virtual std::shared_ptr<WarpMap> clone() const override#
-
class DisplacementMap : public WarpMap#
- #include <displacement_map.h>
Moves material by a displacement field: material at X moves to X + u(X).
Frame: u is sampled at the undeformed point X, in the child’s coordinates, and is a vector in those same coordinates (which are the Warp’s own: world, when the Warp is the root). This is the convention of simulation results, whose displacements live on the undeformed part. u is sampled with d = 0.
Pull-back: g(p) is the X with X + u(X) = p. It is found by fixed-point iteration X <- p - u(X), starting from p - u(p), which converges while u changes by less than the distance it is sampled over (|grad u| < 1). If the iteration stalls, Newton steps with a finite-difference grad u take over, which converge wherever the deformation is invertible. Points that still do not converge use the best estimate and are counted (failed_inversions(), shared by all clones).
prepare() checks det(I + grad u) on a grid in and near the material and throws if the displacement folds material onto itself, since no pull-back exists there.
Jacobian: dg/dp = (I + grad u(X))^-1, with grad u by central differences at X.
World bounds: the child’s box widened by the largest displacement sampled over it on each axis, plus a quarter of it as margin.
Coordinates: “displacement” (|u(X)|, how far the material at a point moved).
Public Functions
-
virtual std::shared_ptr<WarpMap> clone() const override#
Returns a copy for another thread; fields are deep-cloned, immutable data is shared.
- Returns:
The copy.
-
inline const std::shared_ptr<Vec3Attribute> &displacement() const#
Returns the displacement field.
- Returns:
The field u given to the constructor.
Constructor.
- Parameters:
displacement – The displacement field u.
source – How u was given, for display: empty for a field, or the name of the child’s attribute.
- Throws:
std::runtime_error – if displacement is null.
-
inline virtual size_t failed_inversions() const override#
Number of points whose pull-back failed to converge (0 for closed-form maps).
- Returns:
The failed-inversion count.
-
virtual glm::dmat3 jacobian(const glm::dvec3 &world, double step) const override#
Returns the Jacobian dg/dp at a world point (column j is dg/dp_j).
The default takes central differences of to_child().
- Parameters:
world – The world point.
step – The finite-difference step in world units; maps with a closed form ignore it.
- Returns:
The 3x3 Jacobian matrix.
-
inline virtual std::string name() const override#
Name shown in tree diagrams and node labels, such as “Warp” or “Twist”.
- Returns:
The map’s display name.
-
virtual void prepare(Node &child, const Box &world_box, double voxel, double bandwidth) override#
Checks the map against the prepared child before evaluation.
Called from Warp::prepare() after the child is prepared. The default does nothing; a displacement uses it to detect folds.
-
virtual std::vector<std::pair<std::string, std::string>> properties() const override#
Authored parameters as (name, value) text pairs for Node::properties().
- Returns:
The parameter pairs; empty by default.
-
virtual glm::dvec3 to_child(const glm::dvec3 &world) const override#
Returns g(p), the child point a world point pulls back to.
- Parameters:
world – The world point.
- Returns:
The child point.
-
virtual std::optional<Box> world_bounds(const Box &child_box) const override#
Returns a world box holding the warped image of a child box.
Maps that can bound their image analytically override this. The default returns std::nullopt, and the Warp node then needs explicit bounds.
- Parameters:
child_box – The child’s bounding box.
- Returns:
The world box, or std::nullopt when the map cannot bound its image.
Protected Functions
-
virtual double extra_coordinate(size_t index, const glm::dvec3 &world) const override#
Evaluates the map’s own coordinate “displacement”: |u(X)| at the pulled-back point X.
- Parameters:
index – Index into the map’s own coordinate names (only 0).
world – The world point.
- Returns:
The displacement magnitude.
Private Functions
-
glm::dvec3 displacement_at(const glm::dvec3 &point) const#
u at a point, in double precision.
-
glm::dmat3 displacement_gradient(const glm::dvec3 &point) const#
grad u at a point by central differences (column j is du/dx_j).
-
glm::dvec3 solve(const glm::dvec3 &world) const#
Solves X + u(X) = p for X.
Private Members
-
std::shared_ptr<Vec3Attribute> m_displacement#
-
std::shared_ptr<std::atomic<size_t>> m_failures#
-
mutable std::optional<std::pair<glm::dvec3, glm::dvec3>> m_last#
The last pull-back, so jacobian() at the point just pulled back does not solve again.
Each thread has its own clone, so the cache is never shared.
-
std::string m_source#
-
double m_step = 1e-3#
Finite-difference step for grad u.
-
double m_tolerance = 1e-5#
Residual |X + u(X) - p| accepted as converged.
-
virtual std::shared_ptr<WarpMap> clone() const override#
-
class FaceUnitCell#
- #include <unit_cell.h>
A normalized indexed face cell with optional integer tags.
Static face cells tile vertices in [0, 1]. Native subclasses may emit parameterized logical patches that cross an individual cell boundary.
Subclassed by PlateUnitCell
Public Functions
-
virtual std::shared_ptr<FaceUnitCell> clone() const#
Copy the cell.
- Returns:
The copy, with the same dynamic type.
-
inline virtual size_t component_count() const#
Return the number of stable source face components emitted per unit cell.
- Returns:
The face count for static cells.
-
virtual std::vector<FaceUnitCellPatch> emit_faces(const glm::ivec3 &cell_index, const CellMap &cell_map) const#
Emit logical face patches for one tiled cell.
- Parameters:
cell_index – Integer logical cell index.
cell_map – Map supplying cell counts and field context.
- Returns:
Triangular or quadrilateral patches in logical map coordinates.
-
inline virtual bool extends_map_domain() const#
Whether emitted faces may continue beyond the finite map domain.
The default preserves CellMap clipping. Native cells with a deliberate overhanging footprint may opt into extended reference mapping and bounds.
- Returns:
False for static cells.
-
inline const std::vector<int> &face_tags() const#
Per-face tags.
- Returns:
The tags, or an empty list.
-
inline const std::vector<std::vector<size_t>> &faces() const#
Faces as lists of three or four vertex indices.
- Returns:
The faces.
-
FaceUnitCell(const std::vector<glm::vec3> &vertices, const std::vector<std::vector<size_t>> &faces, const std::vector<int> &vertex_tags = {}, const std::vector<int> &face_tags = {}, const std::vector<int> &orientation_tags = {}, const std::vector<int> &material_tags = {})#
Construct a reusable indexed static face cell.
Throws std::runtime_error when vertices or faces are empty, a vertex is not finite or lies outside [0, 1], a face does not have three or four distinct valid indices or has zero area, a non-empty tag list has the wrong length, or a material tag is outside [-1, 255].
- Parameters:
vertices – Finite normalized vertices in [0, 1].
faces – Indexed triangles or quadrilaterals.
vertex_tags – Optional per-vertex provenance tags.
face_tags – Optional per-face provenance tags.
orientation_tags – Optional per-face orientation tags.
material_tags – Optional per-face material IDs in [0, 255], or -1 for none.
-
inline const std::vector<int> &material_tags() const#
Per-face material IDs.
- Returns:
The IDs, or an empty list.
-
inline const std::vector<int> &orientation_tags() const#
Per-face orientation tags.
- Returns:
The tags, or an empty list.
-
inline virtual glm::ivec3 period() const#
Return the cell’s positive tiling period on U/V/W axes.
- Returns:
Period in cells; (1, 1, 1) for static cells.
-
inline const std::vector<int> &vertex_tags() const#
Per-vertex tags.
- Returns:
The tags, or an empty list.
-
inline const std::vector<glm::vec3> &vertices() const#
Normalized vertices.
Empty for native subclasses that emit faces directly.
- Returns:
The vertices.
-
virtual ~FaceUnitCell() = default#
Protected Functions
-
FaceUnitCell() = default#
Construct an empty cell for native subclasses that override emit_faces().
Protected Attributes
-
std::vector<int> m_face_tags#
Per-face tags.
-
std::vector<std::vector<size_t>> m_faces#
Indexed faces.
-
std::vector<int> m_material_tags#
Per-face material IDs.
-
std::vector<int> m_orientation_tags#
Per-face orientation tags.
-
std::vector<int> m_vertex_tags#
Per-vertex tags.
-
std::vector<glm::vec3> m_vertices#
Normalized vertices.
-
virtual std::shared_ptr<FaceUnitCell> clone() const#
-
struct FaceUnitCellPatch#
- #include <unit_cell.h>
One triangle or quadrilateral emitted in logical CellMap coordinates.
Public Members
-
int face_tag = -1#
Face tag, or -1 when the cell has none.
-
int material_tag = -1#
Material ID, or -1 when the cell has none.
-
int orientation_tag = -1#
Orientation tag, or -1 when the cell has none.
-
int unit_cell_face_id = -1#
Index of the source face within the unit cell.
-
std::vector<int> vertex_tags#
Per-vertex tags, or -1 where the cell has none.
-
std::vector<glm::vec3> vertices#
Three or four vertices in logical map coordinates.
-
int face_tag = -1#
-
class GraphUnitCell#
- #include <unit_cell.h>
A normalized graph cell with indexed edges and optional integer tags.
Public Functions
-
std::shared_ptr<GraphUnitCell> clone() const#
Copy the cell.
- Returns:
The copy.
-
inline const std::vector<int> &edge_tags() const#
Per-edge tags.
- Returns:
The tags, or an empty list.
-
inline const std::vector<std::pair<size_t, size_t>> &edges() const#
Edges as vertex index pairs.
- Returns:
The edges.
-
GraphUnitCell(const std::vector<glm::vec3> &vertices, const std::vector<std::pair<size_t, size_t>> &edges, const std::vector<int> &vertex_tags = {}, const std::vector<int> &edge_tags = {}, const std::vector<int> &orientation_tags = {}, const std::vector<int> &material_tags = {})#
Construct a graph cell.
Throws std::runtime_error when vertices or edges are empty, a vertex lies outside [0, 1], an edge index is invalid or repeats a vertex, a non-empty tag list has the wrong length, or a material tag is outside [-1, 255].
- Parameters:
vertices – Normalized vertices in [0, 1].
edges – Vertex index pairs.
vertex_tags – Optional per-vertex tags.
edge_tags – Optional per-edge tags.
orientation_tags – Optional per-edge orientation tags.
material_tags – Optional per-edge material IDs in [0, 255], or -1 for none.
-
inline const std::vector<int> &material_tags() const#
Per-edge material IDs.
- Returns:
The IDs, or an empty list.
-
inline const std::vector<int> &orientation_tags() const#
Per-edge orientation tags.
- Returns:
The tags, or an empty list.
-
inline const std::vector<int> &vertex_tags() const#
Per-vertex tags.
- Returns:
The tags, or an empty list.
-
inline const std::vector<glm::vec3> &vertices() const#
Normalized vertices.
- Returns:
The vertices.
-
std::shared_ptr<GraphUnitCell> clone() const#
-
class ImplicitUnitCell#
- #include <unit_cell.h>
A periodic scalar unit cell evaluated in normalized cell coordinates.
Public Types
-
typedef std::function<glm::vec3(double, double, double)> GradientFunction#
Gradient callback taking normalized cell coordinates (u, v, w).
-
typedef std::function<double(double, double, double)> ValueFunction#
Scalar field callback taking normalized cell coordinates (u, v, w).
Public Functions
-
std::shared_ptr<ImplicitUnitCell> clone() const#
Deep copy.
A mixed cell also clones its source cells and weight field.
- Returns:
The copy.
-
double evaluate(const glm::vec3 &logical) const#
Evaluate the field with a default context.
The context’s logical and position values are both set to
logical.- Parameters:
logical – Logical cell coordinates.
- Returns:
Field value.
-
double evaluate(const glm::vec3 &logical, const AttributeSampleContext &context) const#
Evaluate the field.
A mixed cell samples its weight field with this context, clamps the weight to [0, 1], and interpolates the two source fields. Other cells ignore the context.
- Parameters:
logical – Logical cell coordinates.
context – Sample context passed to the weight field of a mixed cell.
- Returns:
Field value.
-
glm::vec3 gradient(const glm::vec3 &logical) const#
Field gradient with a default context.
- Parameters:
logical – Logical cell coordinates.
- Returns:
Gradient with respect to logical coordinates.
-
glm::vec3 gradient(const glm::vec3 &logical, const AttributeSampleContext &context) const#
Field gradient.
Uses the analytic gradient when one was given, otherwise central finite differences with a 1e-5 step.
- Parameters:
logical – Logical cell coordinates.
context – Sample context passed to the weight field of a mixed cell.
- Returns:
Gradient with respect to logical coordinates.
-
ImplicitUnitCell(const ValueFunction &value, const std::optional<GradientFunction> &gradient = std::nullopt, const std::string &name = "custom")#
Construct a cell from a scalar callback.
The callback should be periodic with period one on every axis. Periodicity is not checked here; call validate_periodicity().
- Parameters:
value – Scalar field callback. Throws std::runtime_error when empty.
gradient – Optional analytic gradient. When omitted, central finite differences with a 1e-5 step are used.
name – Display name of the cell.
-
inline const std::string &name() const#
Display name of the cell.
- Returns:
The name.
-
bool validate_periodicity(double tolerance = 1e-6) const#
Check that the field matches on opposite cell faces.
Compares the field on a 5x5 grid of each pair of opposite faces. Mixed cells always pass.
- Parameters:
tolerance – Largest allowed absolute difference.
- Returns:
True when every sample pair agrees within the tolerance.
-
std::pair<double, glm::vec3> value_and_gradient(const glm::vec3 &logical) const#
Field value and gradient with a default context.
- Parameters:
logical – Logical cell coordinates.
- Returns:
Pair of (value, gradient).
-
std::pair<double, glm::vec3> value_and_gradient(const glm::vec3 &logical, const AttributeSampleContext &context) const#
Field value and gradient in one call.
- Parameters:
logical – Logical cell coordinates.
context – Sample context passed to the weight field of a mixed cell.
- Returns:
Pair of (value, gradient).
Public Static Functions
Construct an aperiodic field-level mix of two periodic implicit cells.
Both source cells are validated for periodicity before their raw fields are interpolated. The cell-space weight may vary over the full logical map.
- Parameters:
first – Cell returned when the weight is zero.
second – Cell returned when the weight is one.
weight – Cell-space scalar weight field.
- Returns:
A composite implicit unit cell using finite-difference gradients.
-
static std::shared_ptr<ImplicitUnitCell> standard(const std::string &name)#
Construct a built-in TPMS cell with an analytic gradient.
- Parameters:
name – One of “gyroid”, “schwarz_p”, “schwarz_d”, “neovius”, “iwp”, “lidinoid”, “fischer_koch_s”, “frd” or “split_p”. Hyphens are accepted in place of underscores.
- Returns:
The requested cell. Throws std::runtime_error for an unknown name.
Private Members
-
std::shared_ptr<ImplicitUnitCell> m_first#
-
std::optional<GradientFunction> m_gradient#
-
std::string m_name#
-
bool m_periodicity_exempt = false#
-
std::shared_ptr<ImplicitUnitCell> m_second#
-
bool m_standard_gyroid = false#
-
ValueFunction m_value#
-
std::shared_ptr<FloatAttribute> m_weight#
-
typedef std::function<glm::vec3(double, double, double)> GradientFunction#
-
class PlateUnitCell : public FaceUnitCell#
- #include <unit_cell.h>
The period-two folded plate cell used by mapped plate lattices.
Eccentricity is sampled at undeformed cell centers and converted with the legacy relation (1-e)/(2(1+e)). Eccentricity must remain positive.
Public Functions
-
virtual std::shared_ptr<FaceUnitCell> clone() const override#
Copy the cell.
- Returns:
The copy, with the same dynamic type.
-
inline virtual size_t component_count() const override#
Each cell emits four quadrilateral plates.
- Returns:
4.
-
inline const std::shared_ptr<FloatAttribute> &eccentricity() const#
The eccentricity field.
- Returns:
The field passed to the constructor.
-
virtual std::vector<FaceUnitCellPatch> emit_faces(const glm::ivec3 &cell_index, const CellMap &cell_map) const override#
Emit logical face patches for one tiled cell.
- Parameters:
cell_index – Integer logical cell index.
cell_map – Map supplying cell counts and field context.
- Returns:
Triangular or quadrilateral patches in logical map coordinates.
-
inline virtual bool extends_map_domain() const override#
Folded plates overhang the cell, so they extend the map domain.
- Returns:
True.
-
inline virtual glm::ivec3 period() const override#
The folded plate pattern repeats every two cells on each axis.
- Returns:
(2, 2, 2).
Construct a folded plate cell from a legacy eccentricity field.
- Parameters:
eccentricity – Positive finite field; 1.0 is the flat state.
Private Functions
Private Members
-
std::shared_ptr<FloatAttribute> m_eccentricity#
Private Static Functions
-
static double convert_eccentricity(double eccentricity)#
-
virtual std::shared_ptr<FaceUnitCell> clone() const override#
Typedefs
-
template<typename T>
using AABB_tetrahedron_traits = CGAL::AABB_traits_3<SC_Kernel, TetrahedronPrimitive<T>># Define the AABB traits for the TetrahedronPrimitive.
-
template<typename T>
using AABBTree = CGAL::AABB_tree<AABB_tetrahedron_traits<T>># Define the AABB tree for the TetrahedronPrimitive.
-
template<typename T>
class Tetrahedron# - #include <tetrahedron.h>
A class that represents a tetrahedron in 3D space.
This class is used to represent a tetrahedron in 3D space. The tetrahedron is defined by four points in 3D space. The class also stores a value (template) associated with each point in the tetrahedron. Methods are provided to interpolate given a point in space within the tetrahedron.
Public Functions
-
inline glm::vec3 a() const#
Get the first point of the tetrahedron.
- Returns:
The first vertex position.
-
inline T a_val() const#
Get the value associated with the first point.
- Returns:
The value at the first vertex.
-
inline glm::vec3 b() const#
Get the second point of the tetrahedron.
- Returns:
The second vertex position.
-
inline T b_val() const#
Get the value associated with the second point.
- Returns:
The value at the second vertex.
-
inline glm::vec3 barycenter() const#
Compute the barycenter of the tetrahedron.
- Returns:
The barycenter or center of mass of the tetrahedron
-
inline glm::vec4 barycentric_coordinates(const glm::vec3 &point) const#
Compute the barycentric coordinates of a point in space within the tetrahedron.
- Parameters:
point – The point in space to compute the barycentric coordinates for
- Returns:
The barycentric coordinates of the point
-
inline std::pair<glm::vec3, glm::vec3> bounding_box() const#
Compute the bounding box of the tetrahedron.
- Returns:
A pair of the minimum and maximum points of the bounding box
-
inline glm::vec3 c() const#
Get the third point of the tetrahedron.
- Returns:
The third vertex position.
-
inline T c_val() const#
Get the value associated with the third point.
- Returns:
The value at the third vertex.
-
inline glm::vec3 d() const#
Get the fourth point of the tetrahedron.
- Returns:
The fourth vertex position.
-
inline T d_val() const#
Get the value associated with the fourth point.
- Returns:
The value at the fourth vertex.
-
inline bool is_point_inside(const glm::vec3 &point) const#
Check if a point is inside the tetrahedron.
Note
depends on barycentric_coordinates()
- Parameters:
point – The point to check
- Returns:
True if the point is inside the tetrahedron, false otherwise
-
inline glm::vec3 max_point() const#
Compute the maximum point of the tetrahedron.
- Returns:
The maximum point of the tetrahedron
-
inline glm::vec3 min_point() const#
Compute the minimum point of the tetrahedron.
- Returns:
The minimum point of the tetrahedron
-
inline T sample(const glm::vec3 &point) const#
Interpolate a value at a point in space within the tetrahedron.
- Parameters:
point – The point in space to interpolate the value at
- Returns:
The interpolated value at the point
-
inline void set_a(const glm::vec3 &a)#
Set the first point of the tetrahedron.
- Parameters:
a – The new vertex position.
-
inline void set_a_val(const T &val)#
Set the value associated with the first point.
- Parameters:
val – The new value.
-
inline void set_b(const glm::vec3 &b)#
Set the second point of the tetrahedron.
- Parameters:
b – The new vertex position.
-
inline void set_b_val(const T &val)#
Set the value associated with the second point.
- Parameters:
val – The new value.
-
inline void set_c(const glm::vec3 &c)#
Set the third point of the tetrahedron.
- Parameters:
c – The new vertex position.
-
inline void set_c_val(const T &val)#
Set the value associated with the third point.
- Parameters:
val – The new value.
-
inline void set_d(const glm::vec3 &d)#
Set the fourth point of the tetrahedron.
- Parameters:
d – The new vertex position.
-
inline void set_d_val(const T &val)#
Set the value associated with the fourth point.
- Parameters:
val – The new value.
-
Tetrahedron() = default#
Constructor.
-
inline Tetrahedron(const glm::vec3 &a, const glm::vec3 &b, const glm::vec3 &c, const glm::vec3 &d, const T &a_val, const T &b_val, const T &c_val, const T &d_val)#
Constructor.
- Parameters:
a – The first point of the tetrahedron
b – The second point of the tetrahedron
c – The third point of the tetrahedron
d – The fourth point of the tetrahedron
a_val – The value associated with the first point
b_val – The value associated with the second point
c_val – The value associated with the third point
d_val – The value associated with the fourth point
-
inline double volume() const#
Compute the volume of the tetrahedron.
- Returns:
The volume of the tetrahedron in mm^3
-
inline glm::vec3 a() const#
-
template<typename T>
class TetrahedronPrimitive# - #include <tetrahedron.h>
A geometric primitive formatting generalized 3D block layouts extracting values into CGAL traits representations.
Public Types
-
typedef const Tetrahedron<T> *Id#
Primitive id type required by CGAL: the tetrahedron pointer.
Public Functions
-
inline Datum datum() const#
Computes CGAL aligned block matching external spatial bounds containing inner mesh features.
- Returns:
Extracted block constraint metrics wrapping nodes.
-
inline Id id() const#
Fetch mapping linking evaluation targets back to origin objects.
- Returns:
Sourced instance reference pointing underlying representations.
-
inline Point reference_point() const#
Fetches the geometric core mass center evaluating origins.
- Returns:
Localized vertex structure evaluation parameters.
-
inline TetrahedronPrimitive(Tetrahedron<T> *tet)#
Initializer assigning core tetra evaluations handling values attached.
- Parameters:
tet – Wrapped object mapping primitive bounds.
Public Members
-
Tetrahedron<T> *m_ptr#
The wrapped tetrahedron; not owned.
-
typedef const Tetrahedron<T> *Id#
-
class TetrahedralMesh#
- #include <tetrahedral_mesh.h>
Pure geometric tetrahedral mesh generated from an implicit OpenVCAD tree.
The mesh stores explicit node positions and tetrahedral connectivity. It contains no solver-specific or attribute-export logic.
Public Types
Public Functions
-
inline std::pair<glm::vec3, glm::vec3> bounding_box() const#
Returns the prepared bounding box used for meshing.
- Returns:
The box as (minimum, maximum).
-
inline const std::vector<glm::vec3> &cell_centroids() const#
Returns the centroid of each tetrahedral element.
- Returns:
The centroids, in element order.
-
inline const std::vector<Element> &elements() const#
Returns the tetrahedral element connectivity.
- Returns:
One Element of node indices per tetrahedron.
-
inline const std::vector<glm::vec3> &nodes() const#
Returns the mesh node coordinates.
- Returns:
The node coordinates.
-
inline size_t number_of_elements() const#
Returns the number of tetrahedral elements.
- Returns:
The element count.
-
inline size_t number_of_nodes() const#
Returns the number of mesh nodes.
- Returns:
The node count.
-
TetrahedralMesh() = default#
Constructs an empty mesh.
-
TetrahedralMesh(const std::vector<glm::vec3> &nodes, const std::vector<Element> &elements, const std::vector<glm::vec3> &cell_centroids, const std::pair<glm::vec3, glm::vec3> &bounding_box)#
Constructs a mesh from explicit data.
- Parameters:
nodes – The node coordinates.
elements – The element connectivity, as indices into nodes.
cell_centroids – The centroid of each element.
bounding_box – The bounding box the mesh was generated in.
Public Static Functions
Builds a tetrahedral mesh from an already prepared implicit tree using adaptive cell sizing.
- Parameters:
root – The prepared root of the tree.
settings – The mesh criteria and cell-size expression.
thread_usage_tracker – Optional tracker that records the threads used; may be nullptr.
- Returns:
The mesh.
Builds a tetrahedral mesh from an already prepared implicit tree using fixed cell sizing.
- Parameters:
root – The prepared root of the tree.
settings – The mesh criteria.
thread_usage_tracker – Optional tracker that records the threads used; may be nullptr.
- Returns:
The mesh.
Builds a tetrahedral mesh from an implicit tree using adaptive cell sizing.
Prepares root with a voxel size of min(facet_size, cell_size_lower) and a bandwidth of 6 * max(facet_size, cell_size_upper).
- Parameters:
root – The root of the tree.
settings – The mesh criteria and cell-size expression.
- Returns:
The mesh.
Builds a tetrahedral mesh from an implicit tree using fixed cell sizing.
Prepares root with a voxel size of min(facet_size, cell_size) and a bandwidth of 6 * max(facet_size, cell_size).
- Parameters:
root – The root of the tree.
settings – The mesh criteria.
- Returns:
The mesh.
Private Members
-
std::pair<glm::vec3, glm::vec3> m_bounding_box#
-
std::vector<glm::vec3> m_cell_centroids#
-
std::vector<glm::vec3> m_nodes#
-
struct AdaptiveSettings#
- #include <tetrahedral_mesh.h>
Settings for an adaptive tetrahedral mesh.
These are CGAL mesh criteria; lengths are in mm. The cell size at each point is variable_cell_size_expression, evaluated with the variables min_cell (cell_size_lower), max_cell (cell_size_upper) and h (the length of the root’s gradient() at the point).
Public Members
-
size_t cell_radius_edge_ratio = 3#
Largest circumradius to shortest edge ratio of a tetrahedron.
-
double cell_size_lower = 0.1#
Smallest cell size; min_cell in the expression.
-
double cell_size_upper = 1.0#
Largest cell size; max_cell in the expression.
-
double facet_angle = 30.0#
Smallest surface-triangle angle, in degrees.
-
double facet_distance = 0.01#
Largest distance between a surface triangle and the true surface.
-
double facet_size = 0.1#
Largest surface-triangle size.
-
uint32_t random_seed = 0#
Seed for the mesher’s random choices.
-
std::string variable_cell_size_expression = "min_cell + h * (max_cell - min_cell)"#
Cell-size expression of min_cell, max_cell and h.
-
size_t cell_radius_edge_ratio = 3#
-
struct FixedSettings#
- #include <tetrahedral_mesh.h>
Settings for a fixed-size tetrahedral mesh.
These are CGAL mesh criteria; lengths are in mm.
Public Members
-
size_t cell_radius_edge_ratio = 3#
Largest circumradius to shortest edge ratio of a tetrahedron.
-
double cell_size = 0.1#
Largest tetrahedron circumradius.
-
double facet_angle = 30.0#
Smallest surface-triangle angle, in degrees.
-
double facet_distance = 0.01#
Largest distance between a surface triangle and the true surface.
-
double facet_size = 0.1#
Largest surface-triangle size.
-
uint32_t random_seed = 0#
Seed for the mesher’s random choices.
-
size_t cell_radius_edge_ratio = 3#
-
inline std::pair<glm::vec3, glm::vec3> bounding_box() const#
-
class HexahedralMesh#
- #include <hexahedral_mesh.h>
Pure geometric structured hexahedral mesh generated from an implicit OpenVCAD tree.
The mesh stores explicit node positions and hexahedral connectivity. It contains no solver-specific or attribute-export logic. The root’s bounding box is split into a grid of voxel_size cells; a cell becomes an element when the tree’s signed distance at its centre is <= 0. Unused grid nodes are dropped.
Public Types
Public Functions
-
inline std::pair<glm::vec3, glm::vec3> bounding_box() const#
Returns the prepared bounding box used for meshing.
- Returns:
The box as (minimum, maximum).
-
inline const std::vector<glm::vec3> &cell_centroids() const#
Returns the centroid of each hexahedral element.
- Returns:
The centroids, in element order.
-
inline const std::vector<Element> &elements() const#
Returns the hexahedral element connectivity.
- Returns:
One Element of node indices per hexahedron.
-
HexahedralMesh() = default#
Constructs an empty mesh.
-
HexahedralMesh(const std::vector<glm::vec3> &nodes, const std::vector<Element> &elements, const std::vector<glm::vec3> &cell_centroids, const std::pair<glm::vec3, glm::vec3> &bounding_box, const glm::vec3 &voxel_size)#
Constructs a mesh from explicit data.
- Parameters:
nodes – The node coordinates.
elements – The element connectivity, as indices into nodes.
cell_centroids – The centroid of each element.
bounding_box – The bounding box the mesh was generated in.
voxel_size – The hexahedron edge lengths.
-
inline const std::vector<glm::vec3> &nodes() const#
Returns the mesh node coordinates.
- Returns:
The node coordinates.
-
inline size_t number_of_elements() const#
Returns the number of hexahedral elements.
- Returns:
The element count.
-
inline size_t number_of_nodes() const#
Returns the number of mesh nodes.
- Returns:
The node count.
-
inline glm::vec3 voxel_size() const#
Returns the voxel size used for structured meshing.
- Returns:
The hexahedron edge lengths.
Public Static Functions
Builds a structured hexahedral mesh from a root that has already been prepared with settings.voxel_size.
- Parameters:
root – The prepared root of the tree.
settings – The mesh settings.
thread_usage_tracker – Optional tracker that records the calling thread; may be nullptr.
- Returns:
The mesh.
Builds a structured hexahedral mesh from an implicit tree.
Prepares root with settings.voxel_size and a bandwidth of 6 times its largest component.
- Parameters:
root – The root of the tree.
settings – The mesh settings.
- Returns:
The mesh.
-
inline std::pair<glm::vec3, glm::vec3> bounding_box() const#
Lookup tables mapping edge and triangle topologies required for traditional Marching Cubes isosurface extraction implementations.
Variables
-
static int EdgeTable[256]#
For each of the 256 corner-sign cases, a 12-bit mask of the cube edges the surface crosses.
-
static int TriangleTable[4096]#
For each of the 256 cases, 16 entries: up to five triangles as edge-index triples, padded with -1.
-
class DICOMVolume#
- #include <dicom_volume.h>
A grid-based volume generated from a directory of medical DICOM slice images representing spatial density (Hounsfield units).
Public Functions
-
std::pair<glm::vec3, glm::vec3> bounding_box() const#
Returns the bounds encompassing the internal OpenVDB storage limits.
Note
The minimum corner is the configured origin and the maximum corner is that origin offset by the physical extents of the stack, in mm.
- Returns:
Defined coordinate constraints mapping [min, max].
-
void center_on_origin()#
Place the volume so that its physical centre sits on the coordinate system origin.
Convenience wrapper around set_origin() for the common case of centring a scan.
-
std::shared_ptr<DICOMVolume> clone()#
Generates a discrete copy of the DICOM volume evaluation elements.
- Returns:
A cloned DICOMVolume mapping pointer.
-
DICOMVolume() = default#
Default constructor.
-
DICOMVolume(const std::string &directory, double rescale_slope = -std::numeric_limits<double>::infinity(), double rescale_intercept = -std::numeric_limits<double>::infinity(), double slice_thickness = -std::numeric_limits<double>::infinity(), double x_pixel_spacing = -std::numeric_limits<double>::infinity(), double y_pixel_spacing = -std::numeric_limits<double>::infinity(), DICOMSliceOrder slice_order = DICOMSliceOrder::AUTO, const std::string &filename_prefix = "", const glm::vec3 &origin = glm::vec3(0.0f))#
Construct a DICOM volume from the given directory.
- Parameters:
directory – The directory containing the DICOM stack.
rescale_slope – Slope applied to raw pixel values to get Hounsfield units. The default (negative infinity) reads it from the metadata.
rescale_intercept – Intercept added after the slope. The default reads it from the metadata.
slice_thickness – Voxel size along z, in mm. The default reads it from the metadata.
x_pixel_spacing – Voxel size along x, in mm. The default reads it from the metadata.
y_pixel_spacing – Voxel size along y, in mm. The default reads it from the metadata.
slice_order – How the slice files are ordered into a stack. See DICOMSliceOrder.
filename_prefix – A literal filename prefix ignored when the order falls back to filenames. Use it when the fixed part of a filename contains digits that must not take part in the ordering (for example “scan2024_” in “scan2024_001.dcm”).
origin – The world-space position, in mm, of the volume’s minimum corner. Defaults to the coordinate system origin.
- Throws:
std::runtime_error – if a value left at its default is missing from the metadata.
-
inline const glm::vec3 &get_origin() const#
Get the world-space position, in mm, of the volume’s minimum corner.
- Returns:
The configured origin.
-
double sample(double x, double y, double z) const#
Sample the volume at the given world coordinates.
Note
The coordinates are in world space, not voxel space, and are taken relative to the configured origin. This will use interpolation to sample the volume.
- Parameters:
x – The x-coordinate in mm.
y – The y-coordinate in mm.
z – The z-coordinate in mm.
- Returns:
The Hounsfield value at the given coordinates.
-
void set(double hounsfield_value, size_t x, size_t y, size_t z)#
Set the Hounsfield value at the given voxel coordinates.
Note
This will set the value directly in the volume grid. This are in grid indices, not world space.
- Parameters:
hounsfield_value – The Hounsfield value to set.
x – The x-coordinate in voxel space.
y – The y-coordinate in voxel space.
z – The z-coordinate in voxel space.
-
inline void set_origin(const glm::vec3 &origin)#
Set the world-space position, in mm, of the volume’s minimum corner.
Moving the origin shifts both the bounding box and the world coordinates accepted by sample(); the underlying voxel data is left untouched.
- Parameters:
origin – The new origin in mm.
Private Types
-
using GridType = openvdb::DoubleGrid#
Private Functions
-
std::vector<std::vector<double>> load_dicom_image(const std::string &file_path)#
Load a single DICOM image from the given file path and return the pixel data as a 2D vector.
-
void load_dicom_stack(const std::string &directory)#
Load a DICOM stack from the given directory into an OpenVDB volume.
- Parameters:
directory – The directory containing the DICOM stack.
Private Members
-
std::string m_filename_prefix#
-
glm::vec3 m_origin = glm::vec3(0.0f)#
-
double m_rescale_intercept = -std::numeric_limits<double>::infinity()#
-
double m_rescale_slope = -std::numeric_limits<double>::infinity()#
-
DICOMSliceOrder m_slice_order = DICOMSliceOrder::AUTO#
-
double m_x_size = 0#
-
double m_x_spacing = -std::numeric_limits<double>::infinity()#
-
double m_y_size = 0#
-
double m_y_spacing = -std::numeric_limits<double>::infinity()#
-
double m_z_size = 0#
-
double m_z_spacing = -std::numeric_limits<double>::infinity()#
Private Static Functions
-
static DICOM_Meta_Data GetDICOMMetaData(const std::string &file_path)#
Get the metadata for a DICOM image from the given file path.
-
static double GetRescaledValue(Uint16 pixel_value, double rescale_slope, double rescale_intercept)#
-
struct DICOM_Meta_Data#
Public Members
-
bool found_rescale_intercept = false#
-
bool found_rescale_slope = false#
-
bool found_thickness = false#
-
bool found_width_and_height = false#
-
bool found_xy_spacing = false#
-
size_t height = 0#
-
double rescale_intercept = 0.0#
-
double rescale_slope = 1.0#
-
double slice_thickness = 1#
-
size_t width = 0#
-
double x_pixel_spacing = -1#
-
double y_pixel_spacing = -1#
-
bool found_rescale_intercept = false#
-
std::pair<glm::vec3, glm::vec3> bounding_box() const#
Typedefs
-
using AABB_node_traits = CGAL::AABB_traits<SC_Kernel, NodeBBoxPrimitive>#
Define the AABB traits for the NodeBBoxPrimitive.
-
using NodeAABBTree = CGAL::AABB_tree<AABB_node_traits>#
Define the AABB tree for the NodeBBoxPrimitive.
-
struct NodeBBoxPrimitive#
- #include <node_bbox_primitive.h>
A geometric primitive wrapper converting internal OpenVCAD Node bounds to CGAL AABB tree compatible formats.
Public Types
Public Functions
-
inline Datum datum() const#
Generates local coordinate constraints matching the Node topology block.
- Returns:
Formatted CGAL bounding box matching extraction sizes.
-
inline Id id() const#
Fetch the associated source node instance.
- Returns:
Pointer reference mapping the original source Node.
Initializes a generic primitive shell extracting evaluation constraints from a base Node.
- Parameters:
node – Target geometry entity to bound.
-
inline Datum datum() const#
Typedefs
-
using AABB_vcad_node_traits = CGAL::AABB_traits_3<SC_Kernel, VCADNodeBBoxPrimitive>#
-
using AABBVCADTree = CGAL::AABB_tree<AABB_vcad_node_traits>#
-
struct VCADNodeBBoxPrimitive#
- #include <vcad_node_bbox_primitive.h>
A geometric primitive wrapper converting internal OpenVCAD Node bounds with an expanded padding bandwidth to CGAL AABB tree compatible formats.
Public Types
Public Functions
-
inline Datum datum() const#
Generates local coordinate constraints matching the Node topology block expanded by the bandwidth.
- Returns:
Formatted CGAL bounding box matching extraction sizes.
-
inline Id id() const#
Fetch the associated source node instance.
- Returns:
Pointer reference mapping the original source Node.
-
inline Point reference_point() const#
Computes the centered evaluation point representing the primitive origin offset.
- Returns:
Point matching geometric centroid layout.
Initializes a generic primitive shell extracting evaluation constraints from a base Node with an expanded bandwidth.
- Parameters:
node – Target geometry entity to bound.
bandwidth – Padding threshold adjusting external bound scales.
-
inline Datum datum() const#
Functions
Morph a random seed set into a regular site set with a regularity field.
Regularity w is sampled at every site and random point and clamped to [0, 1]. Regular sites with w > 0 are paired with random points with w < 1 by greedy nearest matching within match_radius (shortest pairs first). A pair becomes one seed at q + w(r) (r - q), so seeds slide from their random positions (w = 0) onto the regular sites (w = 1) while the seed count stays the same. Unpaired regular sites are kept where w >= 0.5, unpaired random points where w < 0.5. Finally seeds closer than minimum_separation to a seed with higher regularity are dropped, which removes slivers that would create tiny Voronoi cells. When a host is given, a blended seed that falls outside it is moved to whichever source point is inside.
- Parameters:
host – Optional prepared host (may be null).
random_points – Random seeds, for example from sample_poisson_seeds().
regular_points – Regular lattice sites.
regularity – Regularity field; 0 keeps random seeds, 1 keeps regular sites.
match_radius – Maximum pairing distance in millimetres.
minimum_separation – Minimum distance between output seeds (0 disables the check).
boundary_clearance – Host clearance used for the containment check.
- Returns:
Blended seeds and their provenance.
Randomly displace regular sites by an amount that falls to zero where w = 1.
Each site r moves to r + (1 - w(r)) * amplitude * u, with u uniform in the unit ball and drawn from a per-site stream, so results do not depend on order. This is the classic “perturbed lattice” route from a regular Voronoi foam (w = 1) to an irregular one. Displacements that would leave the host or come closer than minimum_separation to an already placed seed are redrawn (up to 16 times) and then shrunk towards the site.
- Parameters:
host – Optional prepared host (may be null).
regular_points – Regular lattice sites.
regularity – Regularity field sampled at the sites and clamped to [0, 1].
amplitude – Maximum displacement in millimetres where w = 0.
seed – Random seed.
minimum_separation – Minimum distance between output seeds (0 disables the check).
boundary_clearance – Host clearance used for the containment check.
- Returns:
Displaced seeds with regular_index set to the source site.
Sample variable-spacing Poisson-disk seeds inside a prepared host.
Uses Bridson’s active-list growth with a uniform background grid, followed by rounds of random darts that restart growth in host regions the front never reached (disconnected or narrow parts). Two points are accepted together when their distance is at least the mean of their local spacings, the same rule as the Python sample_points_in_host(). The spacing field is sampled at candidate positions with the host signed distance as its d argument. Results depend only on the inputs and seed.
- Parameters:
host – Prepared implicit host; a point is inside when its SDF is <= -boundary_clearance.
spacing – Positive, finite local spacing field in millimetres.
seed – Random seed.
max_count – Maximum number of points, or 0 for no limit other than saturation.
boundary_clearance – Non-negative distance kept between seeds and the host surface.
attempts_per_point – Candidates tried around each active point (Bridson’s k).
- Returns:
Accepted points and statistics.
Sample variable-spacing Poisson-disk seeds on a triangle surface.
Darts land uniformly by area: a triangle is chosen in proportion to its area and a point uniformly inside it. A dart is kept when its Euclidean distance to every kept point is at least the mean of their local spacings, the same rule as sample_poisson_seeds(). Sampling stops after a long run of rejected darts (attempts_per_point times the number of points, and at least 64 times that), which leaves the surface close to saturated. Each dart needs only its own triangle, so open, non-manifold or noisy scanned meshes work. The spacing field is sampled at each dart with d = 0. Distances are straight-line, so keep the spacing below the thickness of thin walls and the gap between nearby sheets. Results depend only on the inputs.
- Parameters:
mesh – Triangle surface; degenerate triangles are ignored.
spacing – Positive, finite local spacing field in millimetres.
seed – Random seed.
max_count – Maximum number of points, or 0 for no limit other than saturation.
attempts_per_point – Rejected darts allowed per kept point before sampling stops.
- Returns:
Accepted points, their triangles and spacings, and statistics.
Return the indices of points that lie inside a prepared host.
Points are evaluated in parallel with thread-local host clones.
- Parameters:
host – Prepared implicit host.
points – World-space points.
boundary_clearance – A point is kept when its host SDF is <= -boundary_clearance.
- Returns:
Ascending indices of the kept points.
-
struct PoissonSeedResult#
- #include <stochastic_seeds.h>
World-space seed points from sample_poisson_seeds() plus sampling statistics.
Public Members
-
size_t candidate_count = 0#
Number of candidate positions tested.
-
std::vector<glm::vec3> points#
Accepted seed points in acceptance order.
-
size_t rejected_count = 0#
Number of candidates rejected for spacing or host containment.
-
std::vector<double> spacings#
Local spacing sampled at each accepted point.
-
size_t candidate_count = 0#
-
struct SeedBlendResult#
- #include <stochastic_seeds.h>
Seeds that change from a random point set into a regular point set.
Public Members
-
size_t matched_count = 0#
Number of random points paired with a regular site.
-
std::vector<glm::vec3> points#
Output seed points.
-
std::vector<long long> random_index#
Source random point of each output point, or -1 when it came only from the regular set.
-
std::vector<long long> regular_index#
Source regular site of each output point, or -1 when it came only from the random set.
-
std::vector<double> regularity#
Regularity weight in [0, 1] that placed each output point.
-
size_t separation_dropped_count = 0#
Number of points removed because they were closer than the minimum separation.
-
size_t matched_count = 0#
-
struct SurfaceSeedResult#
- #include <stochastic_seeds.h>
Seed points on a triangle surface from sample_surface_poisson_seeds().
Public Members
-
size_t candidate_count = 0#
Number of candidate positions tested.
-
std::vector<glm::vec3> points#
Accepted seed points in acceptance order, on the surface.
-
size_t rejected_count = 0#
Number of candidates rejected for spacing.
-
std::vector<double> spacings#
Local spacing sampled at each accepted point.
-
std::vector<size_t> triangle_ids#
Index of the triangle each point lies on.
-
size_t candidate_count = 0#
Enums
-
enum class StochasticBoundaryMode#
Inspectable boundary topology retained by a confined stochastic lattice.
Values:
-
enumerator OpenClip#
Members are clipped by the host and their cut ends are left open.
-
enumerator ClosedConfine#
Members are confined to the host and closed with boundary caps or contact patches.
-
enumerator OpenClip#
-
enum class StochasticFaceExtraction#
World-space face soup extracted from one shared 3D Delaunay tessellation.
Values:
-
enumerator DelaunayFacets#
Triangular Delaunay facets.
-
enumerator VoronoiFaces#
Polygonal faces shared by neighboring bounded Voronoi cells.
-
enumerator DelaunayFacets#
-
enum class StochasticGraphExtraction#
World-space graph extracted from one shared 3D Delaunay tessellation.
Values:
-
enumerator DelaunayEdges#
Delaunay edges between neighboring seeds.
-
enumerator DelaunayFacetVertexCentroid#
Segments from each Delaunay facet centroid to its three vertices.
-
enumerator DelaunayBarycentricDual#
Segments joining the centroids of the tetrahedra on each side of a facet.
-
enumerator VoronoiEdges#
Voronoi edges (Delaunay facet duals), clipped to the working box.
-
enumerator DelaunayEdges#
Functions
-
StochasticTessellation build_stochastic_tessellation(const std::vector<glm::vec3> &points, const glm::vec3 &working_min, const glm::vec3 &working_max, bool compute_voronoi_cells = true)#
Build shared Delaunay and bounded Voronoi products for world-space points.
Uses CGAL exact predicates with inexact constructions. Input order defines stable seed IDs. The working box makes hull Voronoi products finite but is not emitted as lattice geometry.
- Parameters:
points – Unique, finite world-space seed points spanning three dimensions.
working_min – Minimum corner of the finite construction domain.
working_max – Maximum corner of the finite construction domain.
compute_voronoi_cells – When false, voronoi_cells and voronoi_faces are left empty; compute them later with compute_stochastic_voronoi_cells(). Graph lattices only need the Voronoi edges, and the per-cell half-space intersections dominate preparation time for large seed sets.
- Returns:
Shared Delaunay/Voronoi products with stable input provenance.
-
bool clip_stochastic_ray_to_box(const glm::vec3 &origin, const glm::vec3 &direction, const glm::vec3 &minimum, const glm::vec3 &maximum, glm::vec3 &first, glm::vec3 &second)#
Clip a ray to an axis-aligned working box.
- Parameters:
origin – Ray origin.
direction – Non-zero ray direction.
minimum – Working-box minimum.
maximum – Working-box maximum.
first – First clipped point.
second – Second clipped point.
- Returns:
True when the ray intersects a non-zero box interval.
-
void compute_stochastic_voronoi_cells(StochasticTessellation &tessellation, const std::vector<glm::vec3> &points)#
Fill a tessellation’s bounded Voronoi cells and faces.
Uses the stored Delaunay edges and facets, so the triangulation is not rebuilt. Results are identical to build_stochastic_tessellation(…, true).
- Parameters:
tessellation – Tessellation built from points; its cell and face products are replaced.
points – The same seed points used to build the tessellation.
-
struct DelaunayCellProduct#
- #include <stochastic_tessellation.h>
Inspectable tetrahedron and quality metadata from the Delaunay tessellation.
Public Members
-
glm::vec3 centroid = {0.0f}#
Average of the four vertices.
-
glm::vec3 circumcenter = {0.0f}#
Circumsphere center (the dual Voronoi vertex).
-
double edge_ratio_quality = 0.0#
Shortest edge length divided by longest edge length, in [0, 1].
-
size_t id = 0#
Index of the tetrahedron in StochasticTessellation::delaunay_cells.
-
std::array<int, 4> seed_ids = {{-1, -1, -1, -1}}#
Seed IDs of the four vertices.
-
std::array<glm::vec3, 4> vertices#
World-space vertex positions, in the same order as seed_ids.
-
double volume = 0.0#
Unsigned tetrahedron volume.
-
glm::vec3 centroid = {0.0f}#
-
struct StochasticBoundaryCapProduct#
- #include <stochastic_tessellation.h>
One host-boundary closure associated with a confined graph fragment.
Public Members
-
std::array<int, 2> cell_ids = {{-1, -1}}#
Delaunay cell IDs copied from the source edge.
-
glm::vec3 center = {0.0f}#
World-space boundary point where the cap sits.
-
size_t edge_id = 0#
ID of the source edge the capped fragment came from.
-
size_t fragment_id = 0#
Fragment index of the capped fragment along its source edge.
-
size_t id = 0#
Index of the cap in the lattice’s cap list.
-
double radius = 0.0#
Beam radius at the cap.
-
std::array<int, 4> seed_ids = {{-1, -1, -1, -1}}#
Seed IDs copied from the source edge.
-
glm::vec3 tangent = {0.0f}#
Unit beam direction pointing from the cap into the fragment, or zero for a degenerate fragment.
-
std::array<int, 2> cell_ids = {{-1, -1}}#
-
struct StochasticBoundaryContactProduct#
- #include <stochastic_tessellation.h>
Approximate host-surface patch owned by a closed plate-lattice boundary.
-
struct StochasticBoundarySeamProduct#
- #include <stochastic_tessellation.h>
One approximate seam segment around a closed plate contact patch.
-
struct StochasticEdgeProduct#
- #include <stochastic_tessellation.h>
One inspectable edge or confined edge fragment.
Public Members
-
std::array<int, 2> cell_ids = {{-1, -1}}#
Adjacent finite Delaunay cell IDs; unused slots are -1.
-
StochasticGraphExtraction extraction = StochasticGraphExtraction::DelaunayEdges#
Extraction that produced the edge.
-
glm::vec3 first = {0.0f}#
First world-space endpoint.
-
bool first_is_boundary = false#
True when the first endpoint was cut at the host boundary.
-
double first_radius = 0.0#
Beam radius sampled at the first endpoint (set by the graph lattice).
-
size_t fragment_id = 0#
Index of this fragment along its source edge after host confinement (0 when unconfined).
-
size_t id = 0#
Index of the source edge in its product list.
Fragments keep their source edge’s ID.
-
bool is_boundary = false#
True for a ClosedConfine fragment that ends on the host boundary.
-
bool is_hull = false#
True when the edge comes from a convex-hull Delaunay facet.
-
glm::vec3 second = {0.0f}#
Second world-space endpoint.
-
bool second_is_boundary = false#
True when the second endpoint was cut at the host boundary.
-
double second_radius = 0.0#
Beam radius sampled at the second endpoint (set by the graph lattice).
-
std::array<int, 4> seed_ids = {{-1, -1, -1, -1}}#
Input seed IDs that define the edge, sorted ascending; unused slots are -1.
-
bool working_domain_truncated = false#
True when an infinite Voronoi ray was clipped to the working box.
-
std::array<int, 2> cell_ids = {{-1, -1}}#
-
struct StochasticFaceProduct#
- #include <stochastic_tessellation.h>
One inspectable polygonal tessellation face.
Public Members
-
std::array<int, 2> cell_ids = {{-1, -1}}#
Adjacent Delaunay cell IDs (Delaunay facets) or Voronoi cell IDs (Voronoi faces); unused slots are -1.
-
StochasticFaceExtraction extraction = StochasticFaceExtraction::DelaunayFacets#
Extraction that produced the face.
-
size_t id = 0#
Index of the face in its product list.
-
bool is_boundary_contact = false#
True when the face crosses the host boundary (set by the face lattice).
-
bool is_hull = false#
True for a convex-hull Delaunay facet, or a Voronoi face touching a hull seed’s cell.
-
std::array<int, 2> neighboring_seed_ids = {{-1, -1}}#
The two seeds a Voronoi face separates; -1 for Delaunay facets.
-
std::array<int, 4> seed_ids = {{-1, -1, -1, -1}}#
Defining seed IDs, sorted ascending: three for a Delaunay facet, two for a Voronoi face; unused slots are -1.
-
std::vector<double> vertex_thicknesses#
Plate thickness sampled at each vertex (set by the face lattice).
-
std::vector<glm::vec3> vertices#
World-space polygon vertices.
-
bool working_domain_truncated = false#
True when a Voronoi face has a vertex on the working box.
-
std::array<int, 2> cell_ids = {{-1, -1}}#
-
struct StochasticTessellation#
- #include <stochastic_tessellation.h>
Compact OpenVCAD-native products derived from a CGAL Delaunay triangulation.
Public Members
-
std::vector<DelaunayCellProduct> delaunay_cells#
Finite Delaunay tetrahedra.
-
std::vector<StochasticEdgeProduct> delaunay_edges#
Finite Delaunay edges.
-
std::vector<StochasticFaceProduct> delaunay_faces#
Finite Delaunay facets.
-
std::vector<VoronoiCellProduct> voronoi_cells#
One bounded Voronoi cell per seed, indexed by seed ID.
-
std::vector<StochasticEdgeProduct> voronoi_edges#
Voronoi edges, with hull rays clipped to the working box.
-
std::vector<StochasticFaceProduct> voronoi_faces#
Faces shared by neighboring bounded Voronoi cells.
-
glm::vec3 working_max = {0.0f}#
Maximum corner of the finite working box.
-
glm::vec3 working_min = {0.0f}#
Minimum corner of the finite working box.
-
std::vector<DelaunayCellProduct> delaunay_cells#
-
struct VoronoiCellProduct#
- #include <stochastic_tessellation.h>
One finite working-domain Voronoi cell and size metrics.
Public Members
-
double equivalent_diameter = 0.0#
Diameter of the sphere with the same volume.
-
std::vector<size_t> face_ids#
IDs into StochasticTessellation::voronoi_faces of the faces shared with neighbors (working-box faces are not listed).
-
size_t id = 0#
Index of the cell; equal to seed_id.
-
double maximum_diameter = 0.0#
Largest distance between two cell vertices.
-
std::vector<size_t> neighboring_seed_ids#
Delaunay neighbor seed IDs, sorted ascending.
-
glm::vec3 seed = {0.0f}#
World-space seed position.
-
size_t seed_id = 0#
Input index of the cell’s seed.
-
std::vector<glm::vec3> vertices#
World-space vertices of the bounded cell.
-
double volume = 0.0#
Cell volume.
-
bool working_domain_truncated = false#
True when a cell vertex lies on the working box.
-
double equivalent_diameter = 0.0#
Functions
-
SurfaceVoronoi restricted_voronoi(const SurfaceMesh &mesh, const std::vector<glm::vec3> &seeds)#
Compute the restricted Voronoi diagram of seed points on a triangle surface.
This is the 3D Voronoi diagram of the seeds intersected with the surface: the region of a seed is the part of the surface closer to it than to any other seed. Every triangle is handled on its own, so open, non-manifold or noisy scanned meshes work. A Voronoi cell is convex, so a triangle whose three corners have the same nearest seed belongs to that seed whole. Any other triangle is clipped exactly against the bisector planes of every seed that can own part of it (all seeds within min_v d(v) + 3 r of its centroid, where d(v) is a corner’s nearest-seed distance and r the largest centroid-to-corner distance). Triangles run in parallel; the result does not depend on the thread count. Seeds need not lie on the surface, but seeds sampled on it (sample_surface_poisson_seeds()) give the expected cells.
- Parameters:
mesh – Triangle surface; degenerate triangles are ignored.
seeds – Finite seed points.
- Returns:
The boundary pieces and the area each seed owns.
-
struct SurfaceVoronoi#
- #include <surface_voronoi.h>
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, by straight-line distance. The pieces of the boundaries between those regions are the edges, in triangle order; within a triangle, in seed order.
Public Members
-
std::vector<double> cell_areas#
Surface area owned by each seed.
-
std::vector<SurfaceVoronoiEdge> edges#
Boundary pieces between the restricted cells.
-
std::vector<double> cell_areas#
-
struct SurfaceVoronoiEdge#
- #include <surface_voronoi.h>
One straight piece of a restricted Voronoi edge, lying in one triangle.
Public Members
-
glm::vec3 first = {0.0f}#
First end point, on the surface.
-
glm::vec3 second = {0.0f}#
Second end point, on the surface.
-
size_t seed_a = 0#
The smaller of the two seeds whose cells meet along this piece.
-
size_t seed_b = 0#
The larger of the two seeds whose cells meet along this piece.
-
size_t triangle = 0#
Index of the triangle that contains the piece.
-
glm::vec3 first = {0.0f}#
-
class PointGrid#
- #include <point_grid.h>
A uniform bucket grid over indexed points for radius and nearest-point queries.
Points are stored by index; the caller keeps their coordinates. Points outside the grid’s box are clamped into the border cells, so queries stay exact for any point. The cell size grows when the grid would exceed about 32 million cells. Used by the seed samplers and the restricted Voronoi diagram.
Public Functions
-
inline void insert(size_t index, const glm::vec3 &point)#
Add the point with the given index.
- Parameters:
index – The point’s index; the caller keeps its coordinates under this index.
point – The point’s coordinates, used to pick its cell.
-
inline size_t nearest(const glm::vec3 &point, const std::vector<glm::vec3> &points, double &distance) const#
Return the index of the stored point nearest to a query, searching ring by ring.
- Parameters:
point – Query point.
points – Coordinates of the stored points, by index.
distance – Receives the distance to the nearest point.
- Returns:
The nearest index, or the largest size_t value when the grid is empty.
-
inline PointGrid(const glm::dvec3 &minimum, const glm::dvec3 &maximum, double cell)#
Construct an empty grid over a box.
- Parameters:
minimum – Box minimum corner.
maximum – Box maximum corner.
cell – Requested cell edge length.
-
template<class Visitor>
inline void visit_near(const glm::vec3 &point, double radius, Visitor visit) const# Call visit(index) for every stored point in cells within radius of point.
Visits a superset of the points within radius; the caller tests distances.
- Parameters:
point – Query point.
radius – Search radius.
visit – Callable invoked as visit(index) for each candidate point.
-
inline void insert(size_t index, const glm::vec3 &point)#