SMPL visualizer (Skinned Mesh)ΒΆ
Requires a .npz model file.
- See here for download instructions:
https://github.com/vchoutas/smplx?tab=readme-ov-file#downloading-the-model
1from __future__ import annotations
2
3import time
4from dataclasses import dataclass
5from pathlib import Path
6from typing import List, Tuple
7
8import numpy as np
9import tyro
10
11import viser
12import viser.transforms as tf
13
14
15@dataclass(frozen=True)
16class SmplFkOutputs:
17 T_world_joint: np.ndarray # (num_joints, 4, 4)
18 T_parent_joint: np.ndarray # (num_joints, 4, 4)
19
20
21class SmplHelper:
22 """Helper for models in the SMPL family, implemented in numpy. Does not include blend skinning."""
23
24 def __init__(self, model_path: Path) -> None:
25 assert model_path.suffix.lower() == ".npz", "Model should be an .npz file!"
26 body_dict = dict(**np.load(model_path, allow_pickle=True))
27
28 self.J_regressor = body_dict["J_regressor"]
29 self.weights = body_dict["weights"]
30 self.v_template = body_dict["v_template"]
31 self.posedirs = body_dict["posedirs"]
32 self.shapedirs = body_dict["shapedirs"]
33 self.faces = body_dict["f"]
34
35 self.num_joints: int = self.weights.shape[-1]
36 self.num_betas: int = self.shapedirs.shape[-1]
37 self.parent_idx: np.ndarray = body_dict["kintree_table"][0]
38
39 def get_tpose(self, betas: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
40 # Get shaped vertices + joint positions, when all local poses are identity.
41 v_tpose = self.v_template + np.einsum("vxb,b->vx", self.shapedirs, betas)
42 j_tpose = np.einsum("jv,vx->jx", self.J_regressor, v_tpose)
43 return v_tpose, j_tpose
44
45 def get_outputs(
46 self, betas: np.ndarray, joint_rotmats: np.ndarray
47 ) -> SmplFkOutputs:
48 # Get shaped vertices + joint positions, when all local poses are identity.
49 v_tpose = self.v_template + np.einsum("vxb,b->vx", self.shapedirs, betas)
50 j_tpose = np.einsum("jv,vx->jx", self.J_regressor, v_tpose)
51
52 # Local SE(3) transforms.
53 T_parent_joint = np.zeros((self.num_joints, 4, 4)) + np.eye(4)
54 T_parent_joint[:, :3, :3] = joint_rotmats
55 T_parent_joint[0, :3, 3] = j_tpose[0]
56 T_parent_joint[1:, :3, 3] = j_tpose[1:] - j_tpose[self.parent_idx[1:]]
57
58 # Forward kinematics.
59 T_world_joint = T_parent_joint.copy()
60 for i in range(1, self.num_joints):
61 T_world_joint[i] = T_world_joint[self.parent_idx[i]] @ T_parent_joint[i]
62
63 return SmplFkOutputs(T_world_joint, T_parent_joint)
64
65
66def main(model_path: Path) -> None:
67 server = viser.ViserServer()
68 server.scene.set_up_direction("+y")
69 server.gui.configure_theme(control_layout="collapsible")
70
71 # Main loop. We'll read pose/shape from the GUI elements, compute the mesh,
72 # and then send the updated mesh in a loop.
73 model = SmplHelper(model_path)
74 gui_elements = make_gui_elements(
75 server,
76 num_betas=model.num_betas,
77 num_joints=model.num_joints,
78 parent_idx=model.parent_idx,
79 )
80 v_tpose, j_tpose = model.get_tpose(np.zeros((model.num_betas,)))
81 mesh_handle = server.scene.add_mesh_skinned(
82 "/human",
83 v_tpose,
84 model.faces,
85 bone_wxyzs=tf.SO3.identity(batch_axes=(model.num_joints,)).wxyz,
86 bone_positions=j_tpose,
87 skin_weights=model.weights,
88 wireframe=gui_elements.gui_wireframe.value,
89 color=gui_elements.gui_rgb.value,
90 )
91
92 while True:
93 # Do nothing if no change.
94 time.sleep(0.02)
95 if not gui_elements.changed:
96 continue
97
98 # Shapes changed: update vertices / joint positions.
99 if gui_elements.betas_changed:
100 v_tpose, j_tpose = model.get_tpose(
101 np.array([gui_beta.value for gui_beta in gui_elements.gui_betas])
102 )
103 mesh_handle.vertices = v_tpose
104 mesh_handle.bone_positions = j_tpose
105
106 gui_elements.changed = False
107 gui_elements.betas_changed = False
108
109 # Render as wireframe?
110 mesh_handle.wireframe = gui_elements.gui_wireframe.value
111
112 # Compute SMPL outputs.
113 smpl_outputs = model.get_outputs(
114 betas=np.array([x.value for x in gui_elements.gui_betas]),
115 joint_rotmats=np.stack(
116 [
117 tf.SO3.exp(np.array(x.value)).as_matrix()
118 for x in gui_elements.gui_joints
119 ],
120 axis=0,
121 ),
122 )
123
124 # Match transform control gizmos to joint positions.
125 for i, control in enumerate(gui_elements.transform_controls):
126 control.position = smpl_outputs.T_parent_joint[i, :3, 3]
127 mesh_handle.bones[i].wxyz = tf.SO3.from_matrix(
128 smpl_outputs.T_world_joint[i, :3, :3]
129 ).wxyz
130 mesh_handle.bones[i].position = smpl_outputs.T_world_joint[i, :3, 3]
131
132
133@dataclass
134class GuiElements:
135 """Structure containing handles for reading from GUI elements."""
136
137 gui_rgb: viser.GuiInputHandle[Tuple[int, int, int]]
138 gui_wireframe: viser.GuiInputHandle[bool]
139 gui_betas: List[viser.GuiInputHandle[float]]
140 gui_joints: List[viser.GuiInputHandle[Tuple[float, float, float]]]
141 transform_controls: List[viser.TransformControlsHandle]
142
143 changed: bool
144 """This flag will be flipped to True whenever any input is changed."""
145
146 betas_changed: bool
147 """This flag will be flipped to True whenever the shape changes."""
148
149
150def make_gui_elements(
151 server: viser.ViserServer,
152 num_betas: int,
153 num_joints: int,
154 parent_idx: np.ndarray,
155) -> GuiElements:
156 """Make GUI elements for interacting with the model."""
157
158 tab_group = server.gui.add_tab_group()
159
160 def set_changed(_) -> None:
161 out.changed = True # out is defined later!
162
163 def set_betas_changed(_) -> None:
164 out.betas_changed = True
165 out.changed = True
166
167 # GUI elements: mesh settings + visibility.
168 with tab_group.add_tab("View", viser.Icon.VIEWFINDER):
169 gui_rgb = server.gui.add_rgb("Color", initial_value=(90, 200, 255))
170 gui_wireframe = server.gui.add_checkbox("Wireframe", initial_value=False)
171 gui_show_controls = server.gui.add_checkbox("Handles", initial_value=True)
172 gui_control_size = server.gui.add_slider(
173 "Handle size", min=0.0, max=10.0, step=0.01, initial_value=1.0
174 )
175
176 gui_rgb.on_update(set_changed)
177 gui_wireframe.on_update(set_changed)
178
179 @gui_show_controls.on_update
180 def _(_):
181 for control in transform_controls:
182 control.visible = gui_show_controls.value
183
184 @gui_control_size.on_update
185 def _(_):
186 for control in transform_controls:
187 prefixed_joint_name = control.name
188 control.scale = (
189 0.2
190 * (0.75 ** prefixed_joint_name.count("/"))
191 * gui_control_size.value
192 )
193
194 # GUI elements: shape parameters.
195 with tab_group.add_tab("Shape", viser.Icon.BOX):
196 gui_reset_shape = server.gui.add_button("Reset Shape")
197 gui_random_shape = server.gui.add_button("Random Shape")
198
199 @gui_reset_shape.on_click
200 def _(_):
201 for beta in gui_betas:
202 beta.value = 0.0
203
204 @gui_random_shape.on_click
205 def _(_):
206 for beta in gui_betas:
207 beta.value = np.random.normal(loc=0.0, scale=1.0)
208
209 gui_betas = []
210 for i in range(num_betas):
211 beta = server.gui.add_slider(
212 f"beta{i}", min=-5.0, max=5.0, step=0.01, initial_value=0.0
213 )
214 gui_betas.append(beta)
215 beta.on_update(set_betas_changed)
216
217 # GUI elements: joint angles.
218 with tab_group.add_tab("Joints", viser.Icon.ANGLE):
219 gui_reset_joints = server.gui.add_button("Reset Joints")
220 gui_random_joints = server.gui.add_button("Random Joints")
221
222 @gui_reset_joints.on_click
223 def _(_):
224 for joint in gui_joints:
225 joint.value = (0.0, 0.0, 0.0)
226
227 @gui_random_joints.on_click
228 def _(_):
229 rng = np.random.default_rng()
230 for joint in gui_joints:
231 joint.value = tf.SO3.sample_uniform(rng).log()
232
233 gui_joints: List[viser.GuiInputHandle[Tuple[float, float, float]]] = []
234 for i in range(num_joints):
235 gui_joint = server.gui.add_vector3(
236 label=f"Joint {i}",
237 initial_value=(0.0, 0.0, 0.0),
238 step=0.05,
239 )
240 gui_joints.append(gui_joint)
241
242 def set_callback_in_closure(i: int) -> None:
243 @gui_joint.on_update
244 def _(_):
245 transform_controls[i].wxyz = tf.SO3.exp(
246 np.array(gui_joints[i].value)
247 ).wxyz
248 out.changed = True
249
250 set_callback_in_closure(i)
251
252 # Transform control gizmos on joints.
253 transform_controls: List[viser.TransformControlsHandle] = []
254 prefixed_joint_names = [] # Joint names, but prefixed with parents.
255 for i in range(num_joints):
256 prefixed_joint_name = f"joint_{i}"
257 if i > 0:
258 prefixed_joint_name = (
259 prefixed_joint_names[parent_idx[i]] + "/" + prefixed_joint_name
260 )
261 prefixed_joint_names.append(prefixed_joint_name)
262 controls = server.scene.add_transform_controls(
263 f"/smpl/{prefixed_joint_name}",
264 depth_test=False,
265 scale=0.2 * (0.75 ** prefixed_joint_name.count("/")),
266 disable_axes=True,
267 disable_sliders=True,
268 visible=gui_show_controls.value,
269 )
270 transform_controls.append(controls)
271
272 def set_callback_in_closure(i: int) -> None:
273 @controls.on_update
274 def _(_) -> None:
275 axisangle = tf.SO3(transform_controls[i].wxyz).log()
276 gui_joints[i].value = (axisangle[0], axisangle[1], axisangle[2])
277
278 set_callback_in_closure(i)
279
280 out = GuiElements(
281 gui_rgb,
282 gui_wireframe,
283 gui_betas,
284 gui_joints,
285 transform_controls=transform_controls,
286 changed=True,
287 betas_changed=False,
288 )
289 return out
290
291
292if __name__ == "__main__":
293 tyro.cli(main, description=__doc__)