yejunliang23 commited on
Commit
200cb0d
·
verified ·
1 Parent(s): 7aaefd7

Create cube2mesh.py

Browse files
trellis/representations/mesh/cube2mesh.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited.
8
+ import torch
9
+ from ...modules.sparse import SparseTensor
10
+ from easydict import EasyDict as edict
11
+ from .utils_cube import *
12
+ from .flexicube import FlexiCubes
13
+
14
+
15
+ class MeshExtractResult:
16
+ def __init__(self,
17
+ vertices,
18
+ faces,
19
+ vertex_attrs=None,
20
+ res=64
21
+ ):
22
+ self.vertices = vertices
23
+ self.faces = faces.long()
24
+ self.vertex_attrs = vertex_attrs
25
+ self.face_normal = self.comput_face_normals(vertices, faces)
26
+ self.res = res
27
+ self.success = (vertices.shape[0] != 0 and faces.shape[0] != 0)
28
+
29
+ # training only
30
+ self.tsdf_v = None
31
+ self.tsdf_s = None
32
+ self.reg_loss = None
33
+
34
+ def comput_face_normals(self, verts, faces):
35
+ i0 = faces[..., 0].long()
36
+ i1 = faces[..., 1].long()
37
+ i2 = faces[..., 2].long()
38
+
39
+ v0 = verts[i0, :]
40
+ v1 = verts[i1, :]
41
+ v2 = verts[i2, :]
42
+ face_normals = torch.cross(v1 - v0, v2 - v0, dim=-1)
43
+ face_normals = torch.nn.functional.normalize(face_normals, dim=1)
44
+ # print(face_normals.min(), face_normals.max(), face_normals.shape)
45
+ return face_normals[:, None, :].repeat(1, 3, 1)
46
+
47
+ def comput_v_normals(self, verts, faces):
48
+ i0 = faces[..., 0].long()
49
+ i1 = faces[..., 1].long()
50
+ i2 = faces[..., 2].long()
51
+
52
+ v0 = verts[i0, :]
53
+ v1 = verts[i1, :]
54
+ v2 = verts[i2, :]
55
+ face_normals = torch.cross(v1 - v0, v2 - v0, dim=-1)
56
+ v_normals = torch.zeros_like(verts)
57
+ v_normals.scatter_add_(0, i0[..., None].repeat(1, 3), face_normals)
58
+ v_normals.scatter_add_(0, i1[..., None].repeat(1, 3), face_normals)
59
+ v_normals.scatter_add_(0, i2[..., None].repeat(1, 3), face_normals)
60
+
61
+ v_normals = torch.nn.functional.normalize(v_normals, dim=1)
62
+ return v_normals
63
+
64
+
65
+ class SparseFeatures2Mesh:
66
+ def __init__(self, device="cuda", res=64, use_color=True):
67
+ '''
68
+ a model to generate a mesh from sparse features structures using flexicube
69
+ '''
70
+ super().__init__()
71
+ self.device=device
72
+ self.res = res
73
+ self.mesh_extractor = FlexiCubes(device=device)
74
+ self.sdf_bias = -1.0 / res
75
+ verts, cube = construct_dense_grid(self.res, self.device)
76
+ self.reg_c = cube.to(self.device)
77
+ self.reg_v = verts.to(self.device)
78
+ self.use_color = use_color
79
+ self._calc_layout()
80
+
81
+ def _calc_layout(self):
82
+ LAYOUTS = {
83
+ 'sdf': {'shape': (8, 1), 'size': 8},
84
+ 'deform': {'shape': (8, 3), 'size': 8 * 3},
85
+ 'weights': {'shape': (21,), 'size': 21}
86
+ }
87
+ if self.use_color:
88
+ '''
89
+ 6 channel color including normal map
90
+ '''
91
+ LAYOUTS['color'] = {'shape': (8, 6,), 'size': 8 * 6}
92
+ self.layouts = edict(LAYOUTS)
93
+ start = 0
94
+ for k, v in self.layouts.items():
95
+ v['range'] = (start, start + v['size'])
96
+ start += v['size']
97
+ self.feats_channels = start
98
+
99
+ def get_layout(self, feats : torch.Tensor, name : str):
100
+ if name not in self.layouts:
101
+ return None
102
+ return feats[:, self.layouts[name]['range'][0]:self.layouts[name]['range'][1]].reshape(-1, *self.layouts[name]['shape'])
103
+
104
+ def __call__(self, cubefeats : SparseTensor, training=False):
105
+ """
106
+ Generates a mesh based on the specified sparse voxel structures.
107
+ Args:
108
+ cube_attrs [Nx21] : Sparse Tensor attrs about cube weights
109
+ verts_attrs [Nx10] : [0:1] SDF [1:4] deform [4:7] color [7:10] normal
110
+ Returns:
111
+ return the success tag and ni you loss,
112
+ """
113
+ # add sdf bias to verts_attrs
114
+ coords = cubefeats.coords[:, 1:]
115
+ feats = cubefeats.feats
116
+
117
+ sdf, deform, color, weights = [self.get_layout(feats, name) for name in ['sdf', 'deform', 'color', 'weights']]
118
+ sdf += self.sdf_bias
119
+ v_attrs = [sdf, deform, color] if self.use_color else [sdf, deform]
120
+ v_pos, v_attrs, reg_loss = sparse_cube2verts(coords, torch.cat(v_attrs, dim=-1), training=training)
121
+ v_attrs_d = get_dense_attrs(v_pos, v_attrs, res=self.res+1, sdf_init=True)
122
+ weights_d = get_dense_attrs(coords, weights, res=self.res, sdf_init=False)
123
+ if self.use_color:
124
+ sdf_d, deform_d, colors_d = v_attrs_d[..., 0], v_attrs_d[..., 1:4], v_attrs_d[..., 4:]
125
+ else:
126
+ sdf_d, deform_d = v_attrs_d[..., 0], v_attrs_d[..., 1:4]
127
+ colors_d = None
128
+
129
+ x_nx3 = get_defomed_verts(self.reg_v, deform_d, self.res)
130
+
131
+ vertices, faces, L_dev, colors = self.mesh_extractor(
132
+ voxelgrid_vertices=x_nx3,
133
+ scalar_field=sdf_d,
134
+ cube_idx=self.reg_c,
135
+ resolution=self.res,
136
+ beta=weights_d[:, :12],
137
+ alpha=weights_d[:, 12:20],
138
+ gamma_f=weights_d[:, 20],
139
+ voxelgrid_colors=colors_d,
140
+ training=training)
141
+
142
+ mesh = MeshExtractResult(vertices=vertices, faces=faces, vertex_attrs=colors, res=self.res)
143
+ if training:
144
+ if mesh.success:
145
+ reg_loss += L_dev.mean() * 0.5
146
+ reg_loss += (weights[:,:20]).abs().mean() * 0.2
147
+ mesh.reg_loss = reg_loss
148
+ mesh.tsdf_v = get_defomed_verts(v_pos, v_attrs[:, 1:4], self.res)
149
+ mesh.tsdf_s = v_attrs[:, 0]
150
+ return mesh