DeepSDFStruct 1.7.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. DeepSDFStruct/SDF.py +1734 -0
  2. DeepSDFStruct/__init__.py +66 -0
  3. DeepSDFStruct/deep_sdf/__init__.py +69 -0
  4. DeepSDFStruct/deep_sdf/create_screenshots_from_plyfiles.py +65 -0
  5. DeepSDFStruct/deep_sdf/data.py +258 -0
  6. DeepSDFStruct/deep_sdf/metrics/__init__.py +14 -0
  7. DeepSDFStruct/deep_sdf/metrics/mesh_to_analytical.py +24 -0
  8. DeepSDFStruct/deep_sdf/models.py +197 -0
  9. DeepSDFStruct/deep_sdf/networks/__init__.py +8 -0
  10. DeepSDFStruct/deep_sdf/networks/analytic_round_cross.py +105 -0
  11. DeepSDFStruct/deep_sdf/networks/deep_sdf_decoder.py +155 -0
  12. DeepSDFStruct/deep_sdf/networks/hierarchical_deep_sdf_decoder.py +139 -0
  13. DeepSDFStruct/deep_sdf/networks/hierarchical_positional_sdf_decoder.py +190 -0
  14. DeepSDFStruct/deep_sdf/networks/resnet_positional_sdf_decoder.py +108 -0
  15. DeepSDFStruct/deep_sdf/nn_utils.py +70 -0
  16. DeepSDFStruct/deep_sdf/plotting.py +143 -0
  17. DeepSDFStruct/deep_sdf/reconstruction.py +165 -0
  18. DeepSDFStruct/deep_sdf/training.py +840 -0
  19. DeepSDFStruct/deep_sdf/workspace.py +363 -0
  20. DeepSDFStruct/design_of_experiments.py +235 -0
  21. DeepSDFStruct/flexicubes/__init__.py +15 -0
  22. DeepSDFStruct/flexicubes/flexicubes.py +1005 -0
  23. DeepSDFStruct/flexicubes/tables.py +2338 -0
  24. DeepSDFStruct/flexisquares/__init__.py +15 -0
  25. DeepSDFStruct/flexisquares/flexisquares.py +967 -0
  26. DeepSDFStruct/flexisquares/tables.py +63 -0
  27. DeepSDFStruct/lattice_structure.py +254 -0
  28. DeepSDFStruct/local_shapes.py +226 -0
  29. DeepSDFStruct/mesh.py +1184 -0
  30. DeepSDFStruct/optimization.py +357 -0
  31. DeepSDFStruct/parametrization.py +215 -0
  32. DeepSDFStruct/pretrained_models.py +128 -0
  33. DeepSDFStruct/sampling.py +670 -0
  34. DeepSDFStruct/sdf_operations.py +990 -0
  35. DeepSDFStruct/sdf_primitives.py +1416 -0
  36. DeepSDFStruct/splinepy_unitcells/__init__.py +35 -0
  37. DeepSDFStruct/splinepy_unitcells/chi_3D.py +1617 -0
  38. DeepSDFStruct/splinepy_unitcells/cross_lattice.py +165 -0
  39. DeepSDFStruct/splinepy_unitcells/double_lattice_extruded.py +298 -0
  40. DeepSDFStruct/splinepy_unitcells/snappy_3d.py +544 -0
  41. DeepSDFStruct/torch_spline.py +446 -0
  42. DeepSDFStruct/trained_models/analytic_round_cross/LatentCodes/latest.pth +0 -0
  43. DeepSDFStruct/trained_models/analytic_round_cross/ModelParameters/latest.pth +0 -0
  44. DeepSDFStruct/trained_models/analytic_round_cross/OptimizerParameters/latest.pth +0 -0
  45. DeepSDFStruct/trained_models/analytic_round_cross/specs.json +45 -0
  46. DeepSDFStruct/trained_models/chi_and_cross/LatentCodes/latest.pth +0 -0
  47. DeepSDFStruct/trained_models/chi_and_cross/Logs.pth +0 -0
  48. DeepSDFStruct/trained_models/chi_and_cross/ModelParameters/latest.pth +0 -0
  49. DeepSDFStruct/trained_models/chi_and_cross/OptimizerParameters/latest.pth +0 -0
  50. DeepSDFStruct/trained_models/chi_and_cross/specs.json +76 -0
  51. DeepSDFStruct/trained_models/primitives/LatentCodes/latest.pth +0 -0
  52. DeepSDFStruct/trained_models/primitives/ModelParameters/latest.pth +0 -0
  53. DeepSDFStruct/trained_models/primitives/OptimizerParameters/latest.pth +0 -0
  54. DeepSDFStruct/trained_models/primitives/specs.json +46 -0
  55. DeepSDFStruct/trained_models/primitives_2d/LatentCodes/latest.pth +0 -0
  56. DeepSDFStruct/trained_models/primitives_2d/ModelParameters/latest.pth +0 -0
  57. DeepSDFStruct/trained_models/primitives_2d/OptimizerParameters/latest.pth +0 -0
  58. DeepSDFStruct/trained_models/primitives_2d/specs.json +46 -0
  59. DeepSDFStruct/trained_models/round_cross/LatentCodes/latest.pth +0 -0
  60. DeepSDFStruct/trained_models/round_cross/Logs.pth +0 -0
  61. DeepSDFStruct/trained_models/round_cross/ModelParameters/latest.pth +0 -0
  62. DeepSDFStruct/trained_models/round_cross/OptimizerParameters/latest.pth +0 -0
  63. DeepSDFStruct/trained_models/round_cross/specs.json +45 -0
  64. DeepSDFStruct/trained_models/test_experiment/LatentCodes/latent_code_data_map.json +106 -0
  65. DeepSDFStruct/trained_models/test_experiment/specs.json +45 -0
  66. DeepSDFStruct/trained_models/test_experiment/training_summary.json +10 -0
  67. DeepSDFStruct/trained_models/test_experiment_hierarchical/LatentCodes/latent_code_data_map.json +106 -0
  68. DeepSDFStruct/trained_models/test_experiment_hierarchical/specs.json +45 -0
  69. DeepSDFStruct/trained_models/test_experiment_hierarchical/training_summary.json +10 -0
  70. DeepSDFStruct/trained_models/test_experiment_homogenization/LatentCodes/latent_code_data_map.json +5006 -0
  71. DeepSDFStruct/trained_models/test_experiment_homogenization/LatentCodes/latest.pth +0 -0
  72. DeepSDFStruct/trained_models/test_experiment_homogenization/Logs.png +0 -0
  73. DeepSDFStruct/trained_models/test_experiment_homogenization/ModelParameters/latest.pth +0 -0
  74. DeepSDFStruct/trained_models/test_experiment_homogenization/OptimizerParameters/latest.pth +0 -0
  75. DeepSDFStruct/trained_models/test_experiment_homogenization/specs.json +83 -0
  76. DeepSDFStruct/trained_models/test_experiment_homogenization/training_summary.json +10 -0
  77. DeepSDFStruct/utils.py +96 -0
  78. DeepSDFStruct/visualization/latent_viewer.py +211 -0
  79. DeepSDFStruct/visualization/latent_viewer_cli.py +8 -0
  80. benchmarks/generate_sdf_showcase.py +622 -0
  81. benchmarks/sdf_from_mesh_benchmark.py +52 -0
  82. benchmarks/sdf_from_mesh_comparison.md +33 -0
  83. benchmarks/sdf_showcase/operations/boolean/difference_sphere_box.png +0 -0
  84. benchmarks/sdf_showcase/operations/boolean/union_sphere_box.png +0 -0
  85. benchmarks/sdf_showcase/operations/transformations/circular_array_sphere.png +0 -0
  86. benchmarks/sdf_showcase/operations/transformations/dilate_sphere.png +0 -0
  87. benchmarks/sdf_showcase/operations/transformations/mirror_sphere.png +0 -0
  88. benchmarks/sdf_showcase/operations/transformations/repeat_sphere.png +0 -0
  89. benchmarks/sdf_showcase/operations/transformations/revolve_circle.png +0 -0
  90. benchmarks/sdf_showcase/operations/transformations/shell_sphere.png +0 -0
  91. benchmarks/sdf_showcase/operations/transformations/twist_torus.png +0 -0
  92. benchmarks/sdf_showcase/primitives/2D/circle.png +0 -0
  93. benchmarks/sdf_showcase/primitives/2D/equilateral_triangle.png +0 -0
  94. benchmarks/sdf_showcase/primitives/2D/hexagon.png +0 -0
  95. benchmarks/sdf_showcase/primitives/2D/polygon_pentagon.png +0 -0
  96. benchmarks/sdf_showcase/primitives/2D/rectangle.png +0 -0
  97. benchmarks/sdf_showcase/primitives/2D/rounded_rectangle.png +0 -0
  98. benchmarks/sdf_showcase/primitives/3D/box.png +0 -0
  99. benchmarks/sdf_showcase/primitives/3D/capped_cone.png +0 -0
  100. benchmarks/sdf_showcase/primitives/3D/capped_cylinder.png +0 -0
  101. benchmarks/sdf_showcase/primitives/3D/capsule.png +0 -0
  102. benchmarks/sdf_showcase/primitives/3D/cone.png +0 -0
  103. benchmarks/sdf_showcase/primitives/3D/corner_spheres.png +0 -0
  104. benchmarks/sdf_showcase/primitives/3D/cross_ms.png +0 -0
  105. benchmarks/sdf_showcase/primitives/3D/cylinder.png +0 -0
  106. benchmarks/sdf_showcase/primitives/3D/dodecahedron.png +0 -0
  107. benchmarks/sdf_showcase/primitives/3D/ellipsoid.png +0 -0
  108. benchmarks/sdf_showcase/primitives/3D/icosahedron.png +0 -0
  109. benchmarks/sdf_showcase/primitives/3D/octahedron.png +0 -0
  110. benchmarks/sdf_showcase/primitives/3D/pyramid.png +0 -0
  111. benchmarks/sdf_showcase/primitives/3D/rounded_box.png +0 -0
  112. benchmarks/sdf_showcase/primitives/3D/rounded_cone.png +0 -0
  113. benchmarks/sdf_showcase/primitives/3D/rounded_cylinder.png +0 -0
  114. benchmarks/sdf_showcase/primitives/3D/sphere.png +0 -0
  115. benchmarks/sdf_showcase/primitives/3D/tetrahedron.png +0 -0
  116. benchmarks/sdf_showcase/primitives/3D/torus.png +0 -0
  117. benchmarks/sdf_showcase/primitives/3D/wireframe_box.png +0 -0
  118. deepsdfstruct-1.7.2.dist-info/METADATA +44 -0
  119. deepsdfstruct-1.7.2.dist-info/RECORD +165 -0
  120. deepsdfstruct-1.7.2.dist-info/WHEEL +5 -0
  121. deepsdfstruct-1.7.2.dist-info/licenses/LICENSE +208 -0
  122. deepsdfstruct-1.7.2.dist-info/licenses/NOTICE +67 -0
  123. deepsdfstruct-1.7.2.dist-info/scm_file_list.json +178 -0
  124. deepsdfstruct-1.7.2.dist-info/scm_version.json +8 -0
  125. deepsdfstruct-1.7.2.dist-info/top_level.txt +4 -0
  126. docs/Makefile +20 -0
  127. docs/api_reference.rst +6 -0
  128. docs/conf.py +60 -0
  129. docs/index.rst +136 -0
  130. docs/make.bat +35 -0
  131. docs/qr_code_github.png +0 -0
  132. docs/qr_code_paper.png +0 -0
  133. docs/readme_images/example_output_01.png +0 -0
  134. docs/readme_images/example_output_02.png +0 -0
  135. docs/readme_images/example_output_03.png +0 -0
  136. docs/readme_images/example_output_04.png +0 -0
  137. tests/data/chairs/1005.obj +282 -0
  138. tests/data/chairs/1024.obj +222 -0
  139. tests/data/chairs/README.md +1 -0
  140. tests/data/circular_balls_test_case.stl +0 -0
  141. tests/data/cone.stl +1794 -0
  142. tests/data/example_disconnectd_mesh.inp +1784 -0
  143. tests/data/example_line_mesh.vtk +0 -0
  144. tests/data/stanford_bunny.stl +0 -0
  145. tests/data/sweep_test_case.stl +0 -0
  146. tests/test_DOE.py +49 -0
  147. tests/test_elongate_sdf.py +195 -0
  148. tests/test_flexisquares.py +187 -0
  149. tests/test_generate_dataset.py +76 -0
  150. tests/test_lattice_evaluation.py +137 -0
  151. tests/test_mesh_export.py +137 -0
  152. tests/test_mesh_functions.py +49 -0
  153. tests/test_networks.py +71 -0
  154. tests/test_pretrained_models.py +40 -0
  155. tests/test_reconstruction.py +101 -0
  156. tests/test_sdf_from_mesh.py +52 -0
  157. tests/test_sdf_functions.py +117 -0
  158. tests/test_sdf_primitives.py +668 -0
  159. tests/test_sdf_trimesh_comparison.py +482 -0
  160. tests/test_splinepy_unitcells.py +64 -0
  161. tests/test_structural_optimization.py +178 -0
  162. tests/test_torch_spline.py +216 -0
  163. tests/test_train_model.py +110 -0
  164. tests/test_training_data_ids.py +41 -0
  165. tests/tmp_outputs/temp_file.txt +0 -0
@@ -0,0 +1,1005 @@
1
+ """
2
+ FlexiCubes Implementation
3
+ =========================
4
+
5
+ This module contains the core implementation of the FlexiCubes algorithm,
6
+ a differentiable 3D mesh extraction method that improves upon traditional
7
+ Dual Marching Cubes.
8
+
9
+ FlexiCubes dynamically adjusts surface representations through gradient-based
10
+ optimization, enhancing geometric fidelity and mesh quality. The method is
11
+ particularly useful for neural implicit representations and inverse design.
12
+
13
+ Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES.
14
+ Licensed under the Apache License, Version 2.0.
15
+ """
16
+
17
+ # Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES.
18
+ # All rights reserved.
19
+ #
20
+ # Licensed under the Apache License, Version 2.0 (the "License");
21
+ # you may not use this file except in compliance with the License.
22
+ # You may obtain a copy of the License at
23
+ #
24
+ # http://www.apache.org/licenses/LICENSE-2.0
25
+ #
26
+ # Unless required by applicable law or agreed to in writing, software
27
+ # distributed under the License is distributed on an "AS IS" BASIS,
28
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
+ # See the License for the specific language governing permissions and
30
+ # limitations under the License.
31
+ import torch
32
+ import warnings
33
+ from DeepSDFStruct.flexicubes.tables import *
34
+
35
+ __all__ = ["FlexiCubes"]
36
+
37
+
38
+ class FlexiCubes:
39
+ """
40
+ This class implements the flexicubes method for extracting meshes
41
+ from scalar fields. It maintains a series of lookup tables and
42
+ indices to support the mesh extraction process. Flexicubes, a
43
+ differentiable variant of the Dual Marching Cubes (DMC) scheme,
44
+ enhances the geometric fidelity and mesh quality of reconstructed
45
+ meshes by dynamically adjusting the surface representation through
46
+ gradient-based optimization.
47
+
48
+ During instantiation, the class loads DMC tables from a file and
49
+ transforms them into PyTorch tensors on the specified device.
50
+
51
+ Attributes:
52
+ device (str): Specifies the computational device (default
53
+ "cuda").
54
+ dmc_table (torch.Tensor): Dual Marching Cubes (DMC) table
55
+ that encodes the edges associated with each dual vertex
56
+ in 256 Marching Cubes (MC) configurations.
57
+ num_vd_table (torch.Tensor): Table holding the number of
58
+ dual vertices in each of the 256 MC configurations.
59
+ check_table (torch.Tensor): Table resolving ambiguity in
60
+ cases C16 and C19 of the DMC configurations.
61
+ tet_table (torch.Tensor): Lookup table used in
62
+ tetrahedralizing the isosurface.
63
+ quad_split_1 (torch.Tensor): Indices for splitting a quad
64
+ into two triangles along one diagonal.
65
+ quad_split_2 (torch.Tensor): Alternative indices for
66
+ splitting a quad into two triangles along the other
67
+ diagonal.
68
+ quad_split_train (torch.Tensor): Indices for splitting a
69
+ quad into four triangles during training by connecting
70
+ all edges to their midpoints.
71
+ cube_corners (torch.Tensor): Defines the positions of a
72
+ standard unit cube's eight corners in 3D space, ordered
73
+ starting from the origin (0,0,0), moving along the
74
+ x-axis, then y-axis, and finally z-axis. Used as a
75
+ blueprint for generating a voxel grid.
76
+ cube_corners_idx (torch.Tensor): Cube corners indexed as
77
+ powers of 2, used to retrieve the case id.
78
+ cube_edges (torch.Tensor): Edge connections in a cube,
79
+ listed in pairs. Used to retrieve edge vertices in DMC.
80
+ edge_dir_table (torch.Tensor): A mapping tensor that
81
+ associates edge indices with their corresponding axis.
82
+ For instance, edge_dir_table[0] = 0 indicates that the
83
+ first edge is oriented along the x-axis.
84
+ dir_faces_table (torch.Tensor): A tensor that maps the
85
+ corresponding axis of shared edges across four adjacent
86
+ cubes to the shared faces of these cubes. For instance,
87
+ dir_faces_table[0] = [5, 4] implies that for four cubes
88
+ sharing an edge along the x-axis, the first and second
89
+ cubes share faces indexed as 5 and 4, respectively.
90
+ This tensor is only utilized during isosurface
91
+ tetrahedralization.
92
+ adj_pairs (torch.Tensor):
93
+ A tensor containing index pairs that correspond to
94
+ neighboring cubes that share the same edge.
95
+ qef_reg_scale (float):
96
+ The scaling factor applied to the regularization loss to
97
+ prevent issues with singularity when solving the QEF.
98
+ This parameter is only used when a 'grad_func' is
99
+ specified.
100
+ weight_scale (float):
101
+ The scale of weights in flexicubes. Should be between
102
+ 0 and 1.
103
+ """
104
+
105
+ def __init__(self, device="cuda", qef_reg_scale=1e-3, weight_scale=0.99):
106
+
107
+ self.device = device
108
+ self.dmc_table = torch.tensor(
109
+ dmc_table, dtype=torch.long, device=device, requires_grad=False
110
+ )
111
+ self.num_vd_table = torch.tensor(
112
+ num_vd_table, dtype=torch.long, device=device, requires_grad=False
113
+ )
114
+ self.check_table = torch.tensor(
115
+ check_table, dtype=torch.long, device=device, requires_grad=False
116
+ )
117
+
118
+ self.tet_table = torch.tensor(
119
+ tet_table, dtype=torch.long, device=device, requires_grad=False
120
+ )
121
+ self.quad_split_1 = torch.tensor(
122
+ [0, 1, 2, 0, 2, 3], dtype=torch.long, device=device, requires_grad=False
123
+ )
124
+ self.quad_split_2 = torch.tensor(
125
+ [0, 1, 3, 3, 1, 2], dtype=torch.long, device=device, requires_grad=False
126
+ )
127
+ self.quad_split_train = torch.tensor(
128
+ [0, 1, 1, 2, 2, 3, 3, 0],
129
+ dtype=torch.long,
130
+ device=device,
131
+ requires_grad=False,
132
+ )
133
+
134
+ self.cube_corners = torch.tensor(
135
+ [
136
+ [0, 0, 0],
137
+ [1, 0, 0],
138
+ [0, 1, 0],
139
+ [1, 1, 0],
140
+ [0, 0, 1],
141
+ [1, 0, 1],
142
+ [0, 1, 1],
143
+ [1, 1, 1],
144
+ ],
145
+ device=device,
146
+ )
147
+ self.cube_corners_idx = torch.pow(2, torch.arange(8, requires_grad=False))
148
+ self.cube_edges = torch.tensor(
149
+ [0, 1, 1, 5, 4, 5, 0, 4, 2, 3, 3, 7, 6, 7, 2, 6, 2, 0, 3, 1, 7, 5, 6, 4],
150
+ dtype=torch.long,
151
+ device=device,
152
+ requires_grad=False,
153
+ )
154
+
155
+ self.edge_dir_table = torch.tensor(
156
+ [0, 2, 0, 2, 0, 2, 0, 2, 1, 1, 1, 1], dtype=torch.long, device=device
157
+ )
158
+ self.dir_faces_table = torch.tensor(
159
+ [
160
+ [[5, 4], [3, 2], [4, 5], [2, 3]],
161
+ [[5, 4], [1, 0], [4, 5], [0, 1]],
162
+ [[3, 2], [1, 0], [2, 3], [0, 1]],
163
+ ],
164
+ dtype=torch.long,
165
+ device=device,
166
+ )
167
+ self.adj_pairs = torch.tensor(
168
+ [0, 1, 1, 3, 3, 2, 2, 0], dtype=torch.long, device=device
169
+ )
170
+ self.qef_reg_scale = qef_reg_scale
171
+ self.weight_scale = weight_scale
172
+
173
+ def construct_voxel_grid(
174
+ self, resolution, bounds=None
175
+ ) -> tuple[torch.tensor, torch.tensor]:
176
+ """
177
+ Generates a voxel grid based on the specified resolution.
178
+
179
+ Args:
180
+ res (int or list[int]): The resolution of the voxel grid. If an integer
181
+ is provided, it is used for all three dimensions. If a list or tuple
182
+ of 3 integers is provided, they define the resolution for the x,
183
+ y, and z dimensions respectively.
184
+
185
+ Returns:
186
+ (torch.Tensor, torch.Tensor): Returns the vertices and the indices of the
187
+ cube corners (index into vertices) of the constructed voxel grid.
188
+ The vertices are centered at the origin, with the length of each
189
+ dimension in the grid being one.
190
+ """
191
+ res = resolution
192
+ base_cube_f = torch.arange(8).to(self.device)
193
+ if isinstance(res, int):
194
+ res = (res, res, res)
195
+ voxel_grid_template = torch.ones(res, device=self.device)
196
+
197
+ res = torch.tensor([res], device=self.device)
198
+ coords = (
199
+ torch.nonzero(voxel_grid_template).to(torch.get_default_dtype()) / res
200
+ ) # N, 3
201
+ verts = (self.cube_corners.unsqueeze(0) / res + coords.unsqueeze(1)).reshape(
202
+ -1, 3
203
+ )
204
+ cubes = (
205
+ base_cube_f.unsqueeze(0)
206
+ + torch.arange(coords.shape[0], device=self.device).unsqueeze(1) * 8
207
+ ).reshape(-1)
208
+
209
+ verts_rounded = torch.round(verts * 10**5) / (10**5)
210
+ verts_unique, inverse_indices = torch.unique(
211
+ verts_rounded, dim=0, return_inverse=True
212
+ )
213
+ cubes = inverse_indices[cubes.reshape(-1)].reshape(-1, 8)
214
+ # changes mkofler: added option to generate points in arbitrary bounds
215
+ if bounds is None:
216
+ bounds = torch.tensor(
217
+ [[-0.05, -0.05, -0.05], [1.05, 1.05, 1.05]],
218
+ device=verts_unique.device,
219
+ dtype=verts_unique.dtype,
220
+ )
221
+ else:
222
+ bounds = torch.as_tensor(
223
+ bounds, device=verts_unique.device, dtype=verts_unique.dtype
224
+ )
225
+ assert bounds.shape == (
226
+ 2,
227
+ 3,
228
+ ), f"bounds must have shape [2, 3] but have shape {bounds.shape}"
229
+
230
+ # Scale samples from [0, 1] to the given bounds
231
+ # samples = samples * 1.1 + _torch.tensor([0.5, 0.5, 0.5], device=device)
232
+ samples = verts_unique - 0.5
233
+ verts_scaled = (
234
+ bounds[0]
235
+ + 0.5 * (bounds[1] - bounds[0])
236
+ + (bounds[1] - bounds[0]) * samples
237
+ )
238
+ bounds_range = bounds[1] - bounds[0]
239
+ tolerance = torch.maximum(
240
+ torch.tensor(1e-6, device=bounds.device), 1e-6 * bounds_range.max()
241
+ )
242
+ below = verts_scaled < bounds[0] - tolerance
243
+ above = verts_scaled > bounds[1] + tolerance
244
+ if below.any() or above.any():
245
+ violations = below | above
246
+ num_violations = violations.sum().item()
247
+ max_violation = torch.maximum(
248
+ (bounds[0] - verts_scaled).max(), (verts_scaled - bounds[1]).max()
249
+ ).item()
250
+ warnings.warn(
251
+ f"{num_violations} samples are out of specified bounds by max {max_violation:.6e}. "
252
+ f"Bounds: [{bounds[0].tolist()}, {bounds[1].tolist()}]"
253
+ )
254
+ return verts_scaled, cubes
255
+
256
+ # changes mkofler: adapted function signature to match the kaolin package
257
+ # function signature on kaolin package:
258
+ # verts, faces, loss = DeepSDFStruct.flexicubes_reconstructor(voxelgrid_vertices=samples_orig[:, :3],
259
+ # scalar_field=sdf_values,
260
+ # cube_idx=cube_idx,
261
+ # resolution=tuple(N),
262
+ # output_tetmesh=output_tetmesh)
263
+ def __call__(
264
+ self,
265
+ voxelgrid_vertices,
266
+ scalar_field,
267
+ cube_idx,
268
+ resolution,
269
+ beta_fx12=None,
270
+ alpha_fx8=None,
271
+ gamma_f=None,
272
+ training=False,
273
+ output_tetmesh=False,
274
+ grad_func=None,
275
+ n_smoothing_iterations=5,
276
+ ):
277
+ r"""
278
+ Main function for mesh extraction from scalar field using
279
+ flexicubes. This function converts discrete signed distance
280
+ fields, encoded on voxel grids and additional per-cube
281
+ parameters, to triangle or tetrahedral meshes using a
282
+ differentiable operation as described in `Flexible Isosurface
283
+ Extraction for Gradient-Based Mesh Optimization`_. Flexicubes
284
+ enhances mesh quality and geometric fidelity by adjusting the
285
+ surface representation based on gradient optimization. The
286
+ output surface is differentiable with respect to the input
287
+ vertex positions, scalar field values, and weight parameters.
288
+
289
+ If you intend to extract a surface mesh from a fixed Signed
290
+ Distance Field without the optimization of parameters, it is
291
+ suggested to provide the "grad_func" which should return the
292
+ surface gradient at any given 3D position. When grad_func is
293
+ provided, the process to determine the dual vertex position
294
+ adapts to solve a Quadratic Error Function (QEF), as
295
+ described in the `Manifold Dual Contouring`_ paper, and
296
+ employs a smart splitting strategy. Please note, this
297
+ approach is non-differentiable.
298
+
299
+ For more details and example usage in optimization, refer to
300
+ the `Flexible Isosurface Extraction for Gradient-Based Mesh
301
+ Optimization`_ SIGGRAPH 2023 paper.
302
+
303
+ Args:
304
+ x_nx3 (torch.Tensor): Coordinates of the voxel grid
305
+ vertices, can be deformed.
306
+ s_n (torch.Tensor): Scalar field values at each vertex
307
+ of the voxel grid. Negative values denote that the
308
+ corresponding vertex resides inside the isosurface.
309
+ This affects the directions of the extracted triangle
310
+ faces and volume to be tetrahedralized.
311
+ cube_fx8 (torch.Tensor): Indices of 8 vertices for each cube in the voxel grid.
312
+ res (int or list[int]): The resolution of the voxel grid. If an integer is provided, it
313
+ is used for all three dimensions. If a list or tuple of 3 integers is provided, they
314
+ specify the resolution for the x, y, and z dimensions respectively.
315
+ beta_fx12 (torch.Tensor, optional): Weight parameters for the cube edges to adjust dual
316
+ vertices positioning. Defaults to uniform value for all edges.
317
+ alpha_fx8 (torch.Tensor, optional): Weight parameters for the cube corners to adjust dual
318
+ vertices positioning. Defaults to uniform value for all vertices.
319
+ gamma_f (torch.Tensor, optional): Weight parameters to control the splitting of
320
+ quadrilaterals into triangles. Defaults to uniform value for all cubes.
321
+ training (bool, optional): If set to True, applies differentiable quad splitting for
322
+ training. Defaults to False.
323
+ output_tetmesh (bool, optional): If set to True, outputs a tetrahedral mesh, otherwise,
324
+ outputs a triangular mesh. Defaults to False.
325
+ grad_func (callable, optional): A function to compute the surface gradient at specified
326
+ 3D positions (input: Nx3 positions). The function should return gradients as an Nx3
327
+ tensor. If None, the original DeepSDFStruct.flexicubes algorithm is utilized. Defaults to None.
328
+
329
+ Returns:
330
+ (torch.Tensor, torch.LongTensor, torch.Tensor): Tuple containing:
331
+ - Vertices for the extracted triangular/tetrahedral mesh.
332
+ - Faces for the extracted triangular/tetrahedral mesh.
333
+ - Regularizer L_dev, computed per dual vertex.
334
+
335
+ .. _Flexible Isosurface Extraction for Gradient-Based Mesh Optimization:
336
+ https://research.nvidia.com/labs/toronto-ai/DeepSDFStruct.flexicubes/
337
+ .. _Manifold Dual Contouring:
338
+ https://people.engr.tamu.edu/schaefer/research/dualsimp_tvcg.pdf
339
+ """
340
+ x_nx3 = voxelgrid_vertices
341
+ s_n = scalar_field
342
+ cube_fx8 = cube_idx
343
+ res = resolution
344
+ surf_cubes, occ_fx8 = self._identify_surf_cubes(s_n, cube_fx8)
345
+ if surf_cubes.sum() == 0:
346
+ return (
347
+ torch.zeros((0, 3), device=self.device),
348
+ (
349
+ torch.zeros((0, 4), dtype=torch.long, device=self.device)
350
+ if output_tetmesh
351
+ else torch.zeros((0, 3), dtype=torch.long, device=self.device)
352
+ ),
353
+ torch.zeros((0), device=self.device),
354
+ )
355
+ beta_fx12, alpha_fx8, gamma_f = self._normalize_weights(
356
+ beta_fx12, alpha_fx8, gamma_f, surf_cubes
357
+ )
358
+
359
+ case_ids = self._get_case_id(occ_fx8, surf_cubes, res)
360
+
361
+ surf_edges, idx_map, edge_counts, surf_edges_mask = self._identify_surf_edges(
362
+ s_n, cube_fx8, surf_cubes
363
+ )
364
+
365
+ vd, L_dev, vd_gamma, vd_idx_map = self._compute_vd(
366
+ x_nx3,
367
+ cube_fx8[surf_cubes],
368
+ surf_edges,
369
+ s_n,
370
+ case_ids,
371
+ beta_fx12,
372
+ alpha_fx8,
373
+ gamma_f,
374
+ idx_map,
375
+ grad_func,
376
+ )
377
+ vertices, faces, s_edges, edge_indices = self._triangulate(
378
+ s_n,
379
+ surf_edges,
380
+ vd,
381
+ vd_gamma,
382
+ edge_counts,
383
+ idx_map,
384
+ vd_idx_map,
385
+ surf_edges_mask,
386
+ training,
387
+ grad_func,
388
+ )
389
+ if not output_tetmesh:
390
+ return vertices, faces, L_dev
391
+ else:
392
+ vertices, tets = self._tetrahedralize(
393
+ x_nx3,
394
+ s_n,
395
+ cube_fx8,
396
+ vertices,
397
+ faces,
398
+ surf_edges,
399
+ s_edges,
400
+ vd_idx_map,
401
+ case_ids,
402
+ edge_indices,
403
+ surf_cubes,
404
+ training,
405
+ )
406
+ return vertices, tets, L_dev
407
+
408
+ def _compute_reg_loss(self, vd, ue, edge_group_to_vd, vd_num_edges):
409
+ """
410
+ Regularizer L_dev as in Equation 8
411
+ """
412
+ dist = torch.norm(
413
+ ue - torch.index_select(input=vd, index=edge_group_to_vd, dim=0), dim=-1
414
+ )
415
+ mean_l2 = torch.zeros_like(vd[:, 0])
416
+ mean_l2 = (mean_l2).index_add_(
417
+ 0, edge_group_to_vd, dist
418
+ ) / vd_num_edges.squeeze(1).to(torch.get_default_dtype())
419
+ mad = (
420
+ dist - torch.index_select(input=mean_l2, index=edge_group_to_vd, dim=0)
421
+ ).abs()
422
+ return mad
423
+
424
+ def _normalize_weights(self, beta_fx12, alpha_fx8, gamma_f, surf_cubes):
425
+ """
426
+ Normalizes the given weights to be non-negative. If input weights are None, it creates and returns a set of weights of ones.
427
+ """
428
+ n_cubes = surf_cubes.shape[0]
429
+
430
+ if beta_fx12 is not None:
431
+ beta_fx12 = torch.tanh(beta_fx12) * self.weight_scale + 1
432
+ else:
433
+ beta_fx12 = torch.ones((n_cubes, 12), device=self.device)
434
+
435
+ if alpha_fx8 is not None:
436
+ alpha_fx8 = torch.tanh(alpha_fx8) * self.weight_scale + 1
437
+ else:
438
+ alpha_fx8 = torch.ones((n_cubes, 8), device=self.device)
439
+
440
+ if gamma_f is not None:
441
+ gamma_f = (
442
+ torch.sigmoid(gamma_f) * self.weight_scale + (1 - self.weight_scale) / 2
443
+ )
444
+ else:
445
+ gamma_f = torch.ones((n_cubes), device=self.device)
446
+
447
+ return beta_fx12[surf_cubes], alpha_fx8[surf_cubes], gamma_f[surf_cubes]
448
+
449
+ @torch.no_grad()
450
+ def _get_case_id(self, occ_fx8, surf_cubes, res):
451
+ """
452
+ Obtains the ID of topology cases based on cell corner occupancy. This function resolves the
453
+ ambiguity in the Dual Marching Cubes (DMC) configurations as described in Section 1.3 of the
454
+ supplementary material. It should be noted that this function assumes a regular grid.
455
+ """
456
+ case_ids = (
457
+ occ_fx8[surf_cubes] * self.cube_corners_idx.to(self.device).unsqueeze(0)
458
+ ).sum(-1)
459
+
460
+ problem_config = self.check_table.to(self.device)[case_ids]
461
+ to_check = problem_config[..., 0] == 1
462
+ problem_config = problem_config[to_check]
463
+ if not isinstance(res, (list, tuple)):
464
+ res = [res, res, res]
465
+
466
+ # The 'problematic_configs' only contain configurations for surface cubes. Next, we construct a 3D array,
467
+ # 'problem_config_full', to store configurations for all cubes (with default config for non-surface cubes).
468
+ # This allows efficient checking on adjacent cubes.
469
+ problem_config_full = torch.zeros(
470
+ list(res) + [5], device=self.device, dtype=torch.long
471
+ )
472
+ vol_idx = torch.nonzero(problem_config_full[..., 0] == 0) # N, 3
473
+ vol_idx_problem = vol_idx[surf_cubes][to_check]
474
+ problem_config_full[
475
+ vol_idx_problem[..., 0], vol_idx_problem[..., 1], vol_idx_problem[..., 2]
476
+ ] = problem_config
477
+ vol_idx_problem_adj = vol_idx_problem + problem_config[..., 1:4]
478
+
479
+ within_range = (
480
+ (vol_idx_problem_adj[..., 0] >= 0)
481
+ & (vol_idx_problem_adj[..., 0] < res[0])
482
+ & (vol_idx_problem_adj[..., 1] >= 0)
483
+ & (vol_idx_problem_adj[..., 1] < res[1])
484
+ & (vol_idx_problem_adj[..., 2] >= 0)
485
+ & (vol_idx_problem_adj[..., 2] < res[2])
486
+ )
487
+
488
+ vol_idx_problem = vol_idx_problem[within_range]
489
+ vol_idx_problem_adj = vol_idx_problem_adj[within_range]
490
+ problem_config = problem_config[within_range]
491
+ problem_config_adj = problem_config_full[
492
+ vol_idx_problem_adj[..., 0],
493
+ vol_idx_problem_adj[..., 1],
494
+ vol_idx_problem_adj[..., 2],
495
+ ]
496
+ # If two cubes with cases C16 and C19 share an ambiguous face, both cases are inverted.
497
+ to_invert = problem_config_adj[..., 0] == 1
498
+ idx = torch.arange(case_ids.shape[0], device=self.device)[to_check][
499
+ within_range
500
+ ][to_invert]
501
+ case_ids.index_put_((idx,), problem_config[to_invert][..., -1])
502
+ return case_ids
503
+
504
+ @torch.no_grad()
505
+ def _identify_surf_edges(self, s_n, cube_fx8, surf_cubes):
506
+ """
507
+ Identifies grid edges that intersect with the underlying surface by checking for opposite signs. As each edge
508
+ can be shared by multiple cubes, this function also assigns a unique index to each surface-intersecting edge
509
+ and marks the cube edges with this index.
510
+ """
511
+ occ_n = s_n < 0
512
+ all_edges = cube_fx8[surf_cubes][:, self.cube_edges].reshape(-1, 2)
513
+ unique_edges, _idx_map, counts = torch.unique(
514
+ all_edges, dim=0, return_inverse=True, return_counts=True
515
+ )
516
+
517
+ unique_edges = unique_edges.long()
518
+ mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1
519
+
520
+ surf_edges_mask = mask_edges[_idx_map]
521
+ counts = counts[_idx_map]
522
+
523
+ mapping = (
524
+ torch.ones(
525
+ (unique_edges.shape[0]), dtype=torch.long, device=cube_fx8.device
526
+ )
527
+ * -1
528
+ )
529
+ mapping[mask_edges] = torch.arange(mask_edges.sum(), device=cube_fx8.device)
530
+ # Shaped as [number of cubes x 12 edges per cube]. This is later used to map a cube edge to the unique index
531
+ # for a surface-intersecting edge. Non-surface-intersecting edges are marked with -1.
532
+ idx_map = mapping[_idx_map]
533
+ surf_edges = unique_edges[mask_edges]
534
+ return surf_edges, idx_map, counts, surf_edges_mask
535
+
536
+ @torch.no_grad()
537
+ def _identify_surf_cubes(self, s_n, cube_fx8):
538
+ """
539
+ Identifies grid cubes that intersect with the underlying surface by checking if the signs at
540
+ all corners are not identical.
541
+ """
542
+ occ_n = s_n < 0
543
+ occ_fx8 = occ_n[cube_fx8.reshape(-1)].reshape(-1, 8)
544
+ _occ_sum = torch.sum(occ_fx8, -1)
545
+ surf_cubes = (_occ_sum > 0) & (_occ_sum < 8)
546
+ return surf_cubes, occ_fx8
547
+
548
+ def _linear_interp(self, edges_weight, edges_x):
549
+ """
550
+ Computes the location of zero-crossings on 'edges_x' using linear interpolation with 'edges_weight'.
551
+ """
552
+ edge_dim = edges_weight.dim() - 2
553
+ assert edges_weight.shape[edge_dim] == 2
554
+ edges_weight = torch.cat(
555
+ [
556
+ torch.index_select(
557
+ input=edges_weight,
558
+ index=torch.tensor(
559
+ [1], device=self.device
560
+ ), # change mkofler: 1 -> [1]
561
+ dim=edge_dim,
562
+ ),
563
+ -torch.index_select(
564
+ input=edges_weight,
565
+ index=torch.tensor(
566
+ [0], device=self.device
567
+ ), # change mkofler: 0 -> [0]
568
+ dim=edge_dim,
569
+ ),
570
+ ],
571
+ edge_dim,
572
+ )
573
+ denominator = edges_weight.sum(edge_dim)
574
+ ue = (edges_x * edges_weight).sum(edge_dim) / denominator
575
+ return ue
576
+
577
+ def _solve_vd_QEF(self, p_bxnx3, norm_bxnx3, c_bx3=None):
578
+ p_bxnx3 = p_bxnx3.reshape(-1, 7, 3)
579
+ norm_bxnx3 = norm_bxnx3.reshape(-1, 7, 3)
580
+ c_bx3 = c_bx3.reshape(-1, 3)
581
+ A = norm_bxnx3
582
+ B = ((p_bxnx3) * norm_bxnx3).sum(-1, keepdims=True)
583
+
584
+ A_reg = (
585
+ (torch.eye(3, device=p_bxnx3.device) * self.qef_reg_scale)
586
+ .unsqueeze(0)
587
+ .repeat(p_bxnx3.shape[0], 1, 1)
588
+ )
589
+ B_reg = (self.qef_reg_scale * c_bx3).unsqueeze(-1)
590
+ A = torch.cat([A, A_reg], 1)
591
+ B = torch.cat([B, B_reg], 1)
592
+ dual_verts = torch.linalg.lstsq(A, B).solution.squeeze(-1)
593
+ return dual_verts
594
+
595
+ def _compute_vd(
596
+ self,
597
+ x_nx3,
598
+ surf_cubes_fx8,
599
+ surf_edges,
600
+ s_n,
601
+ case_ids,
602
+ beta_fx12,
603
+ alpha_fx8,
604
+ gamma_f,
605
+ idx_map,
606
+ grad_func,
607
+ ):
608
+ """
609
+ Computes the location of dual vertices as described in Section 4.2
610
+ """
611
+ alpha_nx12x2 = torch.index_select(
612
+ input=alpha_fx8, index=self.cube_edges, dim=1
613
+ ).reshape(-1, 12, 2)
614
+ surf_edges_x = torch.index_select(
615
+ input=x_nx3, index=surf_edges.reshape(-1), dim=0
616
+ ).reshape(-1, 2, 3)
617
+ surf_edges_s = torch.index_select(
618
+ input=s_n, index=surf_edges.reshape(-1), dim=0
619
+ ).reshape(-1, 2, 1)
620
+ zero_crossing = self._linear_interp(surf_edges_s, surf_edges_x)
621
+
622
+ idx_map = idx_map.reshape(-1, 12)
623
+ num_vd = torch.index_select(input=self.num_vd_table, index=case_ids, dim=0)
624
+ edge_group, edge_group_to_vd, edge_group_to_cube, vd_num_edges, vd_gamma = (
625
+ [],
626
+ [],
627
+ [],
628
+ [],
629
+ [],
630
+ )
631
+
632
+ total_num_vd = 0
633
+ vd_idx_map = torch.zeros(
634
+ (case_ids.shape[0], 12),
635
+ dtype=torch.long,
636
+ device=self.device,
637
+ requires_grad=False,
638
+ )
639
+ if grad_func is not None:
640
+ normals = torch.nn.functional.normalize(grad_func(zero_crossing), dim=-1)
641
+ vd = []
642
+ for num in torch.unique(num_vd):
643
+ cur_cubes = (
644
+ num_vd == num
645
+ ) # consider cubes with the same numbers of vd emitted (for batching)
646
+ curr_num_vd = cur_cubes.sum() * num
647
+ curr_edge_group = self.dmc_table[case_ids[cur_cubes], :num].reshape(
648
+ -1, num * 7
649
+ )
650
+ curr_edge_group_to_vd = (
651
+ torch.arange(curr_num_vd, device=self.device).unsqueeze(-1).repeat(1, 7)
652
+ + total_num_vd
653
+ )
654
+ total_num_vd += curr_num_vd
655
+ curr_edge_group_to_cube = (
656
+ torch.arange(idx_map.shape[0], device=self.device)[cur_cubes]
657
+ .unsqueeze(-1)
658
+ .repeat(1, num * 7)
659
+ .reshape_as(curr_edge_group)
660
+ )
661
+
662
+ curr_mask = curr_edge_group != -1
663
+ edge_group.append(torch.masked_select(curr_edge_group, curr_mask))
664
+ edge_group_to_vd.append(
665
+ torch.masked_select(
666
+ curr_edge_group_to_vd.reshape_as(curr_edge_group), curr_mask
667
+ )
668
+ )
669
+ edge_group_to_cube.append(
670
+ torch.masked_select(curr_edge_group_to_cube, curr_mask)
671
+ )
672
+ vd_num_edges.append(curr_mask.reshape(-1, 7).sum(-1, keepdims=True))
673
+ vd_gamma.append(
674
+ torch.masked_select(gamma_f, cur_cubes)
675
+ .unsqueeze(-1)
676
+ .repeat(1, num)
677
+ .reshape(-1)
678
+ )
679
+
680
+ if grad_func is not None:
681
+ with torch.no_grad():
682
+ cube_e_verts_idx = idx_map[cur_cubes]
683
+ curr_edge_group[~curr_mask] = 0
684
+
685
+ verts_group_idx = torch.gather(
686
+ input=cube_e_verts_idx, dim=1, index=curr_edge_group
687
+ )
688
+ verts_group_idx[verts_group_idx == -1] = 0
689
+ verts_group_pos = torch.index_select(
690
+ input=zero_crossing, index=verts_group_idx.reshape(-1), dim=0
691
+ ).reshape(-1, num.item(), 7, 3)
692
+ v0 = (
693
+ x_nx3[surf_cubes_fx8[cur_cubes][:, 0]]
694
+ .reshape(-1, 1, 1, 3)
695
+ .repeat(1, num.item(), 1, 1)
696
+ )
697
+ curr_mask = curr_mask.reshape(-1, num.item(), 7, 1)
698
+ verts_centroid = (verts_group_pos * curr_mask).sum(2) / (
699
+ curr_mask.sum(2)
700
+ )
701
+
702
+ normals_bx7x3 = torch.index_select(
703
+ input=normals, index=verts_group_idx.reshape(-1), dim=0
704
+ ).reshape(-1, num.item(), 7, 3)
705
+ curr_mask = curr_mask.squeeze(2)
706
+ vd.append(
707
+ self._solve_vd_QEF(
708
+ (verts_group_pos - v0) * curr_mask,
709
+ normals_bx7x3 * curr_mask,
710
+ verts_centroid - v0.squeeze(2),
711
+ )
712
+ + v0.reshape(-1, 3)
713
+ )
714
+ edge_group = torch.cat(edge_group)
715
+ edge_group_to_vd = torch.cat(edge_group_to_vd)
716
+ edge_group_to_cube = torch.cat(edge_group_to_cube)
717
+ vd_num_edges = torch.cat(vd_num_edges)
718
+ vd_gamma = torch.cat(vd_gamma)
719
+
720
+ if grad_func is not None:
721
+ vd = torch.cat(vd)
722
+ L_dev = torch.zeros([1], device=self.device)
723
+ else:
724
+ vd = torch.zeros((total_num_vd, 3), device=self.device)
725
+ beta_sum = torch.zeros((total_num_vd, 1), device=self.device)
726
+
727
+ idx_group = torch.gather(
728
+ input=idx_map.reshape(-1),
729
+ dim=0,
730
+ index=edge_group_to_cube * 12 + edge_group,
731
+ )
732
+
733
+ x_group = torch.index_select(
734
+ input=surf_edges_x, index=idx_group.reshape(-1), dim=0
735
+ ).reshape(-1, 2, 3)
736
+ s_group = torch.index_select(
737
+ input=surf_edges_s, index=idx_group.reshape(-1), dim=0
738
+ ).reshape(-1, 2, 1)
739
+
740
+ zero_crossing_group = torch.index_select(
741
+ input=zero_crossing, index=idx_group.reshape(-1), dim=0
742
+ ).reshape(-1, 3)
743
+
744
+ alpha_group = torch.index_select(
745
+ input=alpha_nx12x2.reshape(-1, 2),
746
+ dim=0,
747
+ index=edge_group_to_cube * 12 + edge_group,
748
+ ).reshape(-1, 2, 1)
749
+ ue_group = self._linear_interp(s_group * alpha_group, x_group)
750
+
751
+ beta_group = torch.gather(
752
+ input=beta_fx12.reshape(-1),
753
+ dim=0,
754
+ index=edge_group_to_cube * 12 + edge_group,
755
+ ).reshape(-1, 1)
756
+ beta_sum = beta_sum.index_add_(0, index=edge_group_to_vd, source=beta_group)
757
+ vd = (
758
+ vd.index_add_(0, index=edge_group_to_vd, source=ue_group * beta_group)
759
+ / beta_sum
760
+ )
761
+ L_dev = self._compute_reg_loss(
762
+ vd, zero_crossing_group, edge_group_to_vd, vd_num_edges
763
+ )
764
+
765
+ v_idx = torch.arange(vd.shape[0], device=self.device) # + total_num_vd
766
+
767
+ vd_idx_map = (vd_idx_map.reshape(-1)).scatter(
768
+ dim=0,
769
+ index=edge_group_to_cube * 12 + edge_group,
770
+ src=v_idx[edge_group_to_vd],
771
+ )
772
+
773
+ return vd, L_dev, vd_gamma, vd_idx_map
774
+
775
+ def _triangulate(
776
+ self,
777
+ s_n,
778
+ surf_edges,
779
+ vd,
780
+ vd_gamma,
781
+ edge_counts,
782
+ idx_map,
783
+ vd_idx_map,
784
+ surf_edges_mask,
785
+ training,
786
+ grad_func,
787
+ ):
788
+ """
789
+ Connects four neighboring dual vertices to form a quadrilateral. The quadrilaterals are then split into
790
+ triangles based on the gamma parameter, as described in Section 4.3.
791
+ """
792
+ with torch.no_grad():
793
+ group_mask = (
794
+ edge_counts == 4
795
+ ) & surf_edges_mask # surface edges shared by 4 cubes.
796
+ group = idx_map.reshape(-1)[group_mask]
797
+ vd_idx = vd_idx_map[group_mask]
798
+ edge_indices, indices = torch.sort(group, stable=True)
799
+ quad_vd_idx = vd_idx[indices].reshape(-1, 4)
800
+
801
+ # Ensure all face directions point towards the positive SDF to maintain consistent winding.
802
+ s_edges = s_n[
803
+ surf_edges[edge_indices.reshape(-1, 4)[:, 0]].reshape(-1)
804
+ ].reshape(-1, 2)
805
+ flip_mask = s_edges[:, 0] > 0
806
+ quad_vd_idx[flip_mask] = quad_vd_idx[flip_mask][:, [0, 1, 3, 2]]
807
+ quad_vd_idx[~flip_mask] = quad_vd_idx[~flip_mask][:, [2, 3, 1, 0]]
808
+ if grad_func is not None:
809
+ # when grad_func is given, split quadrilaterals along the diagonals with more consistent gradients.
810
+ with torch.no_grad():
811
+ vd_gamma = torch.nn.functional.normalize(grad_func(vd), dim=-1)
812
+ quad_gamma = torch.index_select(
813
+ input=vd_gamma, index=quad_vd_idx.reshape(-1), dim=0
814
+ ).reshape(-1, 4, 3)
815
+ gamma_02 = (quad_gamma[:, 0] * quad_gamma[:, 2]).sum(-1, keepdims=True)
816
+ gamma_13 = (quad_gamma[:, 1] * quad_gamma[:, 3]).sum(-1, keepdims=True)
817
+ else:
818
+ quad_gamma = torch.index_select(
819
+ input=vd_gamma, index=quad_vd_idx.reshape(-1), dim=0
820
+ ).reshape(-1, 4)
821
+ gamma_02 = torch.index_select(
822
+ input=quad_gamma, index=torch.tensor(0, device=self.device), dim=1
823
+ ) * torch.index_select(
824
+ input=quad_gamma, index=torch.tensor(2, device=self.device), dim=1
825
+ )
826
+ gamma_13 = torch.index_select(
827
+ input=quad_gamma, index=torch.tensor(1, device=self.device), dim=1
828
+ ) * torch.index_select(
829
+ input=quad_gamma, index=torch.tensor(3, device=self.device), dim=1
830
+ )
831
+ if not training:
832
+ mask = (gamma_02 > gamma_13).squeeze(1)
833
+ faces = torch.zeros(
834
+ (quad_gamma.shape[0], 6), dtype=torch.long, device=quad_vd_idx.device
835
+ )
836
+ faces[mask] = quad_vd_idx[mask][:, self.quad_split_1]
837
+ faces[~mask] = quad_vd_idx[~mask][:, self.quad_split_2]
838
+ faces = faces.reshape(-1, 3)
839
+ else:
840
+ vd_quad = torch.index_select(
841
+ input=vd, index=quad_vd_idx.reshape(-1), dim=0
842
+ ).reshape(-1, 4, 3)
843
+ vd_02 = (
844
+ torch.index_select(
845
+ input=vd_quad, index=torch.tensor(0, device=self.device), dim=1
846
+ )
847
+ + torch.index_select(
848
+ input=vd_quad, index=torch.tensor(2, device=self.device), dim=1
849
+ )
850
+ ) / 2
851
+ vd_13 = (
852
+ torch.index_select(
853
+ input=vd_quad, index=torch.tensor(1, device=self.device), dim=1
854
+ )
855
+ + torch.index_select(
856
+ input=vd_quad, index=torch.tensor(3, device=self.device), dim=1
857
+ )
858
+ ) / 2
859
+ weight_sum = (gamma_02 + gamma_13) + 1e-8
860
+ vd_center = (
861
+ (vd_02 * gamma_02.unsqueeze(-1) + vd_13 * gamma_13.unsqueeze(-1))
862
+ / weight_sum.unsqueeze(-1)
863
+ ).squeeze(1)
864
+ vd_center_idx = (
865
+ torch.arange(vd_center.shape[0], device=self.device) + vd.shape[0]
866
+ )
867
+ vd = torch.cat([vd, vd_center])
868
+ faces = quad_vd_idx[:, self.quad_split_train].reshape(-1, 4, 2)
869
+ faces = torch.cat(
870
+ [faces, vd_center_idx.reshape(-1, 1, 1).repeat(1, 4, 1)], -1
871
+ ).reshape(-1, 3)
872
+ return vd, faces, s_edges, edge_indices
873
+
874
+ def _tetrahedralize(
875
+ self,
876
+ x_nx3,
877
+ s_n,
878
+ cube_fx8,
879
+ vertices,
880
+ faces,
881
+ surf_edges,
882
+ s_edges,
883
+ vd_idx_map,
884
+ case_ids,
885
+ edge_indices,
886
+ surf_cubes,
887
+ training,
888
+ ):
889
+ """
890
+ Tetrahedralizes the interior volume to produce a tetrahedral mesh, as described in Section 4.5.
891
+ """
892
+ occ_n = s_n < 0
893
+ occ_fx8 = occ_n[cube_fx8.reshape(-1)].reshape(-1, 8)
894
+ occ_sum = torch.sum(occ_fx8, -1)
895
+
896
+ inside_verts = x_nx3[occ_n]
897
+ mapping_inside_verts = (
898
+ torch.ones((occ_n.shape[0]), dtype=torch.long, device=self.device) * -1
899
+ )
900
+ mapping_inside_verts[occ_n] = (
901
+ torch.arange(occ_n.sum(), device=self.device) + vertices.shape[0]
902
+ )
903
+ """
904
+ For each grid edge connecting two grid vertices with different
905
+ signs, we first form a four-sided pyramid by connecting one
906
+ of the grid vertices with four mesh vertices that correspond
907
+ to the grid edge and then subdivide the pyramid into two tetrahedra
908
+ """
909
+ inside_verts_idx = mapping_inside_verts[
910
+ surf_edges[edge_indices.reshape(-1, 4)[:, 0]].reshape(-1, 2)[s_edges < 0]
911
+ ]
912
+ if not training:
913
+ inside_verts_idx = inside_verts_idx.unsqueeze(1).expand(-1, 2).reshape(-1)
914
+ else:
915
+ inside_verts_idx = inside_verts_idx.unsqueeze(1).expand(-1, 4).reshape(-1)
916
+
917
+ tets_surface = torch.cat([faces, inside_verts_idx.unsqueeze(-1)], -1)
918
+ """
919
+ For each grid edge connecting two grid vertices with the
920
+ same sign, the tetrahedron is formed by the two grid vertices
921
+ and two vertices in consecutive adjacent cells
922
+ """
923
+ inside_cubes = occ_sum == 8
924
+ inside_cubes_center = (
925
+ x_nx3[cube_fx8[inside_cubes].reshape(-1)].reshape(-1, 8, 3).mean(1)
926
+ )
927
+ inside_cubes_center_idx = (
928
+ torch.arange(inside_cubes_center.shape[0], device=inside_cubes.device)
929
+ + vertices.shape[0]
930
+ + inside_verts.shape[0]
931
+ )
932
+
933
+ surface_n_inside_cubes = surf_cubes | inside_cubes
934
+ edge_center_vertex_idx = (
935
+ torch.ones(
936
+ ((surface_n_inside_cubes).sum(), 13),
937
+ dtype=torch.long,
938
+ device=x_nx3.device,
939
+ )
940
+ * -1
941
+ )
942
+ surf_cubes = surf_cubes[surface_n_inside_cubes]
943
+ inside_cubes = inside_cubes[surface_n_inside_cubes]
944
+ edge_center_vertex_idx[surf_cubes, :12] = vd_idx_map.reshape(-1, 12)
945
+ edge_center_vertex_idx[inside_cubes, 12] = inside_cubes_center_idx
946
+
947
+ all_edges = cube_fx8[surface_n_inside_cubes][:, self.cube_edges].reshape(-1, 2)
948
+ unique_edges, _idx_map, counts = torch.unique(
949
+ all_edges, dim=0, return_inverse=True, return_counts=True
950
+ )
951
+ unique_edges = unique_edges.long()
952
+ mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 2
953
+ mask = mask_edges[_idx_map]
954
+ counts = counts[_idx_map]
955
+ mapping = (
956
+ torch.ones((unique_edges.shape[0]), dtype=torch.long, device=self.device)
957
+ * -1
958
+ )
959
+ mapping[mask_edges] = torch.arange(mask_edges.sum(), device=self.device)
960
+ idx_map = mapping[_idx_map]
961
+
962
+ group_mask = (counts == 4) & mask
963
+ group = idx_map.reshape(-1)[group_mask]
964
+ edge_indices, indices = torch.sort(group)
965
+ cube_idx = (
966
+ torch.arange(
967
+ (_idx_map.shape[0] // 12), dtype=torch.long, device=self.device
968
+ )
969
+ .unsqueeze(1)
970
+ .expand(-1, 12)
971
+ .reshape(-1)[group_mask]
972
+ )
973
+ edge_idx = (
974
+ torch.arange((12), dtype=torch.long, device=self.device)
975
+ .unsqueeze(0)
976
+ .expand(_idx_map.shape[0] // 12, -1)
977
+ .reshape(-1)[group_mask]
978
+ )
979
+ # Identify the face shared by the adjacent cells.
980
+ cube_idx_4 = cube_idx[indices].reshape(-1, 4)
981
+ edge_dir = self.edge_dir_table[edge_idx[indices]].reshape(-1, 4)[..., 0]
982
+ shared_faces_4x2 = self.dir_faces_table[edge_dir].reshape(-1)
983
+ cube_idx_4x2 = cube_idx_4[:, self.adj_pairs].reshape(-1)
984
+ # Identify an edge of the face with different signs and
985
+ # select the mesh vertex corresponding to the identified edge.
986
+ case_ids_expand = (
987
+ torch.ones(
988
+ (surface_n_inside_cubes).sum(), dtype=torch.long, device=x_nx3.device
989
+ )
990
+ * 255
991
+ )
992
+ case_ids_expand[surf_cubes] = case_ids
993
+ cases = case_ids_expand[cube_idx_4x2]
994
+ quad_edge = edge_center_vertex_idx[
995
+ cube_idx_4x2, self.tet_table[cases, shared_faces_4x2]
996
+ ].reshape(-1, 2)
997
+ mask = (quad_edge == -1).sum(-1) == 0
998
+ inside_edge = mapping_inside_verts[
999
+ unique_edges[mask_edges][edge_indices].reshape(-1)
1000
+ ].reshape(-1, 2)
1001
+ tets_inside = torch.cat([quad_edge, inside_edge], -1)[mask]
1002
+
1003
+ tets = torch.cat([tets_surface, tets_inside])
1004
+ vertices = torch.cat([vertices, inside_verts, inside_cubes_center])
1005
+ return vertices, tets