o ˜¯ßfë‡ã@s(ddlZddlTdgZGdd„dƒZdS)éN)Ú*Ú FlexiCubesc@sšeZdZdZd!dd„Zdd„Z d"d d „Zd d„Zdd„Ze   ¡dd„ƒZ e   ¡dd„ƒZ e   ¡dd„ƒZ dd„Zd#dd„Zdd„Zdd„Zdd „Zd S)$ra 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. Attributes: device (str): Specifies the computational device (default is "cuda"). dmc_table (torch.Tensor): Dual Marching Cubes (DMC) table that encodes the edges associated with each dual vertex in 256 Marching Cubes (MC) configurations. num_vd_table (torch.Tensor): Table holding the number of dual vertices in each of the 256 MC configurations. check_table (torch.Tensor): Table resolving ambiguity in cases C16 and C19 of the DMC configurations. tet_table (torch.Tensor): Lookup table used in tetrahedralizing the isosurface. quad_split_1 (torch.Tensor): Indices for splitting a quad into two triangles along one diagonal. quad_split_2 (torch.Tensor): Alternative indices for splitting a quad into two triangles along the other diagonal. quad_split_train (torch.Tensor): Indices for splitting a quad into four triangles during training by connecting all edges to their midpoints. cube_corners (torch.Tensor): 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_idx (torch.Tensor): Cube corners indexed as powers of 2, used to retrieve the case id. cube_edges (torch.Tensor): Edge connections in a cube, listed in pairs. Used to retrieve edge vertices in DMC. edge_dir_table (torch.Tensor): 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. dir_faces_table (torch.Tensor): 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. adj_pairs (torch.Tensor): A tensor containing index pairs that correspond to neighboring cubes that share the same edge. qef_reg_scale (float): 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. weight_scale (float): The scale of weights in FlexiCubes. Should be between 0 and 1. Úcpuçü©ñÒMbP?ç®Gáz®ï?c CsÄ||_tjttj|dd|_tjttj|dd|_tjttj|dd|_tjttj|dd|_tjgd¢tj|dd|_tjgd¢tj|dd|_ tjgd¢tj|dd|_ tjgd¢gd¢gd¢gd ¢gd ¢gd ¢gd ¢gd ¢gtj |d|_ t  dtjddd¡|_tjgd¢tj|dd|_tjgd¢tj|d|_tjddgddgddgddggddgddgddgddggddgddgddgddgggtj|d|_tjgd¢tj|d|_||_||_dS)NF©ÚdtypeÚdeviceÚ requires_grad)réérr é)rr r r r r )rr r r r r r r)rrr)r rr)rr r)r r r)rrr )r rr )rr r )r r r ©rr r é)r )rr r éérrrr r r éérr rr rr r rrrr) rr rr rr rr r r r r rrr r r)rr r r r r r r)r ÚtorchÚtensorÚ dmc_tableÚlongÚ num_vd_tableÚ check_tableÚ tet_tableÚ quad_split_1Ú quad_split_2Úquad_split_trainÚfloatÚ cube_cornersÚpowÚarangeÚcube_corners_idxÚ cube_edgesÚedge_dir_tableÚdir_faces_tableÚ adj_pairsÚ qef_reg_scaleÚ weight_scale)Úselfr r'r(©r*ú//home/gustavo/Documentos/CRM/util/flexicubes.pyÚ__init__CsJÿþÿ( ÿÿ ÿ ÿýü zFlexiCubes.__init__c Csøt d¡ |j¡}t|tƒr|||f}tj||jd}tj|gtj|jd}t  |¡ ¡|}|j   d¡||  d¡  dd¡}|  d¡tj|j d|jd  d¡d  d¡}t |d¡d}tj|dd d \}} | |  d¡  dd¡}|d |fS) aÇ Generates a voxel grid based on the specified resolution. Args: res (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. Returns: (torch.Tensor, torch.Tensor): Returns the vertices and the indices of the cube corners (index into vertices) of the constructed voxel grid. The vertices are centered at the origin, with the length of each dimension in the grid being one. r©r rrr éÿÿÿÿr i †T)ÚdimÚreturn_inversegà?)rr!Útor Ú isinstanceÚintÚonesrrÚnonzerorÚ unsqueezeÚreshapeÚshapeÚroundÚunique) r)ÚresÚ base_cube_fÚvoxel_grid_templateÚcoordsÚvertsÚcubesÚ verts_roundedÚ verts_uniqueÚinverse_indicesr*r*r+Úconstruct_voxel_gridds   "ÿÿ zFlexiCubes.construct_voxel_gridNFc Cs(| ||¡\} } |  ¡dkr3tjd|jd| r!tjdtj|jdn tjdtj|jdtjd|jdfS| |||| ¡\}}}| | | |¡} | ||| ¡\}}}}|  ||| ||| ||||| ¡ \}}}}|  |||||||||| ¡ \}}}}| s}|||fS|  ||||||||| || |¡ \}}|||fS)a8 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. Args: x_nx3 (torch.Tensor): Coordinates of the voxel grid vertices, can be deformed. s_n (torch.Tensor): Scalar field values at each vertex of the voxel grid. Negative values denote that the corresponding vertex resides inside the isosurface. This affects the directions of the extracted triangle faces and volume to be tetrahedralized. cube_fx8 (torch.Tensor): Indices of 8 vertices for each cube in the voxel grid. res (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. beta_fx12 (torch.Tensor, optional): Weight parameters for the cube edges to adjust dual vertices positioning. Defaults to uniform value for all edges. alpha_fx8 (torch.Tensor, optional): Weight parameters for the cube corners to adjust dual vertices positioning. Defaults to uniform value for all vertices. gamma_f (torch.Tensor, optional): Weight parameters to control the splitting of quadrilaterals into triangles. Defaults to uniform value for all cubes. training (bool, optional): If set to True, applies differentiable quad splitting for training. Defaults to False. output_tetmesh (bool, optional): If set to True, outputs a tetrahedral mesh, otherwise, outputs a triangular mesh. Defaults to 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. Returns: (torch.Tensor, torch.LongTensor, torch.Tensor): Tuple containing: - Vertices for the extracted triangular/tetrahedral mesh. - Faces for the extracted triangular/tetrahedral mesh. - Regularizer L_dev, computed per dual vertex. .. _Flexible Isosurface Extraction for Gradient-Based Mesh Optimization: https://research.nvidia.com/labs/toronto-ai/flexicubes/ .. _Manifold Dual Contouring: https://people.engr.tamu.edu/schaefer/research/dualsimp_tvcg.pdf r)rr r-)rrr) Ú_identify_surf_cubesÚsumrÚzerosr rÚ_normalize_weightsÚ _get_case_idÚ_identify_surf_edgesÚ _compute_vdÚ _triangulateÚ_tetrahedralize)r)Úx_nx3Ús_nÚcube_fx8r;Ú beta_fx12Ú alpha_fx8Úgamma_fÚtrainingÚoutput_tetmeshÚ grad_funcÚ surf_cubesÚocc_fx8Úcase_idsÚ surf_edgesÚidx_mapÚ edge_countsÚsurf_edges_maskÚvdÚL_devÚvd_gammaÚ vd_idx_mapÚverticesÚfacesÚs_edgesÚ edge_indicesÚtetsr*r*r+Ú__call__…sH8 þþþþþú  ÿ ÿ þ zFlexiCubes.__call__cCsltj|tj||dddd}t |dd…df¡}| d||¡| d¡ ¡}|tj||dd ¡}|S)z4 Regularizer L_dev as in Equation 8 r©ÚinputÚindexr/r.©r/Nr )rÚnormÚ index_selectÚ zeros_likeÚ index_add_ÚsqueezerÚabs)r)r^ÚueÚedge_group_to_vdÚ vd_num_edgesÚdistÚmean_l2Úmadr*r*r+Ú_compute_reg_lossÚs zFlexiCubes._compute_reg_losscCsÈ|jd}|durt |¡|jd}n tj|dftj|jd}|dur/t |¡|jd}n tj|dftj|jd}|durOt |¡|jd|jd}n tj|tj|jd}||||||fS)zŽ Normalizes the given weights to be non-negative. If input weights are None, it creates and returns a set of weights of ones. rNr é rrr )r8rÚtanhr(r4rr Úsigmoid)r)rQrRrSrWÚn_cubesr*r*r+rHäs  zFlexiCubes._normalize_weightscCs˜|||j |j¡ d¡ d¡}|j |j¡|}|ddk}||}t|ttfƒs0|||g}t j t|ƒdg|jt j d}t   |ddk¡}|||} ||| d| d| df<| |d dd …f} | ddk| d|dk@| ddk@| d|dk@| ddk@| d|d k@} | | } | | } || }|| d| d| df} | ddk} t j |jd|jd || | }| |f|| d ¡|S)a2 Obtains the ID of topology cases based on cell corner occupancy. This function resolves the ambiguity in the Dual Marching Cubes (DMC) configurations as described in Section 1.3 of the supplementary material. It should be noted that this function assumes a regular grid. rr.©.rr r)r r).r ).r .rr r-).r.)r"r1r r6rFrr2ÚlistÚtuplerrGrr5r!r8Ú index_put_)r)rXrWr;rYÚproblem_configÚto_checkÚproblem_config_fullÚvol_idxÚvol_idx_problemÚvol_idx_problem_adjÚ within_rangeÚproblem_config_adjÚ to_invertÚidxr*r*r+rIûs@"    þ ýü ûú ÿ "zFlexiCubes._get_case_idcCsÈ|dk}||dd…|jf dd¡}tj|dddd\}}}| ¡}|| d¡ dd¡ d¡dk} | |} ||}tj|jdtj|jdd} tj |  ¡|jd | | <| |} || } | | || fS) a( Identifies grid edges that intersect with the underlying surface by checking for opposite signs. As each edge can be shared by multiple cubes, this function also assigns a unique index to each surface-intersecting edge and marks the cube edges with this index. rNr.r T©r/r0Ú return_countsr rr-) r#r7rr:rrFr4r8r r!)r)rOrPrWÚocc_nÚ all_edgesÚ unique_edgesÚ_idx_mapÚcountsÚ mask_edgesr]Úmappingr[rZr*r*r+rJ&s  zFlexiCubes._identify_surf_edgescCsB|dk}|| d¡ dd¡}t |d¡}|dk|dk@}||fS)z– Identifies grid cubes that intersect with the underlying surface by checking if the signs at all corners are not identical. rr.r)r7rrF)r)rOrPrrXÚ_occ_sumrWr*r*r+rE?s  zFlexiCubes._identify_surf_cubesc Cs€| ¡d}|j|dksJ‚t tj|tjd|jd|dtj|tjd|jd|d g|¡}| |¡}|| |¡|}|S)zv Computes the location of zero-crossings on 'edges_x' using linear interpolation with 'edges_weight'. r r r-rhr)r/r8rÚcatrmrr rF)r)Ú edges_weightÚedges_xÚedge_dimÚ denominatorrrr*r*r+Ú_linear_interpKs ÿÿ zFlexiCubes._linear_interpc Cs´| ddd¡}| ddd¡}| dd¡}|}||jddd}tjd|jd|j d¡ |jddd¡}|j| d¡}t  ||gd¡}t  ||gd¡}tj   ||¡j   d¡}|S) Nr.rr T©Úkeepdimsr-rr )r7rFrÚeyer r'r6Úrepeatr8r•ÚlinalgÚlstsqÚsolutionrp) r)Úp_bxnx3Ú norm_bxnx3Úc_bx3ÚAÚBÚA_regÚB_regÚ dual_vertsr*r*r+Ú _solve_vd_QEFWs ,zFlexiCubes._solve_vd_QEFc 0 Cs6tj||jdd ddd¡} tj|| d¡dd ddd¡} tj|| d¡dd ddd¡} | | | ¡}|  dd¡} tj|j|dd}gggggf\}}}}}d}tj|jddftj|j dd }| d urrtj j j | |ƒdd }g}t  |¡D]5}||k}| ¡|}|j||d |…f d|d ¡}tj||j d  d¡ dd ¡|}||7}tj| jd|j d | d¡ d|d ¡ |¡}|dk}| t ||¡¡| t | |¡|¡¡| t ||¡¡| | dd ¡jddd¡| t ||¡ d¡ d|¡ d¡¡| d ur­t ¡•| |} d||<tj| d|d}!d|!|!dk<tj||! d¡dd d| ¡d d¡}"|||d d …df dddd¡ d| ¡dd¡}#| d| ¡d d¡}|"| d¡| d¡}$tj||! d¡dd d| ¡d d¡}%| d¡}| | |"|#||%||$|# d¡¡|# dd¡¡Wd ƒn 1s¨wYqwt |¡}t |¡}t |¡}t |¡}t |¡}| d urÛt |¡}tjdg|j d }&nžtj|df|j d }tj|df|j d }'tj|  d¡d|d|d}(tj| |( d¡dd ddd¡})tj| |( d¡dd ddd¡}*tj||( d¡dd dd¡}+tj|  dd¡d|d|d ddd¡},| |*|,|)¡}-tj| d¡d|d|d dd¡}.|'jd||.d}'|jd||-|.d|'}| ||+||¡}&tj|jd|j d }/| d¡jd|d||/|d}||&||fS)zT Computes the location of dual vertices as described in Section 4.2 r rhr.ryr rr FrNrkrr-Tr›)rir/rj)rjÚsource)r/rjÚsrc)rrmr#r7ršrrGr8rr ÚnnÚ functionalÚ normalizer:rFrr!r6ržÚ reshape_asÚappendÚ masked_selectÚno_gradÚgatherÚitemrprªr•rorxÚscatter)0r)rNÚsurf_cubes_fx8rZrOrYrQrRrSr[rVÚ alpha_nx12x2Ú surf_edges_xÚ surf_edges_sÚ zero_crossingÚnum_vdÚ edge_grouprsÚedge_group_to_cubertr`Ú total_num_vdraÚnormalsr^ÚnumÚ cur_cubesÚ curr_num_vdÚcurr_edge_groupÚcurr_edge_group_to_vdÚcurr_edge_group_to_cubeÚ curr_maskÚcube_e_verts_idxÚverts_group_idxÚverts_group_posÚv0Úverts_centroidÚ normals_bx7x3r_Úbeta_sumÚ idx_groupÚx_groupÚs_groupÚzero_crossing_groupÚ alpha_groupÚue_groupÚ beta_groupÚv_idxr*r*r+rKesÈ      "ÿÿÿÿ&     ÿÿ4 þ  ÿ ÿð€          ÿÿ ÿ ÿ ÿÿÿÿÿ zFlexiCubes._compute_vdc Csút ¡g|dk|@} | d¡| } || } tj| dd\}}| | dd¡}||| dd¡dd…df d¡ dd¡}|dd…dfdk}t ||dd…gd¢f||dd…gd ¢ff¡}Wdƒn1snwY| durÑt ¡Mtjjj| |ƒdd }tj|| d¡dd  ddd ¡}|dd…df|dd…dfj ddd }|dd…df|dd…d fj ddd }Wdƒn1sËwYnGtj|| d¡dd  dd¡}tj|tj d|j ddd tj|tj d|j ddd }tj|tj d|j ddd tj|tj d |j ddd }| sT||k  d¡}tj |jddftj|j d}||dd…|jf||<||dd…|jf||<| dd ¡}n£tj|| d¡dd  ddd ¡}tj|tj d|j ddd tj|tj d|j ddd d}tj|tj d|j ddd tj|tj d |j ddd d}||d}|| d¡|| d¡| d¡  d¡}tj|jd|j d|jd}t ||g¡}|dd…|jf ddd¡}t || ddd¡ ddd¡gd¡ dd ¡}||||fS)zÇ Connects four neighboring dual vertices to form a quadrilateral. The quadrilaterals are then split into triangles based on the gamma parameter, as described in Section 4.3. rr.T)ÚstableNrr )rr r r )r r r rrkrhr r›r r-rrg:Œ0âŽyE>)rr³r7Úsortr•r­r®r¯rmrFrr rprGr8rrrr6r!rrž)r)rOrZr^r`r\r[rar]rTrVÚ group_maskÚgroupÚvd_idxreÚindicesÚ quad_vd_idxrdÚ flip_maskÚ quad_gammaÚgamma_02Úgamma_13ÚmaskrcÚvd_quadÚvd_02Úvd_13Ú weight_sumÚ vd_centerÚ vd_center_idxr*r*r+rLÁs~  .ÿö  *,ü€ ÿÿÿ ÿÿÿ ÿÿÿÿ ÿÿ , zFlexiCubes._triangulatec 0Csè|dk} | | d¡ dd¡}t |d¡}|| }tj| jdtj|jdd}tj|  ¡|jd|jd|| < |||  dd¡dd…df dd¡|dk}| sa| d ¡  dd¡ d¡}n | d ¡  dd¡ d¡}t  || d¡gd¡} |dk}||| d¡ ddd ¡  d ¡}tj|jd|jd|jd|jd}| |B}tj| ¡d ftj|jdd}| |} ||}| dd ¡|| dd …f<|||d f<||dd…|j f dd¡}tj |dd d d\}}}| ¡}| | d¡ dd¡ d¡dk}||}||}tj|jdtj|jdd}tj| ¡|jd||<||} |dk|@}!|  d¡|!}"t |"¡\} }#tj|jdd tj|jd d ¡  dd ¡ d¡|!}$tjd tj|jd d¡  |jdd d¡ d¡|!}%|$|# dd¡}&|j|%|# dd¡d}'|j|' d¡}(|&dd…|jf d¡})tj| ¡tj|jdd}*| |*| <|*|)}+||)|j|+|(ff dd¡},|,dk d¡dk}||||  d¡ dd¡}-t  |,|-gd¡|}.t  ||.g¡}/t  |||g¡}||/fS)zq Tetrahedralizes the interior volume to produce a tetrahedral mesh, as described in Section 4.5. rr.rrr-rNr r r é ryTr‹r}éÿ)r7rrFr4r8rr r!r6Úexpandr•Úmeanr#r:rØr$r%r&r)0r)rNrOrPrbrcrZrdrarYrerWrTrrXÚocc_sumÚ inside_vertsÚmapping_inside_vertsÚinside_verts_idxÚ tets_surfaceÚ inside_cubesÚinside_cubes_centerÚinside_cubes_center_idxÚsurface_n_inside_cubesÚedge_center_vertex_idxrŽrrr‘r’râr“r[rÙrÚrÜÚcube_idxÚedge_idxÚ cube_idx_4Úedge_dirÚshared_faces_4x2Ú cube_idx_4x2Úcase_ids_expandÚcasesÚ quad_edgeÚ inside_edgeÚ tets_insiderfr*r*r+rMôsŒ "$ÿ" ÿÿÿÿÿ   ÿÿÿÿzFlexiCubes._tetrahedralize)rrr)NNNFFN)N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r,rDrgrxrHrr³rIrJrEršrªrKrLrMr*r*r*r+rs( 2!! ÿU  *   \ 3)rÚ util.tablesÚ__all__rr*r*r*r+Ús ÿ