Lagrange
Loading...
Searching...
No Matches
bind_utilities.h
1/*
2 * Copyright 2022 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12#pragma once
13
14#include <lagrange/AttributeTypes.h>
15#include <lagrange/NormalWeightingType.h>
16#include <lagrange/cast_attribute.h>
17#include <lagrange/combine_meshes.h>
18#include <lagrange/compute_area.h>
19#include <lagrange/compute_centroid.h>
20#include <lagrange/compute_components.h>
21#include <lagrange/compute_dihedral_angles.h>
22#include <lagrange/compute_dijkstra_distance.h>
23#include <lagrange/compute_edge_lengths.h>
24#include <lagrange/compute_facet_circumcenter.h>
25#include <lagrange/compute_facet_normal.h>
26#include <lagrange/compute_greedy_coloring.h>
27#include <lagrange/compute_mesh_covariance.h>
28#include <lagrange/compute_normal.h>
29#include <lagrange/compute_pointcloud_pca.h>
30#include <lagrange/compute_seam_edges.h>
31#include <lagrange/compute_tangent_bitangent.h>
32#include <lagrange/compute_uv_charts.h>
33#include <lagrange/compute_uv_distortion.h>
34#include <lagrange/compute_uv_orientation.h>
35#include <lagrange/compute_uv_tile_list.h>
36#include <lagrange/compute_vertex_normal.h>
37#include <lagrange/compute_vertex_valence.h>
38#include <lagrange/disconnect_uv_charts.h>
39#include <lagrange/extract_submesh.h>
40#include <lagrange/filter_attributes.h>
41#include <lagrange/get_unique_attribute_name.h>
42#include <lagrange/internal/constants.h>
43#include <lagrange/isoline.h>
44#include <lagrange/map_attribute.h>
45#include <lagrange/mesh_bbox.h>
46#include <lagrange/normalize_meshes.h>
47#include <lagrange/orient_outward.h>
48#include <lagrange/orientation.h>
49#include <lagrange/permute_facets.h>
50#include <lagrange/permute_vertices.h>
51#include <lagrange/python/binding.h>
52#include <lagrange/python/tensor_utils.h>
53#include <lagrange/python/utils/StackVector.h>
54#include <lagrange/python/utils/StubType.h>
55#include <lagrange/remap_vertices.h>
56#include <lagrange/reorder_mesh.h>
57#include <lagrange/select_facets_by_normal_similarity.h>
58#include <lagrange/select_facets_in_frustum.h>
59#include <lagrange/separate_by_components.h>
60#include <lagrange/separate_by_facet_groups.h>
61#include <lagrange/split_facets_by_material.h>
62#include <lagrange/thicken_and_close_mesh.h>
63#include <lagrange/topology.h>
64#include <lagrange/transform_mesh.h>
65#include <lagrange/triangulate_polygonal_facets.h>
66#include <lagrange/unflip_uv_charts.h>
67#include <lagrange/unify_index_buffer.h>
68#include <lagrange/utils/chain_edges.h>
69#include <lagrange/utils/fmt/format.h>
70#include <lagrange/utils/invalid.h>
71#include <lagrange/uv_mesh.h>
72#include <lagrange/weld_indexed_attribute.h>
73
74#include <algorithm>
75#include <optional>
76#include <string_view>
77#include <vector>
78
79namespace lagrange::python {
80
81LA_STUB_HINT(IterableUsageHint, "collections.abc.Iterable[AttributeUsage]");
82LA_STUB_HINT(IterableElementHint, "collections.abc.Iterable[AttributeElement]");
83
84template <typename Scalar, typename Index>
85void bind_utilities(nanobind::module_& m)
86{
87 namespace nb = nanobind;
88 using namespace nb::literals;
89 using MeshType = SurfaceMesh<Scalar, Index>;
90
91 m.def(
92 "chain_edges",
93 [](Tensor<Index> edges,
94 bool directed,
95 bool output_edge_index,
96 bool close_loop_with_identical_vertices) {
97 auto [data, shape, stride] = tensor_to_span(edges);
99 shape.size() == 2 && shape[1] == 2,
100 "Edge tensor must have shape num_edges x 2");
101 la_runtime_assert(data.empty() || is_dense(shape, stride));
103 std::find(data.begin(), data.end(), invalid<Index>()) == data.end(),
104 "Edge vertex indices cannot equal invalid_index");
105
106 ChainEdgesOptions options;
107 options.output_edge_index = output_edge_index;
108 options.close_loop_with_identical_vertices = close_loop_with_identical_vertices;
109 const span<const Index> edge_span(data.data(), data.size());
110 auto result = directed ? chain_directed_edges<Index>(edge_span, options)
111 : chain_undirected_edges<Index>(edge_span, options);
112 return std::make_tuple(std::move(result.loops), std::move(result.chains));
113 },
114 "edges"_a,
115 nb::kw_only(),
116 "directed"_a,
117 "output_edge_index"_a = ChainEdgesOptions().output_edge_index,
118 "close_loop_with_identical_vertices"_a =
119 ChainEdgesOptions().close_loop_with_identical_vertices,
120 R"(Chain a set of edges into loops and chains.
121
122:param edges: An N x 2 tensor of edge vertex indices.
123:param directed: Whether to treat edges as directed (``[v0, v1]`` goes from ``v0`` to ``v1``) or undirected.
124:param output_edge_index: Whether to return edge indices instead of vertex indices.
125:param close_loop_with_identical_vertices: Whether to repeat the first vertex at the end of each loop. Only applies when ``output_edge_index`` is false.
126
127:returns: A tuple ``(loops, chains)`` of lists of edge or vertex index lists.)");
128
129 nb::enum_<NormalWeightingType>(m, "NormalWeightingType", "Normal weighting type.")
130 .value("Uniform", NormalWeightingType::Uniform, "Uniform weighting")
131 .value(
132 "CornerTriangleArea",
134 "Weight by corner triangle area")
135 .value("Angle", NormalWeightingType::Angle, "Weight by corner angle");
136
137 nb::class_<VertexNormalOptions>(
138 m,
139 "VertexNormalOptions",
140 "Options for computing vertex normals")
141 .def(nb::init<>())
142 .def_rw(
143 "output_attribute_name",
145 "Output attribute name. Default is `@vertex_normal`.")
146 .def_rw(
147 "weight_type",
149 "Weighting type for normal computation. Default is Angle.")
150 .def_rw(
151 "weighted_corner_normal_attribute_name",
153 R"(Precomputed weighted corner normals attribute name (default: @weighted_corner_normal).
154
155If attribute exists, the precomputed weighted corner normal will be used.)")
156 .def_rw(
157 "recompute_weighted_corner_normals",
159 "Whether to recompute weighted corner normals (default: false).")
160 .def_rw(
161 "keep_weighted_corner_normals",
163 "Whether to keep the weighted corner normal attribute (default: false).")
164 .def_rw(
165 "distance_tolerance",
167 "Distance tolerance for degenerate edge check in polygon facets.");
168
169 m.def(
170 "compute_vertex_normal",
172 "mesh"_a,
173 "options"_a = VertexNormalOptions(),
174 R"(Compute vertex normal.
175
176:param mesh: Input mesh.
177:param options: Options for computing vertex normals.
178
179:returns: Vertex normal attribute id.)");
180
181 m.def(
182 "compute_vertex_normal",
183 [](MeshType& mesh,
184 std::optional<std::string_view> output_attribute_name,
185 std::optional<NormalWeightingType> weight_type,
186 std::optional<std::string_view> weighted_corner_normal_attribute_name,
187 std::optional<bool> recompute_weighted_corner_normals,
188 std::optional<bool> keep_weighted_corner_normals,
189 std::optional<float> distance_tolerance) {
190 VertexNormalOptions options;
191 if (output_attribute_name) options.output_attribute_name = *output_attribute_name;
192 if (weight_type) options.weight_type = *weight_type;
193 if (weighted_corner_normal_attribute_name)
194 options.weighted_corner_normal_attribute_name =
195 *weighted_corner_normal_attribute_name;
196 if (recompute_weighted_corner_normals)
197 options.recompute_weighted_corner_normals = *recompute_weighted_corner_normals;
198 if (keep_weighted_corner_normals)
199 options.keep_weighted_corner_normals = *keep_weighted_corner_normals;
200 if (distance_tolerance) options.distance_tolerance = *distance_tolerance;
201
202 return compute_vertex_normal<Scalar, Index>(mesh, options);
203 },
204 "mesh"_a,
205 "output_attribute_name"_a = nb::none(),
206 "weight_type"_a = nb::none(),
207 "weighted_corner_normal_attribute_name"_a = nb::none(),
208 "recompute_weighted_corner_normals"_a = nb::none(),
209 "keep_weighted_corner_normals"_a = nb::none(),
210 "distance_tolerance"_a = nb::none(),
211 R"(Compute vertex normal (Pythonic API).
212
213:param mesh: Input mesh.
214:param output_attribute_name: Output attribute name.
215:param weight_type: Weighting type for normal computation.
216:param weighted_corner_normal_attribute_name: Precomputed weighted corner normals attribute name.
217:param recompute_weighted_corner_normals: Whether to recompute weighted corner normals.
218:param keep_weighted_corner_normals: Whether to keep the weighted corner normal attribute.
219:param distance_tolerance: Distance tolerance for degenerate edge check.
220 (Only used to bypass degenerate edge in polygon facets.)
221
222:returns: Vertex normal attribute id.)");
223
224 nb::class_<FacetNormalOptions>(m, "FacetNormalOptions", "Facet normal computation options.")
225 .def(nb::init<>())
226 .def_rw(
227 "output_attribute_name",
229 "Output attribute name. Default: `@facet_normal`");
230
231 m.def(
232 "compute_facet_normal",
234 "mesh"_a,
235 "options"_a = FacetNormalOptions(),
236 R"(Compute facet normal.
237
238:param mesh: Input mesh.
239:param options: Options for computing facet normals.
240
241:returns: Facet normal attribute id.)");
242
243 m.def(
244 "compute_facet_normal",
245 [](MeshType& mesh, std::optional<std::string_view> output_attribute_name) {
246 FacetNormalOptions options;
247 if (output_attribute_name) options.output_attribute_name = *output_attribute_name;
248 return compute_facet_normal<Scalar, Index>(mesh, options);
249 },
250 "mesh"_a,
251 "output_attribute_name"_a = nb::none(),
252 R"(Compute facet normal (Pythonic API).
253
254:param mesh: Input mesh.
255:param output_attribute_name: Output attribute name.
256
257:returns: Facet normal attribute id.)");
258
259 nb::class_<NormalOptions>(m, "NormalOptions", "Normal computation options.")
260 .def(nb::init<>())
261 .def_rw(
262 "output_attribute_name",
264 "Output attribute name. Default: `@normal`")
265 .def_rw(
266 "weight_type",
268 "Weighting type for normal computation. Default is Angle.")
269 .def_rw(
270 "facet_normal_attribute_name",
272 "Facet normal attribute name to use. Default is `@facet_normal`.")
273 .def_rw(
274 "recompute_facet_normals",
276 "Whether to recompute facet normals. Default is false.")
277 .def_rw(
278 "keep_facet_normals",
280 "Whether to keep the computed facet normal attribute. Default is false.")
281 .def_rw(
282 "distance_tolerance",
284 "Distance tolerance for degenerate edge check. (Only used to bypass degenerate edge in "
285 "polygon facets.)");
286
287 m.def(
288 "compute_normal",
289 [](MeshType& mesh,
290 Scalar feature_angle_threshold,
291 nb::object cone_vertices,
292 std::optional<NormalOptions> normal_options) {
293 NormalOptions options;
294 if (normal_options.has_value()) {
295 options = std::move(normal_options.value());
296 }
297
298 if (cone_vertices.is_none()) {
299 return compute_normal<Scalar, Index>(mesh, feature_angle_threshold, {}, options);
300 } else if (nb::isinstance<nb::list>(cone_vertices)) {
301 auto cone_vertices_list = nb::cast<std::vector<Index>>(cone_vertices);
302 span<const Index> data{cone_vertices_list.data(), cone_vertices_list.size()};
303 return compute_normal<Scalar, Index>(mesh, feature_angle_threshold, data, options);
304 } else if (nb::isinstance<Tensor<Index>>(cone_vertices)) {
305 auto cone_vertices_tensor = nb::cast<Tensor<Index>>(cone_vertices);
306 auto [data, shape, stride] = tensor_to_span(cone_vertices_tensor);
307 la_runtime_assert(is_dense(shape, stride));
308 return compute_normal<Scalar, Index>(mesh, feature_angle_threshold, data, options);
309 } else {
310 throw std::runtime_error("Invalid cone_vertices type");
311 }
312 },
313 "mesh"_a,
314 "feature_angle_threshold"_a = lagrange::internal::pi / 4,
315 "cone_vertices"_a = nb::none(),
316 "options"_a = nb::none(),
317 R"(Compute indexed normal attribute.
318
319Edge with dihedral angles larger than `feature_angle_threshold` are considered as sharp edges.
320Vertices listed in `cone_vertices` are considered as cone vertices, which is always sharp.
321
322:param mesh: input mesh
323:param feature_angle_threshold: feature angle threshold
324:param cone_vertices: cone vertices
325:param options: normal options
326
327:returns: the id of the indexed normal attribute.
328)");
329
330 m.def(
331 "compute_normal",
332 [](MeshType& mesh,
333 Scalar feature_angle_threshold,
334 nb::object cone_vertices,
335 std::optional<std::string_view> output_attribute_name,
336 std::optional<NormalWeightingType> weight_type,
337 std::optional<std::string_view> facet_normal_attribute_name,
338 std::optional<bool> recompute_facet_normals,
339 std::optional<bool> keep_facet_normals,
340 std::optional<float> distance_tolerance) {
341 NormalOptions options;
342 if (output_attribute_name) options.output_attribute_name = *output_attribute_name;
343 if (weight_type) options.weight_type = *weight_type;
344 if (facet_normal_attribute_name)
345 options.facet_normal_attribute_name = *facet_normal_attribute_name;
346 if (recompute_facet_normals) options.recompute_facet_normals = *recompute_facet_normals;
347 if (keep_facet_normals) options.keep_facet_normals = *keep_facet_normals;
348 if (distance_tolerance) options.distance_tolerance = *distance_tolerance;
349
350 if (cone_vertices.is_none()) {
351 return compute_normal<Scalar, Index>(mesh, feature_angle_threshold, {}, options);
352 } else if (nb::isinstance<nb::list>(cone_vertices)) {
353 auto cone_vertices_list = nb::cast<std::vector<Index>>(cone_vertices);
354 span<const Index> data{cone_vertices_list.data(), cone_vertices_list.size()};
355 return compute_normal<Scalar, Index>(mesh, feature_angle_threshold, data, options);
356 } else if (nb::isinstance<Tensor<Index>>(cone_vertices)) {
357 auto cone_vertices_tensor = nb::cast<Tensor<Index>>(cone_vertices);
358 auto [data, shape, stride] = tensor_to_span(cone_vertices_tensor);
359 la_runtime_assert(is_dense(shape, stride));
360 return compute_normal<Scalar, Index>(mesh, feature_angle_threshold, data, options);
361 } else {
362 throw std::runtime_error("Invalid cone_vertices type");
363 }
364 },
365 "mesh"_a,
366 "feature_angle_threshold"_a = lagrange::internal::pi / 4,
367 "cone_vertices"_a = nb::none(),
368 "output_attribute_name"_a = nb::none(),
369 "weight_type"_a = nb::none(),
370 "facet_normal_attribute_name"_a = nb::none(),
371 "recompute_facet_normals"_a = nb::none(),
372 "keep_facet_normals"_a = nb::none(),
373 "distance_tolerance"_a = nb::none(),
374 R"(Compute indexed normal attribute (Pythonic API).
375
376:param mesh: input mesh
377:param feature_angle_threshold: feature angle threshold
378:param cone_vertices: cone vertices
379:param output_attribute_name: output normal attribute name
380:param weight_type: normal weighting type
381:param facet_normal_attribute_name: facet normal attribute name
382:param recompute_facet_normals: whether to recompute facet normals
383:param keep_facet_normals: whether to keep the computed facet normal attribute
384:param distance_tolerance: distance tolerance for degenerate edge check
385 (only used to bypass degenerate edges in polygon facets)
386
387:returns: the id of the indexed normal attribute.)");
388
389 using ConstArray3d = nb::ndarray<const double, nb::shape<-1, 3>, nb::c_contig, nb::device::cpu>;
390 m.def(
391 "compute_pointcloud_pca",
392 [](ConstArray3d points, bool shift_centroid, bool normalize) {
393 ComputePointcloudPCAOptions options;
394 options.shift_centroid = shift_centroid;
395 options.normalize = normalize;
396 PointcloudPCAOutput<Scalar> output =
397 compute_pointcloud_pca<Scalar>({points.data(), points.size()}, options);
398 return std::make_tuple(output.center, output.eigenvectors, output.eigenvalues);
399 },
400 "points"_a,
401 "shift_centroid"_a = ComputePointcloudPCAOptions().shift_centroid,
402 "normalize"_a = ComputePointcloudPCAOptions().normalize,
403 R"(Compute principal components of a point cloud.
404
405:param points: Input points.
406:param shift_centroid: When true: covariance = (P-centroid)^T (P-centroid), when false: covariance = (P)^T (P).
407:param normalize: Should we divide the result by number of points?
408
409:returns: tuple of (center, eigenvectors, eigenvalues).)");
410
411 m.def(
412 "compute_greedy_coloring",
413 [](MeshType& mesh,
414 AttributeElement element_type,
415 size_t num_color_used,
416 std::optional<std::string_view> output_attribute_name) {
417 GreedyColoringOptions options;
418 options.element_type = element_type;
419 options.num_color_used = num_color_used;
420 if (output_attribute_name) options.output_attribute_name = *output_attribute_name;
421 return compute_greedy_coloring<Scalar, Index>(mesh, options);
422 },
423 "mesh"_a,
424 "element_type"_a = AttributeElement::Facet,
425 "num_color_used"_a = 8,
426 "output_attribute_name"_a = nb::none(),
427 R"(Compute greedy coloring of mesh elements.
428
429:param mesh: Input mesh.
430:param element_type: Element type to be colored. Can be either Vertex or Facet.
431:param num_color_used: Initial color palette size. The algorithm allocates more colors when neighbors exhaust the palette, and may use fewer.
432:param output_attribute_name: Output attribute name.
433
434:returns: Color attribute id.)");
435
436 m.def(
437 "normalize_mesh_with_transform",
438 [](MeshType& mesh,
439 bool normalize_normals,
440 bool normalize_tangents_bitangents) -> Eigen::Matrix<Scalar, 4, 4> {
441 TransformOptions options;
442 options.normalize_normals = normalize_normals;
443 options.normalize_tangents_bitangents = normalize_tangents_bitangents;
444 return normalize_mesh_with_transform(mesh, options).matrix();
445 },
446 "mesh"_a,
447 "normalize_normals"_a = TransformOptions().normalize_normals,
448 "normalize_tangents_bitangents"_a = TransformOptions().normalize_tangents_bitangents,
449 R"(Normalize a mesh to fit into a unit box centered at the origin.
450
451:param mesh: Input mesh.
452:param normalize_normals: Whether to normalize normals.
453:param normalize_tangents_bitangents: Whether to normalize tangents and bitangents.
454
455:return Inverse transform, can be used to undo the normalization process.)");
456
457
458 m.def(
459 "normalize_mesh_with_transform_2d",
460 [](MeshType& mesh,
461 bool normalize_normals,
462 bool normalize_tangents_bitangents) -> Eigen::Matrix<Scalar, 3, 3> {
463 TransformOptions options;
464 options.normalize_normals = normalize_normals;
465 options.normalize_tangents_bitangents = normalize_tangents_bitangents;
466 return normalize_mesh_with_transform<2>(mesh, options).matrix();
467 },
468 "mesh"_a,
469 "normalize_normals"_a = TransformOptions().normalize_normals,
470 "normalize_tangents_bitangents"_a = TransformOptions().normalize_tangents_bitangents,
471 R"(Normalize a mesh to fit into a unit box centered at the origin.
472
473:param mesh: Input mesh.
474:param normalize_normals: Whether to normalize normals.
475:param normalize_tangents_bitangents: Whether to normalize tangents and bitangents.
476
477:return Inverse transform, can be used to undo the normalization process.)");
478
479 m.def(
480 "normalize_mesh",
481 [](MeshType& mesh, bool normalize_normals, bool normalize_tangents_bitangents) -> void {
482 TransformOptions options;
483 options.normalize_normals = normalize_normals;
484 options.normalize_tangents_bitangents = normalize_tangents_bitangents;
485 normalize_mesh(mesh, options);
486 },
487 "mesh"_a,
488 "normalize_normals"_a = TransformOptions().normalize_normals,
489 "normalize_tangents_bitangents"_a = TransformOptions().normalize_tangents_bitangents,
490 R"(Normalize a mesh to fit into a unit box centered at the origin.
491
492:param mesh: Input mesh.
493:param normalize_normals: Whether to normalize normals.
494:param normalize_tangents_bitangents: Whether to normalize tangents and bitangents.)");
495
496 m.def(
497 "normalize_meshes_with_transform",
498 [](std::vector<MeshType*> meshes,
499 bool normalize_normals,
500 bool normalize_tangents_bitangents) -> Eigen::Matrix<Scalar, 4, 4> {
501 TransformOptions options;
502 options.normalize_normals = normalize_normals;
503 options.normalize_tangents_bitangents = normalize_tangents_bitangents;
504 span<MeshType*> meshes_span(meshes.data(), meshes.size());
505 return normalize_meshes_with_transform(meshes_span, options).matrix();
506 },
507 "meshes"_a,
508 "normalize_normals"_a = TransformOptions().normalize_normals,
509 "normalize_tangents_bitangents"_a = TransformOptions().normalize_tangents_bitangents,
510 R"(Normalize a mesh to fit into a unit box centered at the origin.
511
512:param meshes: Input meshes.
513:param normalize_normals: Whether to normalize normals.
514:param normalize_tangents_bitangents: Whether to normalize tangents and bitangents.
515
516:return Inverse transform, can be used to undo the normalization process.)");
517
518 m.def(
519 "normalize_meshes_with_transform_2d",
520 [](std::vector<MeshType*> meshes,
521 bool normalize_normals,
522 bool normalize_tangents_bitangents) -> Eigen::Matrix<Scalar, 3, 3> {
523 TransformOptions options;
524 options.normalize_normals = normalize_normals;
525 options.normalize_tangents_bitangents = normalize_tangents_bitangents;
526 span<MeshType*> meshes_span(meshes.data(), meshes.size());
527 return normalize_meshes_with_transform<2>(meshes_span, options).matrix();
528 },
529 "meshes"_a,
530 "normalize_normals"_a = TransformOptions().normalize_normals,
531 "normalize_tangents_bitangents"_a = TransformOptions().normalize_tangents_bitangents,
532 R"(Normalize a mesh to fit into a unit box centered at the origin.
533
534:param meshes: Input meshes.
535:param normalize_normals: Whether to normalize normals.
536:param normalize_tangents_bitangents: Whether to normalize tangents and bitangents.
537
538:return Inverse transform, can be used to undo the normalization process.)");
539
540
541 m.def(
542 "normalize_meshes",
543 [](std::vector<MeshType*> meshes,
544 bool normalize_normals,
545 bool normalize_tangents_bitangents) {
546 TransformOptions options;
547 options.normalize_normals = normalize_normals;
548 options.normalize_tangents_bitangents = normalize_tangents_bitangents;
549 span<MeshType*> meshes_span(meshes.data(), meshes.size());
550 normalize_meshes(meshes_span, options);
551 },
552 "meshes"_a,
553 "normalize_normals"_a = TransformOptions().normalize_normals,
554 "normalize_tangents_bitangents"_a = TransformOptions().normalize_tangents_bitangents,
555 R"(Normalize a list of meshes to fit into a unit box centered at the origin.
556
557:param meshes: Input meshes.
558:param normalize_normals: Whether to normalize normals.
559:param normalize_tangents_bitangents: Whether to normalize tangents and bitangents.)");
560
561 m.def(
562 "combine_meshes",
563 [](std::vector<MeshType*> meshes, bool preserve_vertices) {
565 meshes.size(),
566 [&](size_t i) -> const MeshType& { return *meshes[i]; },
567 preserve_vertices);
568 },
569 "meshes"_a,
570 "preserve_attributes"_a = true,
571 R"(Combine a list of meshes into a single mesh.
572
573:param meshes: Input meshes.
574:param preserve_attributes: Whether to preserve attributes.
575
576:returns: The combined mesh.)");
577
578 m.def(
579 "compute_seam_edges",
580 [](MeshType& mesh,
581 AttributeId indexed_attribute_id,
582 std::optional<std::string_view> output_attribute_name,
583 bool include_boundary_edges) {
584 SeamEdgesOptions options;
585 if (output_attribute_name) options.output_attribute_name = *output_attribute_name;
586 options.include_boundary_edges = include_boundary_edges;
587 return compute_seam_edges<Scalar, Index>(mesh, indexed_attribute_id, options);
588 },
589 "mesh"_a,
590 "indexed_attribute_id"_a,
591 "output_attribute_name"_a = nb::none(),
592 "include_boundary_edges"_a = SeamEdgesOptions().include_boundary_edges,
593 R"(Compute seam edges for a given indexed attribute.
594
595:param mesh: Input mesh.
596:param indexed_attribute_id: Input indexed attribute id.
597:param output_attribute_name: Output attribute name.
598:param include_boundary_edges: If true, boundary edges are also marked as seam edges.
599
600:returns: Attribute id for the output per-edge seam attribute (1 is a seam, 0 is not).)");
601
602 m.def(
603 "orient_outward",
604 [](MeshType& mesh, bool positive) {
605 OrientOptions options;
606 options.positive = positive;
607 orient_outward<Scalar, Index>(mesh, options);
608 },
609 "mesh"_a,
610 "positive"_a = OrientOptions().positive,
611 R"(Orient mesh facets to ensure positive or negative signed volume.
612
613:param mesh: Input mesh.
614:param positive: Whether to orient volumes positively or negatively.)");
615
616 m.def(
617 "unify_index_buffer",
618 [](MeshType& mesh) { return unify_index_buffer(mesh); },
619 "mesh"_a,
620 R"(Unify the index buffer for all indexed attributes.
621
622:param mesh: Input mesh.
623
624:returns: Unified mesh.)");
625
626 m.def(
627 "unify_index_buffer",
629 "mesh"_a,
630 "attribute_ids"_a,
631 R"(Unify the index buffer for selected attributes.
632
633:param mesh: Input mesh.
634:param attribute_ids: Attribute IDs to unify.
635
636:returns: Unified mesh.)");
637
638 m.def(
639 "unify_index_buffer",
641 "mesh"_a,
642 "attribute_names"_a,
643 R"(Unify the index buffer for selected attributes.
644
645:param mesh: Input mesh.
646:param attribute_names: Attribute names to unify.
647
648:returns: Unified mesh.)");
649
650 m.def(
651 "triangulate_polygonal_facets",
652 [](MeshType& mesh,
653 std::string_view scheme,
654 std::optional<std::variant<Tensor<Index>, Tensor<bool>, nb::list>> selected_facets) {
655 lagrange::TriangulationOptions opt;
656 if (scheme == "earcut") {
658 } else if (scheme == "centroid_fan") {
660 } else if (scheme == "delaunay") {
662 } else {
663 throw Error(lagrange::format("Unsupported triangulation scheme {}", scheme));
664 }
665
666 if (!selected_facets.has_value()) {
667 // By default, triangulate every polygonal facet.
669 return;
670 }
671
672 // Build a per-facet mask from either a list/tensor of facet ids or a boolean mask (a
673 // length-num_facets tensor whose `True` entries mark facets to triangulate).
674 const Index num_facets = mesh.get_num_facets();
675 std::vector<uint8_t> should_triangulate(static_cast<size_t>(num_facets), 0);
676 auto mark_ids = [&](span<const Index> ids) {
677 for (Index f : ids) {
678 if (f >= num_facets) {
679 throw Error(
680 lagrange::format(
681 "Facet index {} is out of range (mesh has {} facets)",
682 f,
683 num_facets));
684 }
685 should_triangulate[f] = 1;
686 }
687 };
688 auto& selected = selected_facets.value();
689 if (const auto* list_ptr = std::get_if<nb::list>(&selected)) {
690 auto ids = nb::cast<std::vector<Index>>(*list_ptr);
691 mark_ids({ids.data(), ids.size()});
692 } else if (auto* mask_ptr = std::get_if<Tensor<bool>>(&selected)) {
693 // Boolean per-facet mask: entry `f` is true iff facet `f` should be triangulated.
694 if (mask_ptr->ndim() != 1 ||
695 mask_ptr->shape(0) != static_cast<size_t>(num_facets)) {
696 throw Error(
697 lagrange::format(
698 "Facet mask must be a 1D array of length {} (the number of facets)",
699 num_facets));
700 }
701 // Access the 1D buffer through a typed view (same pattern as
702 // `bind_surface_mesh.h`); Tensor<> enforces C-contiguity.
703 auto mask_view = mask_ptr->template view<bool, nb::ndim<1>>();
704 for (Index f = 0; f < num_facets; ++f) {
705 should_triangulate[f] = mask_view(f) ? 1 : 0;
706 }
707 } else {
708 auto [data, shape, stride] = tensor_to_span(std::get<Tensor<Index>>(selected));
709 la_runtime_assert(is_dense(shape, stride));
710 mark_ids(data);
711 }
712
714 mesh,
715 lagrange::function_ref<bool(Index)>(
716 [&](Index f) { return should_triangulate[f] != 0; }),
717 opt);
718 },
719 "mesh"_a,
720 "scheme"_a = "earcut",
721 "selected_facets"_a = nb::none(),
722 R"(Triangulate polygonal facets of the mesh.
723
724:param mesh: The input mesh to be triangulated in place.
725:param scheme: The triangulation scheme (options are 'earcut', 'centroid_fan', and 'delaunay').
726:param selected_facets: Optional subset of facets to triangulate. Either a list/array of facet ids,
727 or a boolean per-facet mask (a length ``num_facets`` array whose ``True`` entries mark facets to
728 triangulate). Honored by all schemes; facets not selected are left untouched. If omitted, all
729 polygonal facets are triangulated.)");
730
731 nb::enum_<ComponentOptions::ConnectivityType>(m, "ConnectivityType", "Mesh connectivity type")
732 .value(
733 "Vertex",
734 ComponentOptions::ConnectivityType::Vertex,
735 "Two facets are connected if they share a vertex")
736 .value(
737 "Edge",
738 ComponentOptions::ConnectivityType::Edge,
739 "Two facets are connected if they share an edge");
740
741 m.def(
742 "compute_components",
743 [](MeshType& mesh,
744 std::optional<std::string_view> output_attribute_name,
745 std::optional<lagrange::ConnectivityType> connectivity_type,
746 std::optional<nb::list>& blocker_elements) {
747 lagrange::ComponentOptions opt;
748 if (output_attribute_name.has_value()) {
749 opt.output_attribute_name = output_attribute_name.value();
750 }
751 if (connectivity_type.has_value()) {
752 opt.connectivity_type = connectivity_type.value();
753 }
754 std::vector<Index> blocker_elements_vec;
755 if (blocker_elements.has_value()) {
756 for (auto val : blocker_elements.value()) {
757 blocker_elements_vec.push_back(nb::cast<Index>(val));
758 }
759 }
760 return lagrange::compute_components<Scalar, Index>(mesh, blocker_elements_vec, opt);
761 },
762 "mesh"_a,
763 "output_attribute_name"_a = nb::none(),
764 "connectivity_type"_a = nb::none(),
765 "blocker_elements"_a = nb::none(),
766 R"(Compute connected components.
767
768This method will create a per-facet component id attribute named by the `output_attribute_name`
769argument. Each component id is in [0, num_components-1] range.
770
771:param mesh: The input mesh.
772:param output_attribute_name: The name of the output attribute.
773:param connectivity_type: The connectivity type. Either "Vertex" or "Edge".
774:param blocker_elements: The list of blocker element indices. If `connectivity_type` is `Edge`, facets adjacent to a blocker edge are not considered as connected through this edge. If `connectivity_type` is `Vertex`, facets sharing a blocker vertex are not considered as connected through this vertex.
775
776:returns: The total number of components.)");
777
778 nb::class_<VertexValenceOptions>(m, "VertexValenceOptions", "Vertex valence options")
779 .def(nb::init<>())
780 .def_rw(
781 "output_attribute_name",
783 "The name of the output attribute")
784 .def_rw(
785 "induced_by_attribute",
787 "Optional per-edge attribute used as indicator function to restrict the graph used for "
788 "vertex valence computation");
789
790 m.def(
791 "compute_vertex_valence",
793 "mesh"_a,
794 "options"_a = VertexValenceOptions(),
795 R"(Compute vertex valence
796
797:param mesh: The input mesh.
798:param options: The vertex valence options.
799
800:returns: The vertex valence attribute id.)");
801
802 m.def(
803 "compute_vertex_valence",
804 [](MeshType& mesh,
805 std::optional<std::string_view> output_attribute_name,
806 std::optional<std::string_view> induced_by_attribute) {
807 VertexValenceOptions opt;
808 if (output_attribute_name.has_value()) {
809 opt.output_attribute_name = output_attribute_name.value();
810 }
811 if (induced_by_attribute.has_value()) {
812 opt.induced_by_attribute = induced_by_attribute.value();
813 }
815 },
816 "mesh"_a,
817 "output_attribute_name"_a = nb::none(),
818 "induced_by_attribute"_a = nb::none(),
819 R"(Compute vertex valence.
820
821:param mesh: The input mesh.
822:param output_attribute_name: The name of the output attribute.
823:param induced_by_attribute: Optional per-edge attribute used as indicator function to restrict the graph used for vertex valence computation.
824
825:returns: The vertex valence attribute id)");
826
827 nb::class_<TangentBitangentOptions>(m, "TangentBitangentOptions", "Tangent bitangent options")
828 .def(nb::init<>())
829 .def_rw(
830 "tangent_attribute_name",
832 "The name of the output tangent attribute, default is `@tangent`")
833 .def_rw(
834 "bitangent_attribute_name",
836 "The name of the output bitangent attribute, default is `@bitangent`")
837 .def_rw(
838 "uv_attribute_name",
840 "The name of the uv attribute")
841 .def_rw(
842 "normal_attribute_name",
844 "The name of the normal attribute")
845 .def_rw(
846 "output_element_type",
848 "The output element type")
849 .def_rw(
850 "pad_with_sign",
852 "Whether to pad the output tangent/bitangent with sign")
853 .def_rw(
854 "orthogonalize_bitangent",
856 "Whether to compute the bitangent as cross(normal, tangent). If false, the bitangent "
857 "is computed as the derivative of v-coordinate")
858 .def_rw(
859 "keep_existing_tangent",
861 "Whether to recompute tangent if the tangent attribute (specified by "
862 "tangent_attribute_name) already exists. If true, bitangent is computed by normalizing "
863 "cross(normal, tangent) and param orthogonalize_bitangent must be true.");
864 nb::class_<TangentBitangentResult>(m, "TangentBitangentResult", "Tangent bitangent result")
865 .def(nb::init<>())
866 .def_rw(
867 "tangent_id",
869 "The output tangent attribute id")
870 .def_rw(
871 "bitangent_id",
873 "The output bitangent attribute id");
874
875 m.def(
876 "compute_tangent_bitangent",
878 "mesh"_a,
879 "options"_a = TangentBitangentOptions(),
880 R"(Compute tangent and bitangent vector attributes.
881
882:param mesh: The input mesh.
883:param options: The tangent bitangent options.
884
885:returns: The tangent and bitangent attribute ids)");
886
887 m.def(
888 "compute_tangent_bitangent",
889 [](MeshType& mesh,
890 std::optional<std::string_view>(tangent_attribute_name),
891 std::optional<std::string_view>(bitangent_attribute_name),
892 std::optional<std::string_view>(uv_attribute_name),
893 std::optional<std::string_view>(normal_attribute_name),
894 std::optional<AttributeElement>(output_attribute_type),
895 std::optional<bool>(pad_with_sign),
896 std::optional<bool>(orthogonalize_bitangent),
897 std::optional<bool>(keep_existing_tangent)) {
898 TangentBitangentOptions opt;
899 if (tangent_attribute_name.has_value()) {
900 opt.tangent_attribute_name = tangent_attribute_name.value();
901 }
902 if (bitangent_attribute_name.has_value()) {
903 opt.bitangent_attribute_name = bitangent_attribute_name.value();
904 }
905 if (uv_attribute_name.has_value()) {
906 opt.uv_attribute_name = uv_attribute_name.value();
907 }
908 if (normal_attribute_name.has_value()) {
909 opt.normal_attribute_name = normal_attribute_name.value();
910 }
911 if (output_attribute_type.has_value()) {
912 opt.output_element_type = output_attribute_type.value();
913 }
914 if (pad_with_sign.has_value()) {
915 opt.pad_with_sign = pad_with_sign.value();
916 }
917 if (orthogonalize_bitangent.has_value()) {
918 opt.orthogonalize_bitangent = orthogonalize_bitangent.value();
919 }
920 if (keep_existing_tangent.has_value()) {
921 opt.keep_existing_tangent = keep_existing_tangent.value();
922 }
923
925 return std::make_tuple(r.tangent_id, r.bitangent_id);
926 },
927 "mesh"_a,
928 "tangent_attribute_name"_a = nb::none(),
929 "bitangent_attribute_name"_a = nb::none(),
930 "uv_attribute_name"_a = nb::none(),
931 "normal_attribute_name"_a = nb::none(),
932 "output_attribute_type"_a = nb::none(),
933 "pad_with_sign"_a = nb::none(),
934 "orthogonalize_bitangent"_a = nb::none(),
935 "keep_existing_tangent"_a = nb::none(),
936 R"(Compute tangent and bitangent vector attributes (Pythonic API).
937
938:param mesh: The input mesh.
939:param tangent_attribute_name: The name of the output tangent attribute.
940:param bitangent_attribute_name: The name of the output bitangent attribute.
941:param uv_attribute_name: The name of the uv attribute.
942:param normal_attribute_name: The name of the normal attribute.
943:param output_attribute_type: The output element type.
944:param pad_with_sign: Whether to pad the output tangent/bitangent with sign.
945:param orthogonalize_bitangent: Whether to compute the bitangent as sign * cross(normal, tangent).
946:param keep_existing_tangent: Whether to recompute tangent if the tangent attribute (specified by tangent_attribute_name) already exists. If true, bitangent is computed by normalizing cross(normal, tangent) and param orthogonalize_bitangent must be true.
947
948:returns: The tangent and bitangent attribute ids)");
949
950 m.def(
951 "map_attribute",
952 static_cast<AttributeId (*)(MeshType&, AttributeId, std::string_view, AttributeElement)>(
954 "mesh"_a,
955 "old_attribute_id"_a,
956 "new_attribute_name"_a,
957 "new_element"_a,
958 R"(Map an attribute to a new element type.
959
960:param mesh: The input mesh.
961:param old_attribute_id: The id of the input attribute.
962:param new_attribute_name: The name of the new attribute.
963:param new_element: The new element type.
964
965:returns: The id of the new attribute.)");
966
967 m.def(
968 "map_attribute",
969 static_cast<
970 AttributeId (*)(MeshType&, std::string_view, std::string_view, AttributeElement)>(
972 "mesh"_a,
973 "old_attribute_name"_a,
974 "new_attribute_name"_a,
975 "new_element"_a,
976 R"(Map an attribute to a new element type.
977
978:param mesh: The input mesh.
979:param old_attribute_name: The name of the input attribute.
980:param new_attribute_name: The name of the new attribute.
981:param new_element: The new element type.
982
983:returns: The id of the new attribute.)");
984
985 m.def(
986 "map_attribute_in_place",
987 static_cast<AttributeId (*)(MeshType&, AttributeId, AttributeElement)>(
989 "mesh"_a,
990 "id"_a,
991 "new_element"_a,
992 R"(Map an attribute to a new element type in place.
993
994:param mesh: The input mesh.
995:param id: The id of the input attribute.
996:param new_element: The new element type.
997
998:returns: The id of the new attribute.)");
999
1000 m.def(
1001 "map_attribute_in_place",
1002 static_cast<AttributeId (*)(MeshType&, std::string_view, AttributeElement)>(
1004 "mesh"_a,
1005 "name"_a,
1006 "new_element"_a,
1007 R"(Map an attribute to a new element type in place.
1008
1009:param mesh: The input mesh.
1010:param name: The name of the input attribute.
1011:param new_element: The new element type.
1012
1013:returns: The id of the new attribute.)");
1014
1015 nb::class_<FacetAreaOptions>(m, "FacetAreaOptions", "Options for computing facet area.")
1016 .def(nb::init<>())
1017 .def_rw(
1018 "output_attribute_name",
1020 "The name of the output attribute.");
1021
1022 m.def(
1023 "compute_facet_area",
1025 "mesh"_a,
1026 "options"_a = FacetAreaOptions(),
1027 R"(Compute facet area.
1028
1029:param mesh: The input mesh.
1030:param options: The options for computing facet area.
1031
1032:returns: The id of the new attribute.)");
1033
1034 m.def(
1035 "compute_facet_area",
1036 [](MeshType& mesh, std::optional<std::string_view> name) {
1037 FacetAreaOptions opt;
1038 if (name.has_value()) {
1039 opt.output_attribute_name = name.value();
1040 }
1042 },
1043 "mesh"_a,
1044 "output_attribute_name"_a = nb::none(),
1045 R"(Compute facet area (Pythonic API).
1046
1047:param mesh: The input mesh.
1048:param output_attribute_name: The name of the output attribute.
1049
1050:returns: The id of the new attribute.)");
1051
1052 m.def(
1053 "compute_facet_vector_area",
1054 [](MeshType& mesh, std::optional<std::string_view> name) {
1055 FacetVectorAreaOptions opt;
1056 if (name.has_value()) {
1057 opt.output_attribute_name = name.value();
1058 }
1060 },
1061 "mesh"_a,
1062 "output_attribute_name"_a = nb::none(),
1063 R"(Compute facet vector area (Pythonic API).
1064
1065Vector area is defined as the area multiplied by the facet normal.
1066For triangular facets, it is equivalent to half of the cross product of two edges.
1067For non-planar polygonal facets, the vector area offers a robust way to compute the area and normal.
1068The magnitude of the vector area is the largest area of any orthogonal projection of the facet.
1069The direction of the vector area is the normal direction that maximizes the projected area [1, 2].
1070
1071[1] Sullivan, John M. "Curvatures of smooth and discrete surfaces." Discrete differential geometry.
1072Basel: Birkhäuser Basel, 2008. 175-188.
1073
1074[2] Alexa, Marc, and Max Wardetzky. "Discrete Laplacians on general polygonal meshes." ACM SIGGRAPH
10752011 papers. 2011. 1-10.
1076
1077:param mesh: The input mesh.
1078:param output_attribute_name: The name of the output attribute.
1079
1080:returns: The id of the new attribute.)");
1081
1082 nb::class_<MeshAreaOptions>(m, "MeshAreaOptions", "Options for computing mesh area.")
1083 .def(nb::init<>())
1084 .def_rw(
1085 "input_attribute_name",
1087 "The name of the pre-computed facet area attribute, default is `@facet_area`.")
1088 .def_rw(
1089 "use_signed_area",
1091 "Whether to use signed area.");
1092
1093 m.def(
1094 "compute_mesh_area",
1096 "mesh"_a,
1097 "options"_a = MeshAreaOptions(),
1098 R"(Compute mesh area.
1099
1100:param mesh: The input mesh.
1101:param options: The options for computing mesh area.
1102
1103:returns: The mesh area.)");
1104
1105 m.def(
1106 "compute_uv_area",
1108 "mesh"_a,
1109 "options"_a = MeshAreaOptions(),
1110 R"(Compute UV mesh area.
1111
1112:param mesh: The input mesh.
1113:param options: The options for computing mesh area.
1114
1115:returns: The UV mesh area.)");
1116
1117 m.def(
1118 "compute_mesh_area",
1119 [](MeshType& mesh,
1120 std::optional<std::string_view> input_attribute_name,
1121 std::optional<bool> use_signed_area) {
1122 MeshAreaOptions opt;
1123 if (input_attribute_name.has_value()) {
1124 opt.input_attribute_name = input_attribute_name.value();
1125 }
1126 if (use_signed_area.has_value()) {
1127 opt.use_signed_area = use_signed_area.value();
1128 }
1129 return compute_mesh_area(mesh, opt);
1130 },
1131 "mesh"_a,
1132 "input_attribute_name"_a = nb::none(),
1133 "use_signed_area"_a = nb::none(),
1134 R"(Compute mesh area (Pythonic API).
1135
1136:param mesh: The input mesh.
1137:param input_attribute_name: The name of the pre-computed facet area attribute.
1138:param use_signed_area: Whether to use signed area.
1139
1140:returns: The mesh area.)");
1141
1142 nb::class_<FacetCentroidOptions>(m, "FacetCentroidOptions", "Facet centroid options.")
1143 .def(nb::init<>())
1144 .def_rw(
1145 "output_attribute_name",
1147 "The name of the output attribute.");
1148 m.def(
1149 "compute_facet_centroid",
1151 "mesh"_a,
1152 "options"_a = FacetCentroidOptions(),
1153 R"(Compute facet centroid.
1154
1155:param mesh: The input mesh.
1156:param options: The options for computing facet centroid.
1157
1158:returns: The id of the new attribute.)");
1159
1160 m.def(
1161 "compute_facet_centroid",
1162 [](MeshType& mesh, std::optional<std::string_view> output_attribute_name) {
1163 FacetCentroidOptions opt;
1164 if (output_attribute_name.has_value()) {
1165 opt.output_attribute_name = output_attribute_name.value();
1166 }
1168 },
1169 "mesh"_a,
1170 "output_attribute_name"_a = nb::none(),
1171 R"(Compute facet centroid (Pythonic API).
1172
1173:param mesh: Input mesh.
1174:param output_attribute_name: Output attribute name.
1175
1176:returns: Attribute ID.)");
1177
1178 m.def(
1179 "compute_facet_circumcenter",
1180 [](MeshType& mesh, std::optional<std::string_view> output_attribute_name) {
1181 FacetCircumcenterOptions opt;
1182 if (output_attribute_name.has_value()) {
1183 opt.output_attribute_name = output_attribute_name.value();
1184 }
1186 },
1187 "mesh"_a,
1188 "output_attribute_name"_a = nb::none(),
1189 R"(Compute facet circumcenter (Pythonic API).
1190
1191:param mesh: The input mesh.
1192:param output_attribute_name: The name of the output attribute.
1193
1194:returns: The id of the new attribute.)");
1195
1196 nb::enum_<MeshCentroidOptions::WeightingType>(
1197 m,
1198 "CentroidWeightingType",
1199 "Centroid weighting type.")
1200 .value("Uniform", MeshCentroidOptions::Uniform, "Uniform weighting.")
1201 .value("Area", MeshCentroidOptions::Area, "Area weighting.");
1202
1203 nb::class_<MeshCentroidOptions>(m, "MeshCentroidOptions", "Mesh centroid options.")
1204 .def(nb::init<>())
1205 .def_rw("weighting_type", &MeshCentroidOptions::weighting_type, "The weighting type.")
1206 .def_rw(
1207 "facet_centroid_attribute_name",
1209 "The name of the pre-computed facet centroid attribute if available.")
1210 .def_rw(
1211 "facet_area_attribute_name",
1213 "The name of the pre-computed facet area attribute if available.");
1214
1215 m.def(
1216 "compute_mesh_centroid",
1217 [](const MeshType& mesh, MeshCentroidOptions opt) {
1218 const Index dim = mesh.get_dimension();
1219 std::vector<Scalar> centroid(dim, invalid<Scalar>());
1220 compute_mesh_centroid<Scalar, Index>(mesh, centroid, opt);
1221 return centroid;
1222 },
1223 "mesh"_a,
1224 "options"_a = MeshCentroidOptions(),
1225 R"(Compute mesh centroid.
1226
1227:param mesh: Input mesh.
1228:param options: Centroid computation options.
1229
1230:returns: Mesh centroid coordinates.)");
1231
1232 m.def(
1233 "compute_mesh_centroid",
1234 [](MeshType& mesh,
1235 std::optional<MeshCentroidOptions::WeightingType> weighting_type,
1236 std::optional<std::string_view> facet_centroid_attribute_name,
1237 std::optional<std::string_view> facet_area_attribute_name) {
1238 MeshCentroidOptions opt;
1239 if (weighting_type.has_value()) {
1240 opt.weighting_type = weighting_type.value();
1241 }
1242 if (facet_centroid_attribute_name.has_value()) {
1243 opt.facet_centroid_attribute_name = facet_centroid_attribute_name.value();
1244 }
1245 if (facet_area_attribute_name.has_value()) {
1246 opt.facet_area_attribute_name = facet_area_attribute_name.value();
1247 }
1248 const Index dim = mesh.get_dimension();
1249 std::vector<Scalar> centroid(dim, invalid<Scalar>());
1250 compute_mesh_centroid<Scalar, Index>(mesh, centroid, opt);
1251 return centroid;
1252 },
1253 "mesh"_a,
1254 "weighting_type"_a = nb::none(),
1255 "facet_centroid_attribute_name"_a = nb::none(),
1256 "facet_area_attribute_name"_a = nb::none(),
1257 R"(Compute mesh centroid (Pythonic API).
1258
1259:param mesh: Input mesh.
1260:param weighting_type: Weighting type (default: Area).
1261:param facet_centroid_attribute_name: Pre-computed facet centroid attribute name.
1262:param facet_area_attribute_name: Pre-computed facet area attribute name.
1263
1264:returns: Mesh centroid coordinates.)");
1265
1266 m.def(
1267 "permute_vertices",
1268 [](MeshType& mesh, Tensor<Index> new_to_old) {
1269 auto [data, shape, stride] = tensor_to_span(new_to_old);
1270 la_runtime_assert(is_dense(shape, stride));
1272 },
1273 "mesh"_a,
1274 "new_to_old"_a,
1275 R"(Reorder vertices of a mesh in place based on a permutation.
1276
1277:param mesh: input mesh
1278:param new_to_old: permutation vector for vertices)");
1279
1280 m.def(
1281 "permute_facets",
1282 [](MeshType& mesh, Tensor<Index> new_to_old) {
1283 auto [data, shape, stride] = tensor_to_span(new_to_old);
1284 la_runtime_assert(is_dense(shape, stride));
1286 },
1287 "mesh"_a,
1288 "new_to_old"_a,
1289 R"(Reorder facets of a mesh in place based on a permutation.
1290
1291:param mesh: input mesh
1292:param new_to_old: permutation vector for facets)");
1293
1294 nb::enum_<MappingPolicy>(m, "MappingPolicy", "Mapping policy for handling collisions.")
1295 .value("Average", MappingPolicy::Average, "Compute the average of the collided values.")
1296 .value("KeepFirst", MappingPolicy::KeepFirst, "Keep the first collided value.")
1297 .value("Error", MappingPolicy::Error, "Throw an error when collision happens.");
1298
1299 nb::class_<RemapVerticesOptions>(m, "RemapVerticesOptions", "Options for remapping vertices.")
1300 .def(nb::init<>())
1301 .def_rw(
1302 "collision_policy_float",
1304 "The collision policy for float attributes.")
1305 .def_rw(
1306 "collision_policy_integral",
1308 "The collision policy for integral attributes.");
1309
1310 m.def(
1311 "remap_vertices",
1312 [](MeshType& mesh, Tensor<Index> old_to_new, RemapVerticesOptions opt) {
1313 auto [data, shape, stride] = tensor_to_span(old_to_new);
1314 la_runtime_assert(is_dense(shape, stride));
1315 remap_vertices<Scalar, Index>(mesh, data, opt);
1316 },
1317 "mesh"_a,
1318 "old_to_new"_a,
1319 "options"_a = RemapVerticesOptions(),
1320 R"(Remap vertices of a mesh in place based on a permutation.
1321
1322:param mesh: input mesh
1323:param old_to_new: permutation vector for vertices
1324:param options: options for remapping vertices)");
1325
1326 m.def(
1327 "remap_vertices",
1328 [](MeshType& mesh,
1329 Tensor<Index> old_to_new,
1330 std::optional<MappingPolicy> collision_policy_float,
1331 std::optional<MappingPolicy> collision_policy_integral) {
1332 RemapVerticesOptions opt;
1333 if (collision_policy_float.has_value()) {
1334 opt.collision_policy_float = collision_policy_float.value();
1335 }
1336 if (collision_policy_integral.has_value()) {
1337 opt.collision_policy_integral = collision_policy_integral.value();
1338 }
1339 auto [data, shape, stride] = tensor_to_span(old_to_new);
1340 la_runtime_assert(is_dense(shape, stride));
1341 remap_vertices<Scalar, Index>(mesh, data, opt);
1342 },
1343 "mesh"_a,
1344 "old_to_new"_a,
1345 "collision_policy_float"_a = nb::none(),
1346 "collision_policy_integral"_a = nb::none(),
1347 R"(Remap vertices of a mesh in place based on a permutation (Pythonic API).
1348
1349:param mesh: input mesh
1350:param old_to_new: permutation vector for vertices
1351:param collision_policy_float: The collision policy for float attributes.
1352:param collision_policy_integral: The collision policy for integral attributes.)");
1353
1354 m.def(
1355 "reorder_mesh",
1356 [](MeshType& mesh, std::string_view method) {
1357 lagrange::ReorderingMethod reorder_method;
1358 if (method == "Lexicographic" || method == "lexicographic") {
1359 reorder_method = ReorderingMethod::Lexicographic;
1360 } else if (method == "Morton" || method == "morton") {
1361 reorder_method = ReorderingMethod::Morton;
1362 } else if (method == "Hilbert" || method == "hilbert") {
1363 reorder_method = ReorderingMethod::Hilbert;
1364 } else if (method == "None" || method == "none") {
1365 reorder_method = ReorderingMethod::None;
1366 } else {
1367 throw std::runtime_error(lagrange::format("Invalid reordering method: {}", method));
1368 }
1369
1370 lagrange::reorder_mesh(mesh, reorder_method);
1371 },
1372 "mesh"_a,
1373 "method"_a = "Morton",
1374 R"(Reorder a mesh in place.
1375
1376:param mesh: input mesh
1377:param method: reordering method, options are 'Lexicographic', 'Morton', 'Hilbert', 'None' (default is 'Morton').)",
1378 nb::sig(
1379 "def reorder_mesh(mesh: SurfaceMesh, "
1380 "method: typing.Literal['Lexicographic', 'Morton', 'Hilbert', 'None']) -> None"));
1381
1382 m.def(
1383 "separate_by_facet_groups",
1384 [](MeshType& mesh,
1385 Tensor<Index> facet_group_indices,
1386 std::string_view source_vertex_attr_name,
1387 std::string_view source_facet_attr_name,
1388 bool map_attributes) {
1389 SeparateByFacetGroupsOptions options;
1390 options.source_vertex_attr_name = source_vertex_attr_name;
1391 options.source_facet_attr_name = source_facet_attr_name;
1392 options.map_attributes = map_attributes;
1393 auto [data, shape, stride] = tensor_to_span(facet_group_indices);
1394 la_runtime_assert(is_dense(shape, stride));
1395 return separate_by_facet_groups<Scalar, Index>(mesh, data, options);
1396 },
1397 "mesh"_a,
1398 "facet_group_indices"_a,
1399 "source_vertex_attr_name"_a = "",
1400 "source_facet_attr_name"_a = "",
1401 "map_attributes"_a = false,
1402 R"(Extract a set of submeshes based on facet groups.
1403
1404:param mesh: The source mesh.
1405:param facet_group_indices: The group index for each facet. Each group index must be in the range of [0, max(facet_group_indices)]
1406:param source_vertex_attr_name: The optional attribute name to track source vertices.
1407:param source_facet_attr_name: The optional attribute name to track source facets.
1408:param map_attributes: Map attributes from the source to target meshes.
1409
1410:returns: A list of meshes, one for each facet group.
1411)");
1412
1413 m.def(
1414 "separate_by_components",
1415 [](MeshType& mesh,
1416 std::string_view source_vertex_attr_name,
1417 std::string_view source_facet_attr_name,
1418 bool map_attributes,
1419 ConnectivityType connectivity_type) {
1420 SeparateByComponentsOptions options;
1421 options.source_vertex_attr_name = source_vertex_attr_name;
1422 options.source_facet_attr_name = source_facet_attr_name;
1423 options.map_attributes = map_attributes;
1424 options.connectivity_type = connectivity_type;
1425 return separate_by_components(mesh, options);
1426 },
1427 "mesh"_a,
1428 "source_vertex_attr_name"_a = "",
1429 "source_facet_attr_name"_a = "",
1430 "map_attributes"_a = false,
1431 "connectivity_type"_a = ConnectivityType::Edge,
1432 R"(Extract a set of submeshes based on connected components.
1433
1434:param mesh: The source mesh.
1435:param source_vertex_attr_name: The optional attribute name to track source vertices.
1436:param source_facet_attr_name: The optional attribute name to track source facets.
1437:param map_attributes: Map attributes from the source to target meshes.
1438:param connectivity_type: The connectivity used for component computation.
1439
1440:returns: A list of meshes, one for each connected component.
1441)");
1442
1443 m.def(
1444 "extract_submesh",
1445 [](MeshType& mesh,
1446 std::variant<Tensor<Index>, nb::list> selected_facets,
1447 std::string_view source_vertex_attr_name,
1448 std::string_view source_facet_attr_name,
1449 bool map_attributes) {
1450 SubmeshOptions options;
1451 options.source_vertex_attr_name = source_vertex_attr_name;
1452 options.source_facet_attr_name = source_facet_attr_name;
1453 options.map_attributes = map_attributes;
1454 if (std::holds_alternative<nb::list>(selected_facets)) {
1455 auto selected_facets_list =
1456 nb::cast<std::vector<Index>>(std::get<nb::list>(selected_facets));
1457 span<const Index> data{selected_facets_list.data(), selected_facets_list.size()};
1458 return extract_submesh<Scalar, Index>(mesh, data, options);
1459 } else {
1460 auto selected_facets_tensor = std::get<Tensor<Index>>(selected_facets);
1461 auto [data, shape, stride] = tensor_to_span(selected_facets_tensor);
1462 la_runtime_assert(is_dense(shape, stride));
1463 return extract_submesh<Scalar, Index>(mesh, data, options);
1464 }
1465 },
1466 "mesh"_a,
1467 "selected_facets"_a,
1468 "source_vertex_attr_name"_a = "",
1469 "source_facet_attr_name"_a = "",
1470 "map_attributes"_a = false,
1471 R"(Extract a submesh based on the selected facets.
1472
1473:param mesh: The source mesh.
1474:param selected_facets: A list or tensor of facet ids to extract.
1475:param source_vertex_attr_name: The optional attribute name to track source vertices.
1476:param source_facet_attr_name: The optional attribute name to track source facets.
1477:param map_attributes: Map attributes from the source to target meshes.
1478
1479:returns: A mesh that contains only the selected facets.
1480)");
1481
1482 m.def(
1483 "compute_dihedral_angles",
1484 [](MeshType& mesh,
1485 std::optional<std::string_view> output_attribute_name,
1486 std::optional<std::string_view> facet_normal_attribute_name,
1487 std::optional<bool> recompute_facet_normals,
1488 std::optional<bool> keep_facet_normals) {
1489 DihedralAngleOptions options;
1490 if (output_attribute_name.has_value()) {
1491 options.output_attribute_name = output_attribute_name.value();
1492 }
1493 if (facet_normal_attribute_name.has_value()) {
1494 options.facet_normal_attribute_name = facet_normal_attribute_name.value();
1495 }
1496 if (recompute_facet_normals.has_value()) {
1497 options.recompute_facet_normals = recompute_facet_normals.value();
1498 }
1499 if (keep_facet_normals.has_value()) {
1500 options.keep_facet_normals = keep_facet_normals.value();
1501 }
1502 return compute_dihedral_angles(mesh, options);
1503 },
1504 "mesh"_a,
1505 "output_attribute_name"_a = nb::none(),
1506 "facet_normal_attribute_name"_a = nb::none(),
1507 "recompute_facet_normals"_a = nb::none(),
1508 "keep_facet_normals"_a = nb::none(),
1509 R"(Compute dihedral angles for each edge.
1510
1511The dihedral angle of an edge is defined as the angle between the __normals__ of two facets adjacent
1512to the edge. The dihedral angle is always in the range [0, pi] for manifold edges. For boundary
1513edges, the dihedral angle defaults to 0. For non-manifold edges, the dihedral angle is not
1514well-defined and will be set to the special value 2 * π.
1515
1516:param mesh: The source mesh.
1517:param output_attribute_name: The optional edge attribute name to store the dihedral angles.
1518:param facet_normal_attribute_name: The optional attribute name to store the facet normals.
1519:param recompute_facet_normals: Whether to recompute facet normals.
1520:param keep_facet_normals: Whether to keep newly computed facet normals. It has no effect on pre-existing facet normals.
1521
1522:return: The edge attribute id of dihedral angles.)");
1523
1524 m.def(
1525 "compute_edge_lengths",
1526 [](MeshType& mesh, std::optional<std::string_view> output_attribute_name) {
1527 EdgeLengthOptions options;
1528 if (output_attribute_name.has_value())
1529 options.output_attribute_name = output_attribute_name.value();
1530 return compute_edge_lengths(mesh, options);
1531 },
1532 "mesh"_a,
1533 "output_attribute_name"_a = nb::none(),
1534 R"(Compute edge lengths.
1535
1536:param mesh: The source mesh.
1537:param output_attribute_name: The optional edge attribute name to store the edge lengths.
1538
1539:return: The edge attribute id of edge lengths.)");
1540
1541 m.def(
1542 "compute_dijkstra_distance",
1543 [](MeshType& mesh,
1544 Index seed_facet,
1545 const nb::list& barycentric_coords,
1546 std::optional<Scalar> radius,
1547 std::string_view output_attribute_name,
1548 bool output_involved_vertices) {
1549 DijkstraDistanceOptions<Scalar, Index> options;
1550 options.seed_facet = seed_facet;
1551 for (auto val : barycentric_coords) {
1552 options.barycentric_coords.push_back(nb::cast<Scalar>(val));
1553 }
1554 if (radius.has_value()) {
1555 options.radius = radius.value();
1556 }
1557 options.output_attribute_name = output_attribute_name;
1558 options.output_involved_vertices = output_involved_vertices;
1559 return compute_dijkstra_distance(mesh, options);
1560 },
1561 "mesh"_a,
1562 "seed_facet"_a,
1563 "barycentric_coords"_a,
1564 "radius"_a = nb::none(),
1565 "output_attribute_name"_a = DijkstraDistanceOptions<Scalar, Index>{}.output_attribute_name,
1566 "output_involved_vertices"_a =
1567 DijkstraDistanceOptions<Scalar, Index>{}.output_involved_vertices,
1568 R"(Compute Dijkstra distance from a seed facet.
1569
1570:param mesh: The source mesh.
1571:param seed_facet: The seed facet index.
1572:param barycentric_coords: The barycentric coordinates of the seed facet.
1573:param radius: The maximum radius of the dijkstra distance.
1574:param output_attribute_name: The output attribute name to store the dijkstra distance.
1575:param output_involved_vertices: Whether to output the list of involved vertices.)");
1576
1577 m.def(
1578 "weld_indexed_attribute",
1579 [](MeshType& mesh,
1580 AttributeId attribute_id,
1581 std::optional<double> epsilon_rel,
1582 std::optional<double> epsilon_abs,
1583 std::optional<double> angle_abs,
1584 std::optional<std::vector<size_t>> exclude_vertices) {
1585 WeldOptions options;
1586 options.epsilon_rel = epsilon_rel;
1587 options.epsilon_abs = epsilon_abs;
1588 options.angle_abs = angle_abs;
1589 if (exclude_vertices.has_value()) {
1590 const auto& exclude_vertices_vec = exclude_vertices.value();
1591 options.exclude_vertices = {
1592 exclude_vertices_vec.data(),
1593 exclude_vertices_vec.size()};
1594 }
1595 return weld_indexed_attribute(mesh, attribute_id, options);
1596 },
1597 "mesh"_a,
1598 "attribute_id"_a,
1599 "epsilon_rel"_a = nb::none(),
1600 "epsilon_abs"_a = nb::none(),
1601 "angle_abs"_a = nb::none(),
1602 "exclude_vertices"_a = nb::none(),
1603 R"(Weld indexed attribute.
1604
1605:param mesh: The source mesh to be updated in place.
1606:param attribute_id: The indexed attribute id to weld.
1607:param epsilon_rel: The relative tolerance for welding.
1608:param epsilon_abs: The absolute tolerance for welding.
1609:param angle_abs: The absolute angle tolerance for welding.
1610:param exclude_vertices: Optional list of vertex indices to exclude from welding.)");
1611
1612 m.def(
1613 "compute_euler",
1615 "mesh"_a,
1616 R"(Compute the Euler characteristic.
1617
1618:param mesh: The source mesh.
1619
1620:return: The Euler characteristic.)");
1621
1622 m.def(
1623 "is_closed",
1625 "mesh"_a,
1626 R"(Check if the mesh is closed.
1627
1628A mesh is considered closed if it has no boundary edges.
1629
1630:param mesh: The source mesh.
1631
1632:return: Whether the mesh is closed.)");
1633
1634 m.def(
1635 "is_vertex_manifold",
1637 "mesh"_a,
1638 R"(Check if the mesh is vertex manifold.
1639
1640:param mesh: The source mesh.
1641
1642:return: Whether the mesh is vertex manifold.)");
1643
1644 m.def(
1645 "is_edge_manifold",
1647 "mesh"_a,
1648 R"(Check if the mesh is edge manifold.
1649
1650:param mesh: The source mesh.
1651
1652:return: Whether the mesh is edge manifold.)");
1653
1654 m.def("is_manifold", &is_manifold<Scalar, Index>, "mesh"_a, R"(Check if the mesh is manifold.
1655
1656A mesh considered as manifold if it is both vertex and edge manifold.
1657
1658:param mesh: The source mesh.
1659
1660:return: Whether the mesh is manifold.)");
1661
1662 m.def(
1663 "compute_vertex_is_manifold",
1664 [](MeshType& mesh, std::string_view output_attribute_name) {
1665 VertexManifoldOptions options;
1666 options.output_attribute_name = output_attribute_name;
1667 return compute_vertex_is_manifold(mesh, options);
1668 },
1669 "mesh"_a,
1670 "output_attribute_name"_a = VertexManifoldOptions().output_attribute_name,
1671 R"(Compute whether each vertex is manifold.
1672
1673A vertex is considered manifold if its one-ring neighborhood is homeomorphic to a disk.
1674
1675:param mesh: The source mesh.
1676:param output_attribute_name: The output vertex attribute name.
1677
1678:return: The attribute id of a vertex attribute indicating whether a vertex is manifold.)");
1679
1680 m.def(
1681 "compute_edge_is_manifold",
1682 [](MeshType& mesh, std::string_view output_attribute_name) {
1683 EdgeManifoldOptions options;
1684 options.output_attribute_name = output_attribute_name;
1685 return compute_edge_is_manifold(mesh, options);
1686 },
1687 "mesh"_a,
1688 "output_attribute_name"_a = EdgeManifoldOptions().output_attribute_name,
1689 R"(Compute whether each edge is manifold.
1690
1691An edge is considered manifold if it is adjacent to one or two facets.
1692
1693:param mesh: The source mesh.
1694:param output_attribute_name: The output edge attribute name.
1695
1696:return: The attribute id of an edge attribute indicating whether an edge is manifold.)");
1697
1698 m.def(
1699 "is_oriented",
1701 "mesh"_a,
1702 R"(Check if the mesh is oriented.
1703
1704A mesh is oriented if all interior edges are oriented. An interior edge is considered as
1705oriented if it has the same number of half-edges for each edge direction. I.e. the number of
1706facets that use the edge in one direction equals the number of facets that use the edge in the
1707opposite direction. Boundary edges are always considered as oriented.
1708
1709:param mesh: The source mesh.
1710
1711:return: Whether the mesh is oriented.)");
1712
1713 m.def(
1714 "compute_edge_is_oriented",
1715 [](MeshType& mesh, std::string_view output_attribute_name) {
1716 OrientationOptions options;
1717 options.output_attribute_name = output_attribute_name;
1718 return compute_edge_is_oriented(mesh, options);
1719 },
1720 "mesh"_a,
1721 "output_attribute_name"_a = OrientationOptions().output_attribute_name,
1722 R"(Compute whether each edge is oriented.
1723
1724An interior edge is considered as oriented if it has the same number of half-edges for each edge
1725direction. I.e. the number of facets that use the edge in one direction equals to the number of
1726facets that use the edge in the opposite direction. Boundary edges are always considered as
1727oriented.
1728
1729:param mesh: The source mesh.
1730:param output_attribute_name: The output edge attribute name.
1731
1732:return: The attribute id of an edge attribute indicating whether an edge is oriented.)");
1733
1734 m.def(
1735 "transform_mesh",
1736 [](MeshType& mesh,
1737 StubType<Eigen::Matrix<Scalar, 4, 4>, ArrayLikeHint> affine_transform,
1738 bool normalize_normals,
1739 bool normalize_tangents_bitangents,
1740 bool reorient,
1741 bool in_place) -> std::optional<MeshType> {
1742 Eigen::Transform<Scalar, 3, Eigen::Affine> M(affine_transform.value);
1743 TransformOptions options;
1744 options.normalize_normals = normalize_normals;
1745 options.normalize_tangents_bitangents = normalize_tangents_bitangents;
1746 options.reorient = reorient;
1747
1748 std::optional<MeshType> result;
1749 if (in_place) {
1750 transform_mesh(mesh, M, options);
1751 } else {
1752 result = transformed_mesh(mesh, M, options);
1753 }
1754 return result;
1755 },
1756 "mesh"_a,
1757 "affine_transform"_a,
1758 nb::kw_only(),
1759 "normalize_normals"_a = TransformOptions().normalize_normals,
1760 "normalize_tangents_bitangents"_a = TransformOptions().normalize_tangents_bitangents,
1761 "reorient"_a = TransformOptions().reorient,
1762 "in_place"_a = true,
1763 R"(Apply affine transformation to a mesh.
1764
1765:param mesh: Input mesh.
1766:param affine_transform: Affine transformation matrix.
1767:param normalize_normals: Whether to normalize normals.
1768:param normalize_tangents_bitangents: Whether to normalize tangents and bitangents.
1769:param reorient: If the transform has a negative determinant, flip facets and reorient attributes (normals, tangents, bitangents).
1770:param in_place: Whether to apply transformation in place.
1771
1772:returns: Transformed mesh if in_place is False.)");
1773
1774 nb::enum_<DistortionMetric>(m, "DistortionMetric", "Distortion metric.")
1775 .value("Dirichlet", DistortionMetric::Dirichlet, "Dirichlet energy")
1776 .value("InverseDirichlet", DistortionMetric::InverseDirichlet, "Inverse Dirichlet energy")
1777 .value(
1778 "SymmetricDirichlet",
1780 "Symmetric Dirichlet energy")
1781 .value("AreaRatio", DistortionMetric::AreaRatio, "Area ratio")
1782 .value("MIPS", DistortionMetric::MIPS, "Most isotropic parameterization energy");
1783
1784 m.def(
1785 "compute_uv_distortion",
1786 [](MeshType& mesh,
1787 std::string_view uv_attribute_name,
1788 std::string_view output_attribute_name,
1789 DistortionMetric metric) {
1790 UVDistortionOptions opt;
1791 opt.uv_attribute_name = uv_attribute_name;
1792 opt.output_attribute_name = output_attribute_name;
1793 opt.metric = metric;
1794 return compute_uv_distortion(mesh, opt);
1795 },
1796 "mesh"_a,
1797 "uv_attribute_name"_a = "@uv",
1798 "output_attribute_name"_a = "@uv_measure",
1800 R"(Compute UV distortion.
1801
1802:param mesh: Input mesh.
1803:param uv_attribute_name: UV attribute name (default: "@uv").
1804:param output_attribute_name: Output attribute name (default: "@uv_measure").
1805:param metric: Distortion metric (default: MIPS).
1806
1807:returns: Facet attribute ID for distortion.)");
1808
1809 m.def(
1810 "trim_by_isoline",
1811 [](const MeshType& mesh,
1812 std::variant<AttributeId, std::string_view> attribute,
1813 double isovalue,
1814 bool keep_below,
1815 bool keep_attributes) {
1816 IsolineOptions opt;
1817 if (std::holds_alternative<AttributeId>(attribute)) {
1818 opt.attribute_id = std::get<AttributeId>(attribute);
1819 } else {
1820 opt.attribute_id = mesh.get_attribute_id(std::get<std::string_view>(attribute));
1821 }
1822 opt.isovalue = isovalue;
1823 opt.keep_below = keep_below;
1824 opt.keep_attributes = keep_attributes;
1825 return trim_by_isoline(mesh, opt);
1826 },
1827 "mesh"_a,
1828 "attribute"_a,
1829 "isovalue"_a = IsolineOptions().isovalue,
1830 "keep_below"_a = IsolineOptions().keep_below,
1831 "keep_attributes"_a = IsolineOptions().keep_attributes,
1832 R"(Trim a triangle mesh by an isoline.
1833
1834:param mesh: Input triangle mesh.
1835:param attribute: Attribute ID or name of scalar field (vertex or indexed).
1836:param isovalue: Isovalue to trim with.
1837:param keep_below: Whether to keep the part below the isoline.
1838:param keep_attributes: Whether to propagate input mesh attributes to the output mesh.
1839
1840:returns: Trimmed mesh.)");
1841
1842 m.def(
1843 "extract_isoline",
1844 [](const MeshType& mesh,
1845 std::variant<AttributeId, std::string_view> attribute,
1846 double isovalue,
1847 bool keep_attributes) {
1848 IsolineOptions opt;
1849 if (std::holds_alternative<AttributeId>(attribute)) {
1850 opt.attribute_id = std::get<AttributeId>(attribute);
1851 } else {
1852 opt.attribute_id = mesh.get_attribute_id(std::get<std::string_view>(attribute));
1853 }
1854 opt.isovalue = isovalue;
1855 opt.keep_attributes = keep_attributes;
1856 return extract_isoline(mesh, opt);
1857 },
1858 "mesh"_a,
1859 "attribute"_a,
1860 "isovalue"_a = IsolineOptions().isovalue,
1861 "keep_attributes"_a = IsolineOptions().keep_attributes,
1862 R"(Extract the isoline of an implicit function defined on the mesh vertices/corners.
1863
1864The input mesh must be a triangle mesh.
1865
1866:param mesh: Input triangle mesh to extract the isoline from.
1867:param attribute: Attribute id or name of the scalar field to use. Can be a vertex or indexed attribute.
1868:param isovalue: Isovalue to extract.
1869:param keep_attributes: Whether to propagate input mesh attributes to the output mesh.
1870
1871:return: A mesh whose facets is a collection of size 2 elements representing the extracted isoline.)");
1872
1873 m.def(
1874 "insert_isoline",
1875 [](const MeshType& mesh,
1876 std::variant<AttributeId, std::string_view> attribute,
1877 double isovalue,
1878 bool keep_attributes) {
1879 IsolineOptions opt;
1880 if (std::holds_alternative<AttributeId>(attribute)) {
1881 opt.attribute_id = std::get<AttributeId>(attribute);
1882 } else {
1883 opt.attribute_id = mesh.get_attribute_id(std::get<std::string_view>(attribute));
1884 }
1885 opt.isovalue = isovalue;
1886 opt.keep_attributes = keep_attributes;
1887 return insert_isoline(mesh, opt);
1888 },
1889 "mesh"_a,
1890 "attribute"_a,
1891 "isovalue"_a = IsolineOptions().isovalue,
1892 "keep_attributes"_a = IsolineOptions().keep_attributes,
1893 R"(Insert the isoline of an implicit function into a triangle mesh.
1894
1895Unlike trimming, the whole mesh is retained; facets crossed by the isoline are split so that the
1896isoline appears as a chain of edges in the output. A triangle crossed in its interior is split into
1897a triangle and a quad, so the output is in general a mixed triangle/quad mesh. When the isoline
1898passes exactly through an existing vertex (or lies along an edge), the split degenerates: the
1899triangle may instead be split into two triangles, or left unchanged.
1900
1901:param mesh: Input triangle mesh to insert the isoline into.
1902:param attribute: Attribute id or name of the scalar field to use. Can be a vertex or indexed attribute.
1903:param isovalue: Isovalue to insert.
1904:param keep_attributes: Whether to propagate input mesh attributes to the output mesh.
1905
1906:return: The input mesh with the isoline inserted as a chain of edges.)");
1907
1908 using AttributeNameOrId = AttributeFilter::AttributeNameOrId;
1909 m.def(
1910 "filter_attributes",
1911 [](MeshType& mesh,
1912 std::optional<std::vector<AttributeNameOrId>> included_attributes,
1913 std::optional<std::vector<AttributeNameOrId>> excluded_attributes,
1914 StubType<std::optional<std::unordered_set<AttributeUsage>>, IterableUsageHint>
1915 included_usages,
1916 StubType<std::optional<std::unordered_set<AttributeElement>>, IterableElementHint>
1917 included_element_types) {
1918 AttributeFilter filter;
1919 if (included_attributes.has_value()) {
1920 filter.included_attributes = included_attributes.value();
1921 }
1922 if (excluded_attributes.has_value()) {
1923 filter.excluded_attributes = excluded_attributes.value();
1924 }
1925 if (included_usages.value.has_value()) {
1926 filter.included_usages.clear_all();
1927 for (auto usage : included_usages.value.value()) {
1928 filter.included_usages.set(usage);
1929 }
1930 }
1931 if (included_element_types.value.has_value()) {
1932 filter.included_element_types.clear_all();
1933 for (auto element_type : included_element_types.value.value()) {
1934 filter.included_element_types.set(element_type);
1935 }
1936 }
1937 return filter_attributes(mesh, filter);
1938 },
1939 "mesh"_a,
1940 "included_attributes"_a = nb::none(),
1941 "excluded_attributes"_a = nb::none(),
1942 "included_usages"_a = nb::none(),
1943 "included_element_types"_a = nb::none(),
1944 R"(Filters the attributes of mesh according to user specifications.
1945
1946:param mesh: Input mesh.
1947:param included_attributes: List of attribute names or ids to include. By default, all attributes are included.
1948:param excluded_attributes: List of attribute names or ids to exclude. By default, no attribute is excluded.
1949:param included_usages: List of attribute usages to include. By default, all usages are included.
1950:param included_element_types: List of attribute element types to include. By default, all element types are included.)");
1951
1952 m.def(
1953 "cast_attribute",
1954 [](MeshType& mesh,
1955 std::variant<AttributeId, std::string_view> input_attribute,
1956 nb::type_object dtype,
1957 std::optional<std::string_view> output_attribute_name) {
1959 auto cast = [&](AttributeId attr_id) {
1960 auto np = nb::module_::import_("numpy");
1961 if (output_attribute_name.has_value()) {
1962 auto name = output_attribute_name.value();
1963 if (dtype.is(&PyFloat_Type)) {
1964 // Native python float is a C double.
1965 return cast_attribute<double>(mesh, attr_id, name);
1966 } else if (dtype.is(&PyLong_Type)) {
1967 // Native python int maps to int64.
1968 return cast_attribute<int64_t>(mesh, attr_id, name);
1969 } else if (dtype.is(np.attr("float32"))) {
1970 return cast_attribute<float>(mesh, attr_id, name);
1971 } else if (dtype.is(np.attr("float64"))) {
1972 return cast_attribute<double>(mesh, attr_id, name);
1973 } else if (dtype.is(np.attr("int8"))) {
1974 return cast_attribute<int8_t>(mesh, attr_id, name);
1975 } else if (dtype.is(np.attr("int16"))) {
1976 return cast_attribute<int16_t>(mesh, attr_id, name);
1977 } else if (dtype.is(np.attr("int32"))) {
1978 return cast_attribute<int32_t>(mesh, attr_id, name);
1979 } else if (dtype.is(np.attr("int64"))) {
1980 return cast_attribute<int64_t>(mesh, attr_id, name);
1981 } else if (dtype.is(np.attr("uint8"))) {
1982 return cast_attribute<uint8_t>(mesh, attr_id, name);
1983 } else if (dtype.is(np.attr("uint16"))) {
1984 return cast_attribute<uint16_t>(mesh, attr_id, name);
1985 } else if (dtype.is(np.attr("uint32"))) {
1986 return cast_attribute<uint32_t>(mesh, attr_id, name);
1987 } else if (dtype.is(np.attr("uint64"))) {
1988 return cast_attribute<uint64_t>(mesh, attr_id, name);
1989 } else {
1990 throw nb::type_error("Unsupported `dtype`!");
1991 }
1992 } else {
1993 if (dtype.is(&PyFloat_Type)) {
1994 // Native python float is a C double.
1995 return cast_attribute_in_place<double>(mesh, attr_id);
1996 } else if (dtype.is(&PyLong_Type)) {
1997 // Native python int maps to int64.
1998 return cast_attribute_in_place<int64_t>(mesh, attr_id);
1999 } else if (dtype.is(np.attr("float32"))) {
2000 return cast_attribute_in_place<float>(mesh, attr_id);
2001 } else if (dtype.is(np.attr("float64"))) {
2002 return cast_attribute_in_place<double>(mesh, attr_id);
2003 } else if (dtype.is(np.attr("int8"))) {
2004 return cast_attribute_in_place<int8_t>(mesh, attr_id);
2005 } else if (dtype.is(np.attr("int16"))) {
2006 return cast_attribute_in_place<int16_t>(mesh, attr_id);
2007 } else if (dtype.is(np.attr("int32"))) {
2008 return cast_attribute_in_place<int32_t>(mesh, attr_id);
2009 } else if (dtype.is(np.attr("int64"))) {
2010 return cast_attribute_in_place<int64_t>(mesh, attr_id);
2011 } else if (dtype.is(np.attr("uint8"))) {
2012 return cast_attribute_in_place<uint8_t>(mesh, attr_id);
2013 } else if (dtype.is(np.attr("uint16"))) {
2014 return cast_attribute_in_place<uint16_t>(mesh, attr_id);
2015 } else if (dtype.is(np.attr("uint32"))) {
2016 return cast_attribute_in_place<uint32_t>(mesh, attr_id);
2017 } else if (dtype.is(np.attr("uint64"))) {
2018 return cast_attribute_in_place<uint64_t>(mesh, attr_id);
2019 } else {
2020 throw nb::type_error("Unsupported `dtype`!");
2021 }
2022 }
2023 };
2024
2025 if (std::holds_alternative<AttributeId>(input_attribute)) {
2026 return cast(std::get<AttributeId>(input_attribute));
2027 } else {
2028 AttributeId id = mesh.get_attribute_id(std::get<std::string_view>(input_attribute));
2029 return cast(id);
2030 }
2031 },
2032 "mesh"_a,
2033 "input_attribute"_a,
2034 "dtype"_a,
2035 "output_attribute_name"_a = nb::none(),
2036 R"(Cast an attribute to a new dtype.
2037
2038:param mesh: The input mesh.
2039:param input_attribute: The input attribute id or name.
2040:param dtype: The new dtype.
2041:param output_attribute_name: The output attribute name. If none, cast will replace the input attribute.
2042
2043:returns: The id of the new attribute.)");
2044
2045 m.def(
2046 "get_unique_attribute_name",
2047 [](const MeshType& mesh,
2048 std::string_view name,
2049 std::string separator,
2050 std::string postfix,
2051 int max_increment,
2052 bool emit_warning) {
2053 UniqueAttributeNameOptions options;
2054 options.separator = std::move(separator);
2055 options.postfix = std::move(postfix);
2056 options.max_increment = max_increment;
2057 options.emit_warning = emit_warning;
2058 return get_unique_attribute_name(mesh, name, options);
2059 },
2060 "mesh"_a,
2061 "name"_a,
2062 "separator"_a = UniqueAttributeNameOptions().separator,
2063 "postfix"_a = UniqueAttributeNameOptions().postfix,
2064 "max_increment"_a = UniqueAttributeNameOptions().max_increment,
2065 "emit_warning"_a = UniqueAttributeNameOptions().emit_warning,
2066 R"(Get a unique attribute name for a mesh.
2067
2068If the desired name does not exist on the mesh it is returned as-is. If it
2069already exists, a suffix of the form ``{separator}{count}{postfix}`` is appended
2070until a unique name is found. An exception is raised if no unique name can be
2071found after ``max_increment`` attempts.
2072
2073:param mesh: The input mesh.
2074:param name: The desired attribute name.
2075:param separator: Separator between the base name and counter (default: ".").
2076:param postfix: Postfix to append after the counter (default: "").
2077:param max_increment: Maximum number of attempts to find a unique name (default: 1000).
2078:param emit_warning: Whether to log a warning when a collision is detected (default: True).
2079
2080:returns: A unique attribute name.)");
2081
2082 m.def(
2083 "compute_mesh_covariance",
2084 [](MeshType& mesh,
2085 StubType<std::array<Scalar, 3>, ArrayLikeHint> center,
2086 std::optional<std::string_view> active_facets_attribute_name)
2087 -> std::array<std::array<Scalar, 3>, 3> {
2088 MeshCovarianceOptions options;
2089 options.center = center.value;
2090 options.active_facets_attribute_name = active_facets_attribute_name;
2091 return compute_mesh_covariance<Scalar, Index>(mesh, options);
2092 },
2093 "mesh"_a,
2094 "center"_a,
2095 "active_facets_attribute_name"_a = nb::none(),
2096 R"(Compute the covariance matrix of a mesh w.r.t. a center (Pythonic API).
2097
2098:param mesh: Input mesh.
2099:param center: The center of the covariance computation.
2100:param active_facets_attribute_name: (optional) Attribute name of whether a facet should be considered in the computation.
2101
2102:returns: The 3 by 3 covariance matrix, which should be symmetric.)");
2103
2104 m.def(
2105 "select_facets_by_normal_similarity",
2106 [](MeshType& mesh,
2107 Index seed_facet_id,
2108 std::optional<double> flood_error_limit,
2109 std::optional<double> flood_second_to_first_order_limit_ratio,
2110 std::optional<std::string_view> facet_normal_attribute_name,
2111 std::optional<std::string_view> is_facet_selectable_attribute_name,
2112 std::optional<std::string_view> output_attribute_name,
2113 std::optional<std::string_view> search_type,
2114 std::optional<int> num_smooth_iterations) {
2115 // Set options in the C++ struct
2116 SelectFacetsByNormalSimilarityOptions options;
2117 if (flood_error_limit.has_value())
2118 options.flood_error_limit = flood_error_limit.value();
2119 if (flood_second_to_first_order_limit_ratio.has_value())
2120 options.flood_second_to_first_order_limit_ratio =
2121 flood_second_to_first_order_limit_ratio.value();
2122 if (facet_normal_attribute_name.has_value())
2123 options.facet_normal_attribute_name = facet_normal_attribute_name.value();
2124 if (is_facet_selectable_attribute_name.has_value()) {
2125 options.is_facet_selectable_attribute_name = is_facet_selectable_attribute_name;
2126 }
2127 if (output_attribute_name.has_value())
2128 options.output_attribute_name = output_attribute_name.value();
2129 if (search_type.has_value()) {
2130 if (search_type.value() == "BFS")
2132 else if (search_type.value() == "DFS")
2134 else
2135 throw std::runtime_error(
2136 lagrange::format("Invalid search type: {}", search_type.value()));
2137 }
2138 if (num_smooth_iterations.has_value())
2139 options.num_smooth_iterations = num_smooth_iterations.value();
2140
2141 return select_facets_by_normal_similarity<Scalar, Index>(mesh, seed_facet_id, options);
2142 },
2143 "mesh"_a, /* `_a` is a literal for nanobind to create nb::args, a required argument */
2144 "seed_facet_id"_a,
2145 "flood_error_limit"_a = nb::none(),
2146 "flood_second_to_first_order_limit_ratio"_a = nb::none(),
2147 "facet_normal_attribute_name"_a = nb::none(),
2148 "is_facet_selectable_attribute_name"_a = nb::none(),
2149 "output_attribute_name"_a = nb::none(),
2150 "search_type"_a = nb::none(),
2151 "num_smooth_iterations"_a = nb::none(),
2152 R"(Select facets by normal similarity (Pythonic API).
2153
2154:param mesh: Input mesh.
2155:param seed_facet_id: Index of the seed facet.
2156:param flood_error_limit: Tolerance for normals of the seed and the selected facets. Higher limit leads to larger selected region.
2157:param flood_second_to_first_order_limit_ratio: Ratio of the flood_error_limit and the tolerance for normals of neighboring selected facets. Higher ratio leads to more curvature in selected region.
2158:param facet_normal_attribute_name: Attribute name of the facets normal. If the mesh doesn't have this attribute, it will call compute_facet_normal to compute it.
2159:param is_facet_selectable_attribute_name: If provided, this function will look for this attribute to determine if a facet is selectable.
2160:param output_attribute_name: Attribute name of whether a facet is selected.
2161:param search_type: Use 'BFS' for breadth-first search or 'DFS' for depth-first search.
2162:param num_smooth_iterations: Number of iterations to smooth the boundary of the selected region.
2163
2164:returns: Id of the attribute on whether a facet is selected.)",
2165 nb::sig(
2166 "def select_facets_by_normal_similarity(mesh: SurfaceMesh, "
2167 "seed_facet_id: int, "
2168 "flood_error_limit: typing.Optional[float] = None, "
2169 "flood_second_to_first_order_limit_ratio: typing.Optional[float] = None, "
2170 "facet_normal_attribute_name: typing.Optional[str] = None, "
2171 "is_facet_selectable_attribute_name: typing.Optional[str] = None, "
2172 "output_attribute_name: typing.Optional[str] = None, "
2173 "search_type: typing.Optional[typing.Literal['BFS', 'DFS']] = None,"
2174 "num_smooth_iterations: typing.Optional[int] = None) -> int"));
2175
2176 m.def(
2177 "select_facets_in_frustum",
2178 [](MeshType& mesh,
2179 StubType<std::array<std::array<Scalar, 3>, 4>, ArrayLikeHint> frustum_plane_points,
2180 StubType<std::array<std::array<Scalar, 3>, 4>, ArrayLikeHint> frustum_plane_normals,
2181 std::optional<bool> greedy,
2182 std::optional<std::string_view> output_attribute_name) {
2183 // Set options in the C++ struct
2184 Frustum<Scalar> frustum;
2185 for (size_t i = 0; i < 4; ++i) {
2186 frustum.planes[i].point = frustum_plane_points.value[i];
2187 frustum.planes[i].normal = frustum_plane_normals.value[i];
2188 }
2189 FrustumSelectionOptions options;
2190 if (greedy.has_value()) options.greedy = greedy.value();
2191 if (output_attribute_name.has_value())
2192 options.output_attribute_name = output_attribute_name.value();
2193
2194 return select_facets_in_frustum<Scalar, Index>(mesh, frustum, options);
2195 },
2196 "mesh"_a,
2197 "frustum_plane_points"_a,
2198 "frustum_plane_normals"_a,
2199 "greedy"_a = nb::none(),
2200 "output_attribute_name"_a = nb::none(),
2201 R"(Select facets in a frustum (Pythonic API).
2202
2203:param mesh: Input mesh.
2204:param frustum_plane_points: Four points on each of the frustum planes.
2205:param frustum_plane_normals: Four normals of each of the frustum planes.
2206:param greedy: If true, the function returns as soon as the first facet is found.
2207:param output_attribute_name: Attribute name of whether a facet is selected.
2208
2209:returns: Whether any facets got selected.)");
2210
2211 m.def(
2212 "thicken_and_close_mesh",
2213 [](MeshType& mesh,
2214 std::optional<Scalar> offset_amount,
2215 std::variant<std::monostate, std::array<double, 3>, std::string_view> direction,
2216 std::optional<double> mirror_ratio,
2217 std::optional<size_t> num_segments,
2218 std::optional<std::vector<std::string>> indexed_attributes) {
2219 ThickenAndCloseOptions options;
2220
2221 if (auto array_val = std::get_if<std::array<double, 3>>(&direction)) {
2222 options.direction = *array_val;
2223 } else if (auto string_val = std::get_if<std::string_view>(&direction)) {
2224 options.direction = *string_val;
2225 }
2226 options.offset_amount = offset_amount.value_or(options.offset_amount);
2227 options.mirror_ratio = std::move(mirror_ratio);
2228 options.num_segments = num_segments.value_or(options.num_segments);
2229 options.indexed_attributes = indexed_attributes.value_or(options.indexed_attributes);
2230
2231 return thicken_and_close_mesh<Scalar, Index>(mesh, options);
2232 },
2233 "mesh"_a,
2234 "offset_amount"_a = nb::none(),
2235 "direction"_a = nb::none(),
2236 "mirror_ratio"_a = nb::none(),
2237 "num_segments"_a = nb::none(),
2238 "indexed_attributes"_a = nb::none(),
2239 R"(Thicken a mesh by offsetting it, and close the shape into a thick 3D solid.
2240
2241:param mesh: Input mesh.
2242:param direction: Direction of the offset. Can be an attribute name or a fixed 3D vector.
2243:param offset_amount: Amount of offset.
2244:param mirror_ratio: Ratio of the offset amount to mirror the mesh.
2245:param num_segments: Number of segments to use for the thickening.
2246:param indexed_attributes: List of indexed attributes to copy to the new mesh.
2247
2248:returns: The thickened and closed mesh.)");
2249
2250 m.def(
2251 "extract_boundary_loops",
2253 "mesh"_a,
2254 R"(Extract boundary loops from a mesh.
2255
2256:param mesh: Input mesh.
2257
2258:returns: A list of boundary loops, each represented as a list of vertex indices.)");
2259
2260 m.def(
2261 "extract_boundary_edges",
2262 [](MeshType& mesh) {
2263 mesh.initialize_edges();
2264 Index num_edges = mesh.get_num_edges();
2265 std::vector<Index> bd_edges;
2266 bd_edges.reserve(num_edges);
2267 for (Index ei = 0; ei < num_edges; ++ei) {
2268 if (mesh.is_boundary_edge(ei)) {
2269 bd_edges.push_back(ei);
2270 }
2271 }
2272 return bd_edges;
2273 },
2274 "mesh"_a,
2275 R"(Extract boundary edges from a mesh.
2276
2277:param mesh: Input mesh.
2278
2279:returns: A list of boundary edge indices.)");
2280
2281 m.def(
2282 "compute_uv_charts",
2283 [](MeshType& mesh,
2284 std::string_view uv_attribute_name,
2285 std::string_view output_attribute_name,
2286 std::string_view connectivity_type) {
2287 UVChartOptions options;
2288 options.uv_attribute_name = uv_attribute_name;
2289 options.output_attribute_name = output_attribute_name;
2290 if (connectivity_type == "Vertex") {
2291 options.connectivity_type = UVChartOptions::ConnectivityType::Vertex;
2292 } else if (connectivity_type == "Edge") {
2293 options.connectivity_type = UVChartOptions::ConnectivityType::Edge;
2294 } else {
2295 throw std::runtime_error(
2296 lagrange::format("Invalid connectivity type: {}", connectivity_type));
2297 }
2298 return compute_uv_charts(mesh, options);
2299 },
2300 "mesh"_a,
2301 "uv_attribute_name"_a = UVChartOptions().uv_attribute_name,
2302 "output_attribute_name"_a = UVChartOptions().output_attribute_name,
2303 "connectivity_type"_a = "Edge",
2304 R"(Compute UV charts.
2305
2306:param mesh: Input mesh.
2307:param uv_attribute_name: Name of the UV attribute.
2308:param output_attribute_name: Name of the output attribute to store the chart ids.
2309:param connectivity_type: Type of connectivity to use for chart computation. Can be "Vertex" or "Edge".
2310
2311:returns: The number of charts.)");
2312
2313 nb::class_<UVOrientationCount>(m, "UVOrientationCount", "Counts of per-facet UV orientations.")
2314 .def(nb::init<>())
2315 .def_rw(
2316 "positive",
2318 "Number of CCW (positively oriented) facets.")
2319 .def_rw(
2320 "degenerate",
2322 "Number of degenerate (zero-area) facets.")
2323 .def_rw(
2324 "negative",
2326 "Number of CW (negatively oriented / flipped) facets.");
2327
2328 m.def(
2329 "compute_uv_orientation",
2330 [](MeshType& mesh,
2331 std::string_view uv_attribute_name,
2332 std::string_view output_attribute_name) {
2333 UVOrientationOptions options;
2334 options.uv_attribute_name = uv_attribute_name;
2335 options.output_attribute_name = output_attribute_name;
2336 return compute_uv_orientation(mesh, options);
2337 },
2338 "mesh"_a,
2339 "uv_attribute_name"_a = UVOrientationOptions().uv_attribute_name,
2340 "output_attribute_name"_a = UVOrientationOptions().output_attribute_name,
2341 R"(Compute a per-facet orientation attribute using Shewchuk's exact ``orient2D`` predicate.
2342
2343Each facet is assigned an ``int8`` value: ``+1`` for CCW (positively oriented), ``0`` for
2344degenerate, ``-1`` for CW (negatively oriented / flipped).
2345
2346:param mesh: Input triangle mesh.
2347:param uv_attribute_name: Name of the UV attribute. If empty, uses the first UV attribute.
2348:param output_attribute_name: Name of the output per-facet attribute (int8).
2349
2350:returns: A :class:`UVOrientationCount` with counts of positive, degenerate, and negative facets.)");
2351
2352 m.def(
2353 "unflip_uv_charts",
2354 [](MeshType& mesh,
2355 std::string_view uv_attribute_name,
2356 std::string_view chart_id_attribute_name) {
2357 UnflipUVChartsOptions options;
2358 options.uv_attribute_name = uv_attribute_name;
2359 options.chart_id_attribute_name = chart_id_attribute_name;
2360 return unflip_uv_charts(mesh, options);
2361 },
2362 "mesh"_a,
2363 "uv_attribute_name"_a = UnflipUVChartsOptions().uv_attribute_name,
2364 "chart_id_attribute_name"_a = UnflipUVChartsOptions().chart_id_attribute_name,
2365 R"(Mirror the UV positions of every UV vertex in any chart that is "flipped" by negating
2366its U coordinate. A chart is considered flipped when either its total signed UV area is negative,
2367OR every triangle in the chart is individually flipped (per :func:`compute_uv_orientation`); the
2368latter rule catches charts whose floating-point area sum is non-negative due to nearly-degenerate
2369triangles. Assumes UV vertices are not shared across charts.
2370
2371:param mesh: Input triangle mesh. The UV attribute must be indexed.
2372:param uv_attribute_name: Name of the UV attribute. If empty, uses the first indexed UV attribute.
2373:param chart_id_attribute_name: Optional per-facet chart id attribute name. If empty, charts are
2374 computed automatically using edge connectivity on the UV mesh.
2375
2376:returns: The number of charts that were unflipped.)");
2377
2378 m.def(
2379 "disconnect_uv_charts",
2380 [](MeshType& mesh,
2381 std::string_view uv_attribute_name,
2382 std::string_view chart_id_attribute_name) {
2383 DisconnectUVChartsOptions options;
2384 options.uv_attribute_name = uv_attribute_name;
2385 options.chart_id_attribute_name = chart_id_attribute_name;
2386 return disconnect_uv_charts(mesh, options);
2387 },
2388 "mesh"_a,
2389 "uv_attribute_name"_a = DisconnectUVChartsOptions().uv_attribute_name,
2390 "chart_id_attribute_name"_a = DisconnectUVChartsOptions().chart_id_attribute_name,
2391 R"(Disconnect UV charts by duplicating UV vertices shared across different charts.
2392
2393After this operation, no two facets belonging to different UV charts will share a UV vertex
2394index. Without any input chart id attribute, this eliminates non-manifold UV vertices (pinch
2395points) where charts touch at a single vertex.
2396
2397:param mesh: Input mesh. The UV attribute must be indexed.
2398:param uv_attribute_name: Name of the UV attribute. If empty, uses the first indexed UV attribute.
2399:param chart_id_attribute_name: Optional per-facet chart id attribute name. If empty, chart ids
2400 are computed automatically using edge connectivity on the UV mesh.
2401
2402:returns: The number of UV vertices that were duplicated.)");
2403
2404 m.def(
2405 "uv_mesh_view",
2406 [](const MeshType& mesh, std::string_view uv_attribute_name) {
2407 UVMeshOptions options;
2408 options.uv_attribute_name = uv_attribute_name;
2409 return uv_mesh_view(mesh, options);
2410 },
2411 "mesh"_a,
2412 "uv_attribute_name"_a = UVMeshOptions().uv_attribute_name,
2413 R"(Extract a UV mesh view from a 3D mesh.
2414
2415:param mesh: Input mesh.
2416:param uv_attribute_name: Name of the (indexed or vertex) UV attribute.
2417
2418:return: A new mesh representing the UV mesh.)");
2419 m.def(
2420 "uv_mesh_ref",
2421 [](MeshType& mesh, std::string_view uv_attribute_name) {
2422 UVMeshOptions options;
2423 options.uv_attribute_name = uv_attribute_name;
2424 return uv_mesh_ref(mesh, options);
2425 },
2426 "mesh"_a,
2427 "uv_attribute_name"_a = UVMeshOptions().uv_attribute_name,
2428 R"(Extract a UV mesh reference from a 3D mesh.
2429
2430:param mesh: Input mesh.
2431:param uv_attribute_name: Name of the (indexed or vertex) UV attribute.
2432
2433:return: A new mesh representing the UV mesh.)");
2434
2435 m.def(
2436 "split_facets_by_material",
2438 "mesh"_a,
2439 "material_attribute_name"_a,
2440 R"(Split mesh facets based on a material attribute.
2441
2442@param mesh: Input mesh on which material segmentation will be applied in place.
2443@param material_attribute_name: Name of the material attribute to use for inserting boundaries.
2444
2445@note The material attribute should be n by k vertex attribute, where n is the number of vertices,
2446and k is the number of materials. The value at row i and column j indicates the probability of vertex
2447i belonging to material j. The function will insert boundaries between different materials based on
2448the material attribute.
2449)");
2450
2451 m.def(
2452 "mesh_bbox",
2453 [](MeshType& mesh) -> std::tuple<Eigen::VectorX<Scalar>, Eigen::VectorX<Scalar>> {
2454 const Index dim = mesh.get_dimension();
2455 if (dim == 2) {
2456 auto box = mesh_bbox<2, Scalar, Index>(mesh);
2457 return {Eigen::VectorX<Scalar>(box.min()), Eigen::VectorX<Scalar>(box.max())};
2458 } else if (dim == 3) {
2459 auto box = mesh_bbox<3, Scalar, Index>(mesh);
2460 return {Eigen::VectorX<Scalar>(box.min()), Eigen::VectorX<Scalar>(box.max())};
2461 }
2462 throw nb::value_error("mesh_bbox only supports 2D or 3D meshes.");
2463 },
2464 "mesh"_a,
2465 R"(Compute the axis-aligned bounding box of a mesh.
2466
2467:param mesh: Input mesh (must be 2D or 3D).
2468
2469:returns: A tuple ``(min, max)`` of corner coordinates. For a mesh with no vertices, an empty box is returned, where ``min`` is component-wise greater than ``max``.)");
2470
2471 m.def(
2472 "compute_uv_tile_list",
2474 "mesh"_a,
2475 R"(Extract the list of all UV tiles that a mesh's parametrization spans.
2476
2477UV tiles are understood to be a regular unit grid in UV space. Tiles are unioned across
2478every attribute marked with UV usage (both indexed and per-vertex), adding an entry for
2479each distinct integer ``(floor(u), floor(v))`` pair found.
2480
2481:param mesh: Input mesh to be analyzed.
2482
2483:returns: A list of integer ``(u, v)`` coordinate pairs, one per UV tile.)");
2484}
2485
2486} // namespace lagrange::python
SurfaceMesh< Scalar, Index > unify_named_index_buffer(const SurfaceMesh< Scalar, Index > &mesh, const std::vector< std::string_view > &attribute_names)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition unify_index_buffer.cpp:279
void weld_indexed_attribute(SurfaceMesh< Scalar, Index > &mesh, AttributeId attr_id, const WeldOptions &options={})
Weld an indexed attribute by combining all corners around a vertex with the same attribute value.
Definition weld_indexed_attribute.cpp:500
AttributeId map_attribute_in_place(SurfaceMesh< Scalar, Index > &mesh, AttributeId id, AttributeElement new_element)
Map attribute values to a different element type.
Definition map_attribute.cpp:292
AttributeId map_attribute(SurfaceMesh< Scalar, Index > &mesh, AttributeId id, std::string_view new_name, AttributeElement new_element)
Map attribute values to a new attribute with a different element type.
Definition map_attribute.cpp:265
SurfaceMesh< Scalar, Index > unify_index_buffer(const SurfaceMesh< Scalar, Index > &mesh, const std::vector< AttributeId > &attribute_ids={})
Unify index buffers of the input mesh for all attributes specified in attribute_ids.
Definition unify_index_buffer.cpp:34
uint32_t AttributeId
Identified to be used to access an attribute.
Definition AttributeFwd.h:73
AttributeElement
Type of element to which the attribute is attached.
Definition AttributeFwd.h:26
@ Scalar
Mesh attribute must have exactly 1 channel.
Definition AttributeFwd.h:56
@ Facet
Per-facet mesh attributes.
Definition AttributeFwd.h:31
AttributeId compute_normal(SurfaceMesh< Scalar, Index > &mesh, function_ref< bool(Index)> is_edge_smooth, span< const Index > cone_vertices={}, NormalOptions options={})
Compute smooth normals based on specified sharp edges and cone vertices.
Definition compute_normal.cpp:210
SurfaceMesh< Scalar, Index > trim_by_isoline(const SurfaceMesh< Scalar, Index > &mesh, const IsolineOptions &options={})
Trim a mesh by the isoline of an implicit function defined on the mesh vertices/corners.
Definition isoline.cpp:610
AttributeId cast_attribute_in_place(SurfaceMesh< Scalar, Index > &mesh, AttributeId attribute_id)
Cast an attribute in place to a different value type.
Definition cast_attribute.cpp:68
bool is_closed(const SurfaceMesh< Scalar, Index > &mesh)
Check if a mesh is closed.
Definition topology.cpp:51
Scalar compute_uv_area(const SurfaceMesh< Scalar, Index > &mesh, MeshAreaOptions options={})
Compute UV mesh area.
Definition compute_area.cpp:429
std::array< std::array< Scalar, 3 >, 3 > compute_mesh_covariance(const SurfaceMesh< Scalar, Index > &mesh, const MeshCovarianceOptions &options={})
Compute the covariance matrix w.r.t.
Definition compute_mesh_covariance.cpp:102
size_t compute_uv_charts(SurfaceMesh< Scalar, Index > &mesh, const UVChartOptions &options={})
Compute UV charts of an input mesh.
Definition compute_uv_charts.cpp:24
int compute_euler(const SurfaceMesh< Scalar, Index > &mesh)
Compute Euler characteristic of a mesh.
Definition topology.cpp:35
bool select_facets_in_frustum(SurfaceMesh< Scalar, Index > &mesh, const Frustum< Scalar > &frustum, const FrustumSelectionOptions &options={})
Select all facets that intersect the cone/frustrum bounded by 4 planes defined by (n_i,...
Definition select_facets_in_frustum.cpp:45
AttributeId compute_greedy_coloring(SurfaceMesh< Scalar, Index > &mesh, const GreedyColoringOptions &options={})
Compute a greedy graph coloring of the mesh.
Definition compute_greedy_coloring.cpp:153
AttributeId compute_edge_is_oriented(SurfaceMesh< Scalar, Index > &mesh, const OrientationOptions &options={})
Compute a mesh attribute indicating whether an edge is oriented.
Definition orientation.cpp:82
std::string get_unique_attribute_name(const SurfaceMesh< Scalar, Index > &mesh, std::string_view name, const UniqueAttributeNameOptions &options={})
Returns a unique attribute name by appending a suffix if necessary.
Definition get_unique_attribute_name.cpp:23
SurfaceMesh< Scalar, Index > combine_meshes(std::initializer_list< const SurfaceMesh< Scalar, Index > * > meshes, bool preserve_attributes=true)
Combine multiple meshes into a single mesh.
Definition combine_meshes.cpp:330
std::vector< SurfaceMesh< Scalar, Index > > separate_by_facet_groups(const SurfaceMesh< Scalar, Index > &mesh, size_t num_groups, span< const Index > facet_group_indices, const SeparateByFacetGroupsOptions &options={})
Extract a set of submeshes based on facet groups.
Definition separate_by_facet_groups.cpp:26
ReorderingMethod
Mesh reordering method to apply before decimation.
Definition reorder_mesh.h:26
size_t disconnect_uv_charts(SurfaceMesh< Scalar, Index > &mesh, const DisconnectUVChartsOptions &options={})
Disconnect UV charts by duplicating UV vertices shared across different charts.
Definition disconnect_uv_charts.cpp:221
bool is_oriented(const SurfaceMesh< Scalar, Index > &mesh)
Check if a mesh is oriented.
Definition orientation.cpp:57
SurfaceMesh< Scalar, Index > thicken_and_close_mesh(SurfaceMesh< Scalar, Index > input_mesh, const ThickenAndCloseOptions &options={})
Thicken a mesh by offsetting it, and close the shape into a thick 3D solid.
Definition thicken_and_close_mesh.cpp:272
bool is_manifold(const SurfaceMesh< Scalar, Index > &mesh)
Check if a mesh is both vertex-manifold and edge-manifold.
Definition topology.h:98
void permute_facets(SurfaceMesh< Scalar, Index > &mesh, span< const Index > new_to_old)
Reorder facets of a mesh based on a given permutation.
Definition permute_facets.cpp:26
SurfaceMesh< Scalar, Index > insert_isoline(const SurfaceMesh< Scalar, Index > &mesh, const IsolineOptions &options={})
Insert the isoline of an implicit function into a mesh.
Definition isoline.cpp:626
AttributeId compute_facet_normal(SurfaceMesh< Scalar, Index > &mesh, FacetNormalOptions options={})
Compute facet normals.
Definition compute_facet_normal.cpp:34
void orient_outward(lagrange::SurfaceMesh< Scalar, Index > &mesh, const OrientOptions &options={})
Orient the facets of a mesh so that the signed volume of each connected component is positive or nega...
Definition orient_outward.cpp:128
bool is_edge_manifold(const SurfaceMesh< Scalar, Index > &mesh)
Check if a mesh is edge-manifold.
Definition topology.cpp:125
size_t unflip_uv_charts(SurfaceMesh< Scalar, Index > &mesh, const UnflipUVChartsOptions &options={})
Mirror the UV positions of every UV vertex in any chart that is "flipped".
Definition unflip_uv_charts.cpp:159
AttributeId compute_facet_area(SurfaceMesh< Scalar, Index > &mesh, FacetAreaOptions options={})
Compute per-facet area.
Definition compute_area.cpp:307
AttributeId compute_edge_lengths(SurfaceMesh< Scalar, Index > &mesh, const EdgeLengthOptions &options={})
Computes edge lengths attribute.
Definition compute_edge_lengths.cpp:28
AttributeId cast_attribute(SurfaceMesh< Scalar, Index > &mesh, AttributeId source_id, std::string_view target_name)
Cast an attribute in place to a different value type.
Definition cast_attribute.cpp:25
std::optional< std::vector< Index > > compute_dijkstra_distance(SurfaceMesh< Scalar, Index > &mesh, const DijkstraDistanceOptions< Scalar, Index > &options={})
Computes dijkstra distance from a seed facet.
Definition compute_dijkstra_distance.cpp:24
Scalar compute_mesh_area(const SurfaceMesh< Scalar, Index > &mesh, MeshAreaOptions options={})
Compute mesh area.
Definition compute_area.cpp:407
AttributeId compute_vertex_valence(SurfaceMesh< Scalar, Index > &mesh, VertexValenceOptions options={})
Compute vertex valence.
Definition compute_vertex_valence.cpp:28
SurfaceMesh< Scalar, Index > extract_submesh(const SurfaceMesh< Scalar, Index > &mesh, span< const Index > selected_facets, const SubmeshOptions &options={})
Extract a submesh that consists of a subset of the facets of the source mesh.
Definition extract_submesh.cpp:29
void normalize_mesh(SurfaceMesh< Scalar, Index > &mesh, const TransformOptions &options={})
Normalize a mesh to fit in a unit box centered at the origin.
Definition normalize_meshes.cpp:57
AttributeId compute_facet_vector_area(SurfaceMesh< Scalar, Index > &mesh, FacetVectorAreaOptions options={})
Compute per-facet vector area.
Definition compute_area.cpp:325
void split_facets_by_material(SurfaceMesh< Scalar, Index > &mesh, std::string_view material_attribute_name)
Split mesh facets based on material labels.
Definition split_facets_by_material.cpp:57
void remap_vertices(SurfaceMesh< Scalar, Index > &mesh, span< const Index > forward_mapping, RemapVerticesOptions options={})
Remap vertices of a mesh based on provided forward mapping.
Definition remap_vertices.cpp:137
void triangulate_polygonal_facets(SurfaceMesh< Scalar, Index > &mesh, const TriangulationOptions &options={})
Triangulate polygonal facets of a mesh using a prescribed set of rules.
Definition triangulate_polygonal_facets.cpp:550
auto normalize_mesh_with_transform(SurfaceMesh< Scalar, Index > &mesh, const TransformOptions &options={}) -> Eigen::Transform< Scalar, Dimension, Eigen::Affine >
Normalize a mesh to fit in a unit box centered at the origin.
Definition normalize_meshes.cpp:30
void permute_vertices(SurfaceMesh< Scalar, Index > &mesh, span< const Index > new_to_old)
Reorder vertices of a mesh based on a given permutation.
Definition permute_vertices.cpp:26
AttributeId compute_vertex_normal(SurfaceMesh< Scalar, Index > &mesh, VertexNormalOptions options={})
Compute per-vertex normals based on specified weighting type.
Definition compute_vertex_normal.cpp:35
bool is_vertex_manifold(const SurfaceMesh< Scalar, Index > &mesh)
Check if a mesh is vertex-manifold.
Definition topology.cpp:98
AttributeId compute_facet_centroid(SurfaceMesh< Scalar, Index > &mesh, FacetCentroidOptions options={})
Compute per-facet centroid.
Definition compute_centroid.cpp:31
PointcloudPCAOutput< Scalar > compute_pointcloud_pca(span< const Scalar > points, ComputePointcloudPCAOptions options={})
Finds the principal components for a pointcloud.
Definition compute_pointcloud_pca.cpp:23
std::vector< SurfaceMesh< Scalar, Index > > separate_by_components(const SurfaceMesh< Scalar, Index > &mesh, const SeparateByComponentsOptions &options={})
Separate a mesh by connected components.
Definition separate_by_components.cpp:21
SurfaceMesh< UVScalar, Index > uv_mesh_view(const SurfaceMesh< Scalar, Index > &mesh, const UVMeshOptions &options={})
Extract a UV mesh view from an input mesh.
Definition uv_mesh.cpp:86
AttributeId compute_vertex_is_manifold(SurfaceMesh< Scalar, Index > &mesh, const VertexManifoldOptions &options={})
Compute a mesh attribute of value type uint8_t indicating vertex manifoldness.
Definition topology.cpp:142
AttributeId select_facets_by_normal_similarity(SurfaceMesh< Scalar, Index > &mesh, const Index seed_facet_id, const SelectFacetsByNormalSimilarityOptions &options={})
Given a seed facet, selects facets around it based on the change in triangle normals.
Definition select_facets_by_normal_similarity.cpp:30
std::vector< std::pair< int32_t, int32_t > > compute_uv_tile_list(const SurfaceMesh< Scalar, Index > &mesh)
Extract the list of all UV tiles that a mesh's parametrization spans.
Definition compute_uv_tile_list.cpp:25
std::vector< std::vector< Index > > extract_boundary_loops(const SurfaceMesh< Scalar, Index > &mesh)
Extract boundary loops from a surface mesh.
Definition extract_boundary_loops.cpp:24
AttributeId compute_dihedral_angles(SurfaceMesh< Scalar, Index > &mesh, const DihedralAngleOptions &options={})
Computes dihedral angles for each edge in the mesh.
Definition compute_dihedral_angles.cpp:33
SurfaceMesh< ToScalar, ToIndex > cast(const SurfaceMesh< FromScalar, FromIndex > &source_mesh, const AttributeFilter &convertible_attributes={}, std::vector< std::string > *converted_attributes_names=nullptr)
Cast a mesh to a mesh of different scalar and/or index type.
Eigen::AlignedBox< Scalar, static_cast< int >(Dimension)> mesh_bbox(const SurfaceMesh< Scalar, Index > &mesh)
Compute the axis-aligned bounding box of a mesh.
Definition mesh_bbox.cpp:22
TangentBitangentResult compute_tangent_bitangent(SurfaceMesh< Scalar, Index > &mesh, TangentBitangentOptions options={})
Compute mesh tangent and bitangent vectors orthogonal to the input mesh normals.
Definition compute_tangent_bitangent.cpp:536
AttributeId compute_edge_is_manifold(SurfaceMesh< Scalar, Index > &mesh, const EdgeManifoldOptions &options={})
Compute a mesh attribute of value type uint8_t indicating edge manifoldness.
Definition topology.cpp:168
SurfaceMesh< Scalar, Index > transformed_mesh(SurfaceMesh< Scalar, Index > mesh, const Eigen::Transform< Scalar, Dimension, Eigen::Affine > &transform, const TransformOptions &options={})
Apply an affine transform to a mesh and return the transformed mesh.
Definition transform_mesh.cpp:173
SurfaceMesh< Scalar, Index > filter_attributes(SurfaceMesh< Scalar, Index > source_mesh, const AttributeFilter &options={})
Filters the attributes of mesh according to user specifications.
Definition filter_attributes.cpp:116
void normalize_meshes(span< SurfaceMesh< Scalar, Index > * > meshes, const TransformOptions &options={})
Normalize a list of meshes to fit in a unit box centered at the origin.
Definition normalize_meshes.cpp:107
void transform_mesh(SurfaceMesh< Scalar, Index > &mesh, const Eigen::Transform< Scalar, Dimension, Eigen::Affine > &transform, const TransformOptions &options={})
Apply an affine transform to a mesh in-place.
Definition transform_mesh.cpp:164
AttributeId compute_facet_circumcenter(SurfaceMesh< Scalar, Index > &mesh, FacetCircumcenterOptions options={})
Compute per-facet circumcenter.
Definition compute_facet_circumcenter.cpp:32
AttributeId compute_uv_distortion(SurfaceMesh< Scalar, Index > &mesh, const UVDistortionOptions &options={})
Compute uv distortion using the selected distortion measure.
Definition compute_uv_distortion.cpp:31
DistortionMetric
UV distortion metric type.
Definition DistortionMetric.h:26
void compute_mesh_centroid(const SurfaceMesh< Scalar, Index > &mesh, span< Scalar > centroid, MeshCentroidOptions options={})
Compute mesh centroid, where mesh centroid is defined as the weighted sum of facet centroids.
Definition compute_centroid.cpp:74
SurfaceMesh< UVScalar, Index > uv_mesh_ref(SurfaceMesh< Scalar, Index > &mesh, const UVMeshOptions &options={})
Extract a UV mesh reference from an input mesh.
Definition uv_mesh.cpp:40
UVOrientationCount compute_uv_orientation(SurfaceMesh< Scalar, Index > &mesh, const UVOrientationOptions &options={})
Compute a per-facet orientation attribute using Shewchuk's exact orient2D predicate.
Definition compute_uv_orientation.cpp:96
AttributeId compute_seam_edges(SurfaceMesh< Scalar, Index > &mesh, AttributeId indexed_attribute_id, const SeamEdgesOptions &options={})
Computes the seam edges for a given indexed attribute.
Definition compute_seam_edges.cpp:35
void reorder_mesh(SurfaceMesh< Scalar, Index > &mesh, ReorderingMethod method)
Mesh reordering to improve cache locality.
Definition reorder_mesh.cpp:172
size_t compute_components(SurfaceMesh< Scalar, Index > &mesh, ComponentOptions options={})
Compute connected components of an input mesh.
Definition compute_components.cpp:127
SurfaceMesh< Scalar, Index > extract_isoline(const SurfaceMesh< Scalar, Index > &mesh, const IsolineOptions &options={})
Extract the isoline of an implicit function defined on the mesh vertices/corners.
Definition isoline.cpp:618
auto normalize_meshes_with_transform(span< SurfaceMesh< Scalar, Index > * > meshes, const TransformOptions &options={}) -> Eigen::Transform< Scalar, Dimension, Eigen::Affine >
Normalize a list of meshes to fit in a unit box centered at the origin.
Definition normalize_meshes.cpp:67
@ Lexicographic
Sort vertices/facets lexicographically.
Definition reorder_mesh.h:27
@ None
Do not reorder mesh vertices/facets.
Definition reorder_mesh.h:30
@ Hilbert
Spatial sort vertices/facets using Hilbert curve.
Definition reorder_mesh.h:29
@ Morton
Spatial sort vertices/facets using Morton encoding.
Definition reorder_mesh.h:28
@ Angle
Incident face normals are averaged weighted by incident angle of vertex.
Definition NormalWeightingType.h:36
@ CornerTriangleArea
Incident face normals are averaged weighted by area of the corner triangle.
Definition NormalWeightingType.h:33
@ Uniform
Incident face normals have uniform influence on vertex normal.
Definition NormalWeightingType.h:29
@ MIPS
UV triangle area / 3D triangle area.
Definition DistortionMetric.h:31
@ InverseDirichlet
Inverse Dirichlet energy.
Definition DistortionMetric.h:28
@ SymmetricDirichlet
Symmetric Dirichlet energy.
Definition DistortionMetric.h:29
@ Dirichlet
Dirichlet energy.
Definition DistortionMetric.h:27
#define la_runtime_assert(...)
Runtime assertion check.
Definition assert.h:177
::nonstd::span< T, Extent > span
A bounds-safe view for sequences of objects.
Definition span.h:27
constexpr T invalid()
You can use invalid<T>() to get a value that can represent "invalid" values, such as invalid indices ...
Definition invalid.h:40
function_ref(R(*)(Args...)) -> function_ref< R(Args...)>
Deduce function_ref type from a function pointer.
ChainEdgesResult< Index > chain_undirected_edges(const span< const Index > edges, const ChainEdgesOptions &options={})
Chain a set of undirected edges into loops and chains.
Definition chain_edges.cpp:248
ChainEdgesResult< Index > chain_directed_edges(const span< const Index > edges, const ChainEdgesOptions &options={})
Chain a set of directed edges into loops and chains.
Definition chain_edges.cpp:51
void map_attributes(const SurfaceMesh< Scalar, Index > &source_mesh, SurfaceMesh< Scalar, Index > &target_mesh, span< const Index > mapping_data, span< const Index > mapping_offsets={}, const MapAttributesOptions &options={})
Map attributes from the source mesh to the target mesh.
Definition map_attributes.cpp:47
ConnectivityType
This type defines the condition when two facets are considered as "connected".
Definition ConnectivityType.h:19
@ Edge
Two facets are considered connected if they share an edge.
Definition ConnectivityType.h:21
@ KeepFirst
Keep the value of the first elements.
Definition MappingPolicy.h:23
@ Error
Throw an error if collision is detected.
Definition MappingPolicy.h:24
@ Average
Take the average of all involved elements.
Definition MappingPolicy.h:22
std::variant< AttributeId, std::string > AttributeNameOrId
Variant identifying an attribute by its name or id.
Definition filter_attributes.h:39
ConnectivityType connectivity_type
Connectivity type used for component computation.
Definition compute_components.h:38
std::string_view output_attribute_name
Output component id attribute name.
Definition compute_components.h:35
std::string_view output_attribute_name
Output attribute name for facet area.
Definition compute_area.h:34
std::string_view output_attribute_name
Ouptut facet centroid attribute name.
Definition compute_centroid.h:33
std::string_view output_attribute_name
Output normal attribute name.
Definition compute_facet_normal.h:35
std::string_view input_attribute_name
Precomputed facet area attribute name.
Definition compute_area.h:146
bool use_signed_area
For 2D mesh only: whether the computed facet area (if any) should be signed.
Definition compute_area.h:149
std::string_view facet_centroid_attribute_name
Precomputed facet centroid attribute name.
Definition compute_centroid.h:66
@ Area
Per-facet centroid are weighted by facet area.
Definition compute_centroid.h:61
@ Uniform
Per-facet centroid are weighted uniformly.
Definition compute_centroid.h:60
std::string_view facet_area_attribute_name
Precomputed facet area attribute name.
Definition compute_centroid.h:70
bool keep_facet_normals
Whether to keep any newly added facet normal attribute.
Definition compute_normal.h:55
std::string_view facet_normal_attribute_name
Precomputed facet normal attribute name.
Definition compute_normal.h:48
bool recompute_facet_normals
Whether to recompute the facet normal attribute, or reuse existing cached values if present.
Definition compute_normal.h:51
std::string_view output_attribute_name
Output normal attribute name.
Definition compute_normal.h:41
float distance_tolerance
Tolerance for degenerate edge check. (only used to bypass degenerate edges in polygon facets)
Definition compute_normal.h:58
NormalWeightingType weight_type
Per-vertex normal averaging weighting type.
Definition compute_normal.h:44
CollisionPolicy collision_policy_integral
Collision policy for integral valued attributes.
Definition remap_vertices.h:39
CollisionPolicy collision_policy_float
Collision policy for float or double valued attributes.
Definition remap_vertices.h:36
@ BFS
Breadth-First Search.
Definition select_facets_by_normal_similarity.h:67
@ DFS
Depth-First Search.
Definition select_facets_by_normal_similarity.h:68
std::string_view bitangent_attribute_name
Output bitangent attribute name.
Definition compute_tangent_bitangent.h:41
bool keep_existing_tangent
Whether to recompute tangent if the tangent attribute (specified by tangent_attribute_name) already e...
Definition compute_tangent_bitangent.h:70
std::string_view normal_attribute_name
Normal attribute name used to compute the BTN frame.
Definition compute_tangent_bitangent.h:52
std::string_view tangent_attribute_name
Output tangent attribute name.
Definition compute_tangent_bitangent.h:38
AttributeElement output_element_type
Output element type. Can be either Corner or Indexed.
Definition compute_tangent_bitangent.h:55
bool pad_with_sign
Whether to pad the tangent/bitangent vectors with a 4th coordinate indicating the sign of the UV tria...
Definition compute_tangent_bitangent.h:59
bool orthogonalize_bitangent
Whether to compute the bitangent as sign * cross(normal, tangent) If false, the bitangent is computed...
Definition compute_tangent_bitangent.h:63
std::string_view uv_attribute_name
UV attribute name used to orient the BTN frame.
Definition compute_tangent_bitangent.h:45
AttributeId tangent_id
Tangent vector attribute id.
Definition compute_tangent_bitangent.h:77
AttributeId bitangent_id
Bitangent vector attribute id.
Definition compute_tangent_bitangent.h:80
@ Delaunay
Earcut triangulation refined toward a Delaunay triangulation via edge flips.
Definition triangulate_polygonal_facets.h:34
@ Earcut
Use earcut algorithm to triangulate polygons.
Definition triangulate_polygonal_facets.h:32
@ CentroidFan
Connect facet centroid to polygon edges to form a fan of triangles.
Definition triangulate_polygonal_facets.h:33
Scheme scheme
Triangulation scheme to use.
Definition triangulate_polygonal_facets.h:37
size_t degenerate
Number of degenerate (zero-area) facets.
Definition compute_uv_orientation.h:41
size_t positive
Number of CCW (positively oriented) facets.
Definition compute_uv_orientation.h:40
size_t negative
Number of CW (negatively oriented / flipped) facets.
Definition compute_uv_orientation.h:42
bool keep_weighted_corner_normals
Whether to keep any newly added weighted corner normal attribute.
Definition compute_vertex_normal.h:56
std::string_view weighted_corner_normal_attribute_name
Precomputed weighted corner attribute name.
Definition compute_vertex_normal.h:47
std::string_view output_attribute_name
Output normal attribute name.
Definition compute_vertex_normal.h:39
float distance_tolerance
Tolerance for degenerate edge check. (only used to bypass degenerate edges in polygon facets)
Definition compute_vertex_normal.h:59
bool recompute_weighted_corner_normals
Whether to recompute the weighted corner normal attribute, or reuse existing cached values if present...
Definition compute_vertex_normal.h:51
NormalWeightingType weight_type
Per-vertex normal averaging weighting type.
Definition compute_vertex_normal.h:42
std::string_view induced_by_attribute
Optional per-edge attribute used as indicator function to restrict the graph used for vertex valence ...
Definition compute_vertex_valence.h:39
std::string_view output_attribute_name
Output vertex valence attribute name.
Definition compute_vertex_valence.h:42
Definition StubType.h:32