This class implements the FlexiCubes method for extracting meshes from scalar fields. It maintains a series of lookup tables and indices to support the mesh extraction process. FlexiCubes, a differentiable variant of the Dual Marching Cubes (DMC) scheme, enhances the geometric fidelity and mesh quality of reconstructed meshes by dynamically adjusting the surface representation through gradient-based optimization.
During instantiation, the class loads DMC tables from a file and transforms them into PyTorch tensors on the specified device.
Note
For more details and example usage in optimization, refer to the Flexible Isosurface Extraction for Gradient-Based Mesh Optimization SIGGRAPH 2023 paper, and the project page.
Dual Marching Cubes (DMC) table that encodes the edges associated with each dual vertex in 256 Marching Cubes (MC) configurations.
Table holding the number of dual vertices in each of the 256 MC configurations.
Table resolving ambiguity in cases C16 and C19 of the DMC configurations.
Lookup table used in tetrahedralizing the isosurface.
Indices for splitting a quad into two triangles along one diagonal.
Alternative indices for splitting a quad into two triangles along the other diagonal.
Indices for splitting a quad into four triangles during training by connecting all edges to their midpoints.
Defines the positions of a standard unit cube’s eight corners in 3D space, ordered starting from the origin (0,0,0), moving along the x-axis, then y-axis, and finally z-axis. Used as a blueprint for generating a voxel grid.
Cube corners indexed as powers of 2, used to retrieve the case id.
Edge connections in a cube, listed in pairs. Used to retrieve edge vertices in DMC.
A mapping tensor that associates edge indices with their corresponding axis. For instance, edge_dir_table[0] = 0 indicates that the first edge is oriented along the x-axis.
A tensor that maps the corresponding axis of shared edges across four adjacent cubes to the shared faces of these cubes. For instance, dir_faces_table[0] = [5, 4] implies that for four cubes sharing an edge along the x-axis, the first and second cubes share faces indexed as 5 and 4, respectively. This tensor is only utilized during isosurface tetrahedralization.
A tensor containing index pairs that correspond to neighboring cubes that share the same edge.
Main function for mesh extraction from scalar field using FlexiCubes. This function converts discrete signed distance fields, encoded on voxel grids and additional per-cube parameters, to triangle or tetrahedral meshes using a differentiable operation as described in Flexible Isosurface Extraction for Gradient-Based Mesh Optimization. FlexiCubes enhances mesh quality and geometric fidelity by adjusting the surface representation based on gradient optimization. The output surface is differentiable with respect to the input vertex positions, scalar field values, and weight parameters.
If you intend to extract a surface mesh from a fixed Signed Distance Field without the optimization of parameters, it is suggested to provide the “grad_func” which should return the surface gradient at any given 3D position. When grad_func is provided, the process to determine the dual vertex position adapts to solve a Quadratic Error Function (QEF), as described in the Manifold Dual Contouring paper, and employs an smart splitting strategy. Please note, this approach is non-differentiable.
For more details and example usage in optimization, refer to the Flexible Isosurface Extraction for Gradient-Based Mesh Optimization SIGGRAPH 2023 paper.
voxelgrid_vertices (torch.Tensor) – Coordinates of the voxel grid vertices, can be deformed, of shape \((\text{num_vertices}, 3)\).
scalar_field (torch.Tensor) – Scalar field values at each vertex of the voxel grid. Negative values denote that the corresponding vertex resides inside the isosurface, of shape \((\text{num_vertices},)\). This affects the directions of the extracted triangle faces and volume to be tetrahedralized.
cube_idx (torch.Tensor) – Indices of 8 vertices for each cube in the voxel grid, of shape \((\text{num_cube}, 8)\).
resolution (int or list[int]) – The resolution of the voxel grid. If an integer is provided, it is used for all three dimensions. If a list or tuple of 3 integers is provided, they specify the resolution for the x, y, and z dimensions respectively.
qef_reg_scale (float, optional) – The scaling factor applied to the regularization loss to prevent issues with singularity when solving the QEF. This parameter is only used when a ‘grad_func’ is specified. Default: 1e-3.
weight_scale (float, optional) – The scale of weights in FlexiCubes. Should be between 0 and 1. Default: 0.99.
beta (torch.Tensor, optional) – Weight parameters for the cube edges to adjust dual vertices positioning, of shape \((\text{num_cube}, 12)\). Default: uniform value for all edges.
alpha (torch.Tensor, optional) – Weight parameters for the cube corners to adjust dual vertices positioning, of shape \((\text{num_cubes}, 8)\). Default: uniform value for all vertices.
gamma_f (torch.Tensor, optional) – Weight parameters to control the splitting of quadrilaterals into triangles, of shape \((\text{num_cubes},)\). Default: uniform value for all cubes.
training (bool, optional) – If set to True, applies differentiable quad splitting for training. Default: False.
output_tetmesh (bool, optional) – If set to True, outputs a tetrahedral mesh, otherwise, outputs a triangular mesh. Defaults: False.
grad_func (callable, optional) – A function to compute the surface gradient at specified 3D positions (input: Nx3 positions). The function should return gradients as an Nx3 tensor. If None, the original FlexiCubes algorithm is utilized. Defaults to None.
voxelgrid_features (torch.Tensor, optional) – Features per voxelgrid vertices, of shape \((\text{num_vertices}, \text{num_channels})\).
This is not supported with output_tetmesh or grad_func.
Tuple of tensors containing
vertices (torch.Tensor): Vertices for the extracted triangular/tetrahedral mesh, of shape \((\text{num_vertices}, 3)\).
faces (torch.LongTensor): Faces for the extracted triangular/tetrahedral mesh, of shape \((\text{num_faces}, 3)\)/\((\text{num_faces}, 4)\).
l_dev (torch.Tensor): Regularizer L_dev, computed per dual vertex, of shape \((\text{num_dual_vertices},)\).
vertex_features (optional, torch.Tensor): if
voxelgrid_featuresis provided there will be an additional returned tensor, of the interpolated features to the vertices.
Generates a voxel grid based on the specified resolution.
The voxelgrid is represented as a mesh, with the voxels corners as vertices.
resolution (int or list[int]) – The resolution of the voxel grid. If an integer is provided, it is used for all three dimensions. If a list or tuple of 3 integers is provided, they define the resolution for the x, y, and z dimensions respectively.
The corners of the voxels of the constructed voxelgrid, centered and normalized (i.e: the vertices are in the range \([-0.5, 0.5]), of shape :math:\).
The indices into vertices for each voxel, of shape \((\text{res}, 8)\).
Define a voxelgrid overlapping with a 3D Gaussians Splat. Opacity is integrated over multiple samples.
Note
This op is not differentiable
xyz (torch.cuda.FloatTensor) – 3D Volumetric Gaussians means, of shape \((\text{num_gaussians, 3})\).
scales (torch.cuda.FloatTensor) – 3D Volumetric Gaussians scales, of shape \((\text{num_gaussians, 3})\).
rots (torch.cuda.FloatTensor) – 3D Volumetric Gaussians rotations, of shape \((\text{num_gaussians, 4})\).
opacities (torch.cuda.FloatTensor) – 3D Volumetric Gaussians opacities, of shape \((\text{num_gaussians})\).
level (int) – level at which to process, resolution will be at \(2^level\).
iso (float) – The isocontour value used to determine the surface of a Gaussian. Default: In the Gaussian Splat paper the 99th percentile value is advised (11.345).
tol (float) – Minimum allowable scale in the scale matrix of the :math:’(Sigma = R S S^T R^T)’ factorization of a Gaussian covariance matrix. This value is relative to the size of a voxel at the deepest level of SPC point hierarchy. This value is needed to ensure that \((\Sigma)\) is numerically invertable. Note: This issue does not arise in Gaussian Splatting since it is only necessary that the 2D projection of a Gaussian have an inverse. Default: 0.125.
step (int) – number of samples for opacity integration.
list the voxels coordinates, of shape \((\text{num_voxels}, 3)\)
the accumulated opacities, of shape \((\text{num_voxels})\)
(torch.cuda.ShortTensor, torch.cuda.LongTensor, torch.cuda.BoolTensor, torch.cuda.FloatTensor)
Convert discrete signed distance fields encoded on tetrahedral grids to triangle meshes using marching tetrahedra algorithm as described in An efficient method of triangulating equi-valued surfaces by using tetrahedral cells. The output surface is differentiable with respect to input vertex positions and the SDF values. For more details and example usage in learning, see Deep Marching Tetrahedra: a Hybrid Representation for High-Resolution 3D Shape Synthesis NeurIPS 2021.
vertices (torch.tensor) – batched vertices of tetrahedral meshes, of shape \((\text{batch_size}, \text{num_vertices}, 3)\).
tets (torch.tensor) – unbatched tetrahedral mesh topology, of shape \((\text{num_tetrahedrons}, 4)\).
sdf (torch.tensor) – batched SDFs which specify the SDF value of each vertex, of shape \((\text{batch_size}, \text{num_vertices})\).
return_tet_idx (optional, bool) – if True, return index of tetrahedron where each face is extracted. Default: False.
the list of vertices for mesh converted from each tetrahedral grid.
the list of faces for mesh converted from each tetrahedral grid.
the list of indices that correspond to tetrahedra where faces are extracted.
(list[torch.Tensor], list[torch.LongTensor], (optional) list[torch.LongTensor])
Example
>>> vertices = torch.tensor([[[0, 0, 0],
... [1, 0, 0],
... [0, 1, 0],
... [0, 0, 1]]], dtype=torch.float)
>>> tets = torch.tensor([[0, 1, 2, 3]], dtype=torch.long)
>>> sdf = torch.tensor([[-1., -1., 0.5, 0.5]], dtype=torch.float)
>>> verts_list, faces_list, tet_idx_list = marching_tetrahedra(vertices, tets, sdf, True)
>>> verts_list[0]
tensor([[0.0000, 0.6667, 0.0000],
[0.0000, 0.0000, 0.6667],
[0.3333, 0.6667, 0.0000],
[0.3333, 0.0000, 0.6667]])
>>> faces_list[0]
tensor([[3, 0, 1],
[3, 2, 0]])
>>> tet_idx_list[0]
tensor([0, 0])
Converts pointclouds to voxelgrids. It separates the 3D space into empty voxelgrid, and for each boxes, if there is a corresponding point, set that voxelgrid to be occupied.
Will convert only points in the range [0, 1] after been shifted and scaled as following (pointclouds - origin) * scale.
pointclouds (torch.Tensor) – Exact batched pointclouds, of shape \((\text{batch_size}, \text{num_points}, 3)\).
resolution (int) – Resolution of output voxelgrids.
origin (optional, torch.Tensor) – Origin of the voxelgrid in the pointcloud coordinates,
of shape \((\text{batch_size}, 3)\).
Default: torch.min(pointcloud, dim=1)[0].
scale (optional, torch.Tensor) – Scale by which we divide the pointclouds’ coordinates,
of shape \((\text{batch_size})\).
Default: torch.max(torch.max(pointclouds, dim=1)[0] - origin, dim=1)[0].
return_sparse (optional, bool) – Whether to return a sparse voxelgrids or not. Default: False.
Exact batched voxelgrids, of shape
\((\text{batch_size}, \text{resolution}, \text{resolution}, \text{resolution})\).
If return_sparse is True, a sparse FloatTensor is returned.
(torch.Tensor or torch.FloatTensor)
Example
>>> pointclouds = torch.tensor([[[0, 0, 0],
... [1, 1, 1],
... [2, 2, 2]]], dtype=torch.float)
>>> pointclouds_to_voxelgrids(pointclouds, 3)
tensor([[[[1., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 1.]]]])
Converts SDFs to voxelgrids.
For each SDF returns a voxel grid with resolution \(init\_res * 2 ^ {upsampling\_steps} + 1\) (so the underlying voxel resolution is \(init\_res * 2 ^ {upsampling\_steps}\)) where each grid point holds a binary value determined by the sign of the SDF at the location of the grid point after normalizing the voxel grid to the bounding box defined by bbox_center and bbox_dim.
This solution is largely borrowed from “Multiresolution IsoSurface Extraction (MISE)” proposed in the CVPR 2019 paper “Occupancy Networks: Learning 3D Reconstruction in Function Space”: https://arxiv.org/abs/1906.02739. Instead of evaluating SDF values of all grid points at high resolution, this function incrementally builds an octree and only evaluate dense grid points around the surface.
sdf (list[callable]) – A list of callable that takes 3D coordinates as a torch.Tensor, of shape
\((\text{num_points}, 3)\) and output the N corresponding SDF values
as a torch.Tensor, of shape \((\text{num_points})\).
bbox_center (optional, float) – Center of the surface’s bounding box. Default: 0.
bbox_dim (optional, float) – Largest dimension of the surface’s bounding box. Default: 1.
init_res (optional, int) – The initial resolution of the voxelgrids, should be large enough to properly define the surface. Default: 32.
upsampling_steps (optional, int) – Number of times the initial resolution will be doubled. Default: 0.
Binary voxelgrids, of shape \((\text{batch_size}, \text{init_res} * 2 ^ \text{upsampling_steps} + 1)\).
Example
>>> def sphere(points):
... return torch.sum(points ** 2, 1) ** 0.5 - 0.5
>>> sdf_to_voxelgrids([sphere], init_res=4)
tensor([[[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 1., 1., 0.],
[0., 0., 0., 0., 0.]],
[[0., 0., 1., 0., 0.],
[0., 1., 1., 1., 0.],
[1., 1., 1., 1., 1.],
[0., 1., 1., 1., 0.],
[0., 0., 1., 0., 0.]],
[[0., 0., 0., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 1., 1., 0.],
[0., 1., 1., 1., 0.],
[0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]]])
Converts meshes to surface voxelgrids of a given resolution. It first upsamples triangle mesh’s vertices to given resolution, then it performs a box test. If a voxel contains a triangle vertex, set that voxel to 1. Vertex will be offset and scaled as following: \(\text{normalized_vertices} = (\text{vertices} - \text{origin}) / \text{scale}\) the voxelgrids will only be generated in the range [0, 1] of normalized_vertices.
vertices (torch.tensor) – Batched vertices of the input meshes, of shape \((\text{batch_size}, \text{num_vertices}, 3)\).
faces (torch.tensor) – Unbatched faces of the meshes, of shape \((\text{num_faces}, 3)\).
resolution (int) – desired resolution of generated voxelgrid.
origin (torch.tensor) – Origin of the voxelgrid in the mesh coordinates,
of shape \((\text{batch_size}, 3)\).
Default: torch.min(vertices, dim=1)[0].
scale (torch.tensor) – The scale by which we divide the vertex position,
of shape \((\text{batch_size})\).
Default: torch.max(torch.max(vertices, dim=1)[0] - origin, dim=1)[0].
return_sparse (optional, bool) – If True, sparse tensor is returned. Default: False.
Binary batched voxelgrids, of shape \((\text{batch_size}, \text{resolution}, \text{resolution}, \text{resolution})\). If return_sparse is True, sparse tensor is returned.
(torch.Tensor or torch.FloatTensor)
Example
>>> vertices = torch.tensor([[[0, 0, 0],
... [1, 0, 0],
... [0, 0, 1]]], dtype=torch.float)
>>> faces = torch.tensor([[0, 1, 2]], dtype=torch.long)
>>> origin = torch.zeros((1, 3))
>>> scale = torch.ones((1))
>>> trianglemeshes_to_voxelgrids(vertices, faces, 3, origin, scale)
tensor([[[[1., 1., 1.],
[0., 0., 0.],
[0., 0., 0.]],
[[1., 1., 0.],
[0., 0., 0.],
[0., 0., 0.]],
[[1., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]]])
Convert a mesh into a Structured Point Cloud octree.
The conversion is using a conservative rasterization process, the resulting octree is fully wrapping the mesh.
Note
The mesh will be voxelized in the range \([-1, 1]\) of the vertices coordinate system.
face_vertices (torch.LongTensor) – The vertices indexed by faces (see kaolin.ops.mesh.index_vertices_by_faces()),
of shape \((\text{num_faces}, 3, 3)\).
level (int) – number of levels in the returned SPC.
The generated octree, of size \((\text{num_nodes})\), where \(\text{num_nodes}\) depends on the geometry of the input mesh.
The indices of the face corresponding to each voxel at the highest level, of shape \((\text{num_voxels})\).
The barycentric coordinates of the voxel with respect to corresponding face of shape \((\text{num_vertices}, 2)\).
(torch.ByteTensor, torch.LongTensor, torch.FloatTensor)
This function takes as input a single point-cloud - a set of continuous coordinates in 3D, and coverts it into a Structured Point Cloud (SPC), a compressed octree representation where the point cloud coordinates are quantized to integer coordinates.
Point coordinates are expected to be normalized to the range \([-1, 1]\). If a point is out of the range \([-1, 1]\) it will be clipped to it.
If features are specified, the current implementation will average features
of points that inhabit the same quantized bucket.
pointclouds (torch.Tensor) – An unbatched pointcloud, of shape \((\text{num_points}, 3)\). Coordinates are expected to be normalized to the range \([-1, 1]\).
level (int) – Maximum number of levels to use in octree hierarchy.
features (optional, torch.Tensor) – Feature vector containing information per point, of shape \((\text{num_points}, \text{feat_dim})\).
A Structured Point Cloud (SPC) object, holding a single-item batch.
Convert voxelgrids to meshes by replacing each occupied voxel with a cuboid mesh (unit cube). Each cube has 8 vertices and 6 (for quadmesh) or 12 faces (for triangular mesh). Internal faces are ignored. If is_trimesh==True, this function performs the same operation as “Cubify” defined in the ICCV 2019 paper “Mesh R-CNN”: https://arxiv.org/abs/1906.02739.
voxelgrids (torch.Tensor) – binary voxel array, of shape \((\text{batch_size}, \text{X}, \text{Y}, \text{Z})\).
is_trimesh (optional, bool) – if True, the outputs are triangular meshes. Otherwise quadmeshes are returned. Default: True.
The list of vertices for each mesh.
The list of faces for each mesh.
(list[torch.Tensor], list[torch.LongTensor])
Example
>>> voxelgrids = torch.ones((1, 1, 1, 1))
>>> verts, faces = voxelgrids_to_cubic_meshes(voxelgrids)
>>> verts[0]
tensor([[0., 0., 0.],
[0., 0., 1.],
[0., 1., 0.],
[0., 1., 1.],
[1., 0., 0.],
[1., 0., 1.],
[1., 1., 0.],
[1., 1., 1.]])
>>> faces[0]
tensor([[0, 1, 2],
[5, 4, 7],
[0, 4, 1],
[6, 2, 7],
[0, 2, 4],
[3, 1, 7],
[3, 2, 1],
[6, 7, 4],
[5, 1, 4],
[3, 7, 2],
[6, 4, 2],
[5, 7, 1]])
Converts voxelgrids to triangle meshes using marching cube algorithm. Please refer to: Lorensen, William E.; Cline, Harvey E. in Marching cubes, A high resolution 3D surface construction algorithm
voxelgrids (torch.Tensor) – Exact batched voxel array with shape \((\text{batch_size}, \text{X}, \text{Y}, \text{Z})\).
iso_value (optional, float) – Value in the range \([0, 1]\) used to determine whether a voxel is inside the surface or not. Isovalue is also used to interpolate newly created triangle vertices. Defaults to 0.5
The list of vertices of each mesh.
The list of faces of each mesh.
Example
>>> voxelgrid = torch.tensor([[[[1, 0],
... [0, 0]],
... [[0, 0],
... [0, 0]]]], device='cuda', dtype=torch.uint8)
>>> vertices, faces = voxelgrids_to_trianglemeshes(voxelgrid)
>>> vertices[0]
tensor([[1.0000, 1.0000, 0.5000],
[1.0000, 0.5000, 1.0000],
[0.5000, 1.0000, 1.0000],
[1.0000, 1.0000, 1.5000],
[1.0000, 1.5000, 1.0000],
[1.5000, 1.0000, 1.0000]], device='cuda:0')
>>> faces[0]
tensor([[0, 1, 2],
[3, 2, 1],
[4, 0, 2],
[4, 2, 3],
[0, 5, 1],
[5, 3, 1],
[4, 5, 0],
[5, 4, 3]], device='cuda:0')