mannequin-x 0.0.1__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: mannequin-x
3
+ Version: 0.0.1
4
+ Summary: Rigid, non-skinned mannequins driven directly by SMPL-X motion
5
+ Author: Andrea Boscolo Camiletto
6
+ Author-email: Andrea Boscolo Camiletto <abcamiletto@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Dist: jaxtyping>=0.2.28
10
+ Requires-Dist: nanomanifold>=0.8.0
11
+ Requires-Dist: numpy>=2.0.0
12
+ Requires-Dist: trimesh>=4.0.0
13
+ Requires-Dist: viser>=0.2.0 ; extra == 'viser'
14
+ Requires-Python: >=3.11
15
+ Provides-Extra: viser
16
+ Description-Content-Type: text/markdown
17
+
18
+ # SMPL-X Mannequin
19
+
20
+ A rigid mannequin driven directly by SMPL-X parameters — no skinning, no
21
+ blend shapes. Every part, down to the fingers, is a rigid mesh owned by one
22
+ SMPL-X joint; shape coefficients change bone lengths without changing part
23
+ thickness. Numpy-only and fully standalone: the SMPL-X shape response is
24
+ baked into a small bundled table, so neither `body-models` nor the SMPL-X
25
+ model files are needed.
26
+
27
+ ```bash
28
+ pip install mannequin-x
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ```python
34
+ from mannequin import SmplxMannequin
35
+
36
+ model = SmplxMannequin(lod=1)
37
+ params = model.get_rest_pose()
38
+ vertices = model.forward_vertices(**params)
39
+ ```
40
+
41
+ `forward_vertices`, `forward_skeleton`, `forward_links`, and `forward_meshes`
42
+ take SMPL-X parameters (axis-angle, optionally batched) and use the native
43
+ SMPL-X origin: identical parameters place the pelvis and neutral foot surface
44
+ in the same coordinates as SMPL-X. For repeated calls with the same betas,
45
+ prepare the identity once with `prepare_identity` and pass it as `identity=`.
46
+
47
+ ## Viser
48
+
49
+ Each link mesh is uploaded to the [viser](https://viser.studio) scene once,
50
+ parented to its joint's frame; pose and shape updates only send the per-joint
51
+ frame transforms (~10 KB per full pose).
52
+
53
+ ```python
54
+ import viser
55
+ from mannequin import SmplxMannequin, add_mannequin
56
+
57
+ server = viser.ViserServer()
58
+ model = SmplxMannequin(lod=1)
59
+ handle = add_mannequin(server.scene, "/mannequin", model)
60
+ handle.set_shape(betas)
61
+ handle.set_pose(**model.get_apose())
62
+ ```
63
+
64
+ `set_pose` accepts any subset of the SMPL-X pose parameters, and full
65
+ per-frame parameter dicts work directly (`shape` is routed to `set_shape`,
66
+ `expression` is ignored). Unchanged values are skipped.
67
+
68
+ `add_mannequin` takes a `palette` — one of the built-in armor/joint pairs in
69
+ `PALETTES` (`sand`, `ivory`, `charcoal`, `sage`, `clay`, `slate`; see
70
+ [`renders/palettes.jpg`](renders/palettes.jpg)) or a custom
71
+ `(armor, joint)` RGB pair.
72
+
73
+ ## Assets
74
+
75
+ Three exactly mirrored levels of detail are bundled: `lod=0` (~40k vertices),
76
+ `lod=1` (~15k), and `lod=2` (<5k). Lower-leg length is calibrated against the
77
+ SMPL-X sole vertices, so shaped identities keep the same ground plane. The
78
+ editable source is [`authoring/mannequin.blend`](authoring/mannequin.blend);
79
+ the installed package ships only the compact numpy assets.
@@ -0,0 +1,62 @@
1
+ # SMPL-X Mannequin
2
+
3
+ A rigid mannequin driven directly by SMPL-X parameters — no skinning, no
4
+ blend shapes. Every part, down to the fingers, is a rigid mesh owned by one
5
+ SMPL-X joint; shape coefficients change bone lengths without changing part
6
+ thickness. Numpy-only and fully standalone: the SMPL-X shape response is
7
+ baked into a small bundled table, so neither `body-models` nor the SMPL-X
8
+ model files are needed.
9
+
10
+ ```bash
11
+ pip install mannequin-x
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```python
17
+ from mannequin import SmplxMannequin
18
+
19
+ model = SmplxMannequin(lod=1)
20
+ params = model.get_rest_pose()
21
+ vertices = model.forward_vertices(**params)
22
+ ```
23
+
24
+ `forward_vertices`, `forward_skeleton`, `forward_links`, and `forward_meshes`
25
+ take SMPL-X parameters (axis-angle, optionally batched) and use the native
26
+ SMPL-X origin: identical parameters place the pelvis and neutral foot surface
27
+ in the same coordinates as SMPL-X. For repeated calls with the same betas,
28
+ prepare the identity once with `prepare_identity` and pass it as `identity=`.
29
+
30
+ ## Viser
31
+
32
+ Each link mesh is uploaded to the [viser](https://viser.studio) scene once,
33
+ parented to its joint's frame; pose and shape updates only send the per-joint
34
+ frame transforms (~10 KB per full pose).
35
+
36
+ ```python
37
+ import viser
38
+ from mannequin import SmplxMannequin, add_mannequin
39
+
40
+ server = viser.ViserServer()
41
+ model = SmplxMannequin(lod=1)
42
+ handle = add_mannequin(server.scene, "/mannequin", model)
43
+ handle.set_shape(betas)
44
+ handle.set_pose(**model.get_apose())
45
+ ```
46
+
47
+ `set_pose` accepts any subset of the SMPL-X pose parameters, and full
48
+ per-frame parameter dicts work directly (`shape` is routed to `set_shape`,
49
+ `expression` is ignored). Unchanged values are skipped.
50
+
51
+ `add_mannequin` takes a `palette` — one of the built-in armor/joint pairs in
52
+ `PALETTES` (`sand`, `ivory`, `charcoal`, `sage`, `clay`, `slate`; see
53
+ [`renders/palettes.jpg`](renders/palettes.jpg)) or a custom
54
+ `(armor, joint)` RGB pair.
55
+
56
+ ## Assets
57
+
58
+ Three exactly mirrored levels of detail are bundled: `lod=0` (~40k vertices),
59
+ `lod=1` (~15k), and `lod=2` (<5k). Lower-leg length is calibrated against the
60
+ SMPL-X sole vertices, so shaped identities keep the same ground plane. The
61
+ editable source is [`authoring/mannequin.blend`](authoring/mannequin.blend);
62
+ the installed package ships only the compact numpy assets.
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "mannequin-x"
3
+ version = "0.0.1"
4
+ description = "Rigid, non-skinned mannequins driven directly by SMPL-X motion"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "jaxtyping>=0.2.28",
11
+ "nanomanifold>=0.8.0",
12
+ "numpy>=2.0.0",
13
+ "trimesh>=4.0.0",
14
+ ]
15
+
16
+ [[project.authors]]
17
+ name = "Andrea Boscolo Camiletto"
18
+ email = "abcamiletto@gmail.com"
19
+
20
+ [project.optional-dependencies]
21
+ viser = ["viser>=0.2.0"]
22
+
23
+ [build-system]
24
+ requires = ["uv_build>=0.11.11,<0.12.0"]
25
+ build-backend = "uv_build"
26
+
27
+ [tool.uv.build-backend]
28
+ module-name = "mannequin"
29
+
30
+ [tool.ruff]
31
+ line-length = 120
32
+
33
+ [tool.ruff.lint]
34
+ ignore = [
35
+ "F722",
36
+ "F821",
37
+ "UP037",
38
+ ]
39
+
40
+ [tool.ty.src]
41
+ exclude = [
42
+ "authoring/",
43
+ "tests/",
44
+ ]
45
+
46
+ [dependency-groups]
47
+ dev = [
48
+ "pytest>=8.0.0",
49
+ "ruff>=0.16.0",
50
+ "ty>=0.0.1a13",
51
+ "viser>=0.2.0",
52
+ ]
@@ -0,0 +1,44 @@
1
+ [project]
2
+ name = "mannequin-x"
3
+ version = "0.0.1"
4
+ description = "Rigid, non-skinned mannequins driven directly by SMPL-X motion"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Andrea Boscolo Camiletto", email = "abcamiletto@gmail.com" }
8
+ ]
9
+ license = "Apache-2.0"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.11"
12
+ dependencies = [
13
+ "jaxtyping>=0.2.28",
14
+ "nanomanifold>=0.8.0",
15
+ "numpy>=2.0.0",
16
+ "trimesh>=4.0.0",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ viser = ["viser>=0.2.0"]
21
+
22
+ [build-system]
23
+ requires = ["uv_build>=0.11.11,<0.12.0"]
24
+ build-backend = "uv_build"
25
+
26
+ [tool.uv.build-backend]
27
+ module-name = "mannequin"
28
+
29
+ [dependency-groups]
30
+ dev = [
31
+ "pytest>=8.0.0",
32
+ "ruff>=0.16.0",
33
+ "ty>=0.0.1a13",
34
+ "viser>=0.2.0",
35
+ ]
36
+
37
+ [tool.ruff]
38
+ line-length = 120
39
+
40
+ [tool.ruff.lint]
41
+ ignore = ["F722", "F821", "UP037"]
42
+
43
+ [tool.ty.src]
44
+ exclude = ["authoring/", "tests/"]
@@ -0,0 +1,6 @@
1
+ """Rigid, non-skinned mannequin driven directly by SMPL-X motion."""
2
+
3
+ from mannequin._model import SmplxMannequin
4
+ from mannequin._viser import PALETTES, ViserMannequinHandle, add_mannequin
5
+
6
+ __all__ = ["PALETTES", "SmplxMannequin", "ViserMannequinHandle", "add_mannequin"]
@@ -0,0 +1,4 @@
1
+ """SMPL-X ordering constants."""
2
+
3
+ # Mannequin body order as indices into SMPL-X's 23-joint body pose.
4
+ SMPLX_BODY_ORDER = (0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11, 14, 12, 15, 17, 19, 21, 13, 16, 18, 20, 22)
@@ -0,0 +1,83 @@
1
+ """Native mannequin asset loading."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from importlib.resources import files
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ from jaxtyping import Float, Int
11
+
12
+ Array = Any
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ShapeCalibration:
17
+ """Affine SMPL-X shape response baked in mannequin joint order.
18
+
19
+ Rest joints are exactly linear in the first ten SMPL-X betas, and the
20
+ shaped-body floor is the minimum over the (also linear) heights of the
21
+ neutral sole vertices, so this small table reproduces the SMPL-X model's
22
+ skeleton lengths and ground plane without the SMPL-X assets.
23
+ """
24
+
25
+ joint_rest: Float[Array, "J 3"]
26
+ joint_dirs: Float[Array, "J 3 10"]
27
+ sole_y_rest: Float[Array, "K"]
28
+ sole_y_dirs: Float[Array, "K 10"]
29
+ body_a_pose: Float[Array, "21 3"]
30
+ hand_flat: Float[Array, "30 3"]
31
+ hand_rest: Float[Array, "30 3"]
32
+
33
+
34
+ def load_calibration(*, dtype=np.float64) -> ShapeCalibration:
35
+ """Load the baked SMPL-X shape calibration."""
36
+ resource = files("mannequin") / "assets" / "smplx_calibration.npz"
37
+ with resource.open("rb") as archive, np.load(archive, allow_pickle=False) as data:
38
+ return ShapeCalibration(**{key: data[key].astype(dtype) for key in data.files})
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class MannequinWeights:
43
+ joint_names: list[str]
44
+ parents: list[int]
45
+ local_offsets: Float[Array, "J 3"]
46
+ rest_local_rotations: Float[Array, "J 3 3"]
47
+ vertices: Float[Array, "V 3"]
48
+ faces: Int[Array, "F 3"]
49
+ link_joint_indices: list[int]
50
+ link_vertex_starts: list[int]
51
+ link_vertex_counts: list[int]
52
+ link_face_starts: list[int]
53
+ link_face_counts: list[int]
54
+ link_geom_positions: Float[Array, "L 3"]
55
+ link_geom_rotations: Float[Array, "L 3 3"]
56
+ link_names: list[str]
57
+ actuated_joint_indices: list[int]
58
+
59
+
60
+ def load(lod: int = 0, *, dtype=np.float32) -> MannequinWeights:
61
+ """Load one bundled mannequin LOD."""
62
+ if lod not in (0, 1, 2):
63
+ raise ValueError(f"lod must be 0, 1, or 2; got {lod!r}")
64
+
65
+ resource = files("mannequin") / "assets" / f"lod{lod}.npz"
66
+ with resource.open("rb") as archive, np.load(archive, allow_pickle=False) as data:
67
+ return MannequinWeights(
68
+ joint_names=data["joint_names"].tolist(),
69
+ parents=data["parents"].tolist(),
70
+ local_offsets=data["local_offsets"].astype(dtype),
71
+ rest_local_rotations=data["rest_local_rotations"].astype(dtype),
72
+ vertices=data["vertices"].astype(dtype),
73
+ faces=data["faces"].astype(np.int64),
74
+ link_joint_indices=data["link_joint_indices"].tolist(),
75
+ link_vertex_starts=data["link_vertex_starts"].tolist(),
76
+ link_vertex_counts=data["link_vertex_counts"].tolist(),
77
+ link_face_starts=data["link_face_starts"].tolist(),
78
+ link_face_counts=data["link_face_counts"].tolist(),
79
+ link_geom_positions=data["link_geom_positions"].astype(dtype),
80
+ link_geom_rotations=data["link_geom_rotations"].astype(dtype),
81
+ link_names=data["link_names"].tolist(),
82
+ actuated_joint_indices=data["actuated_joint_indices"].tolist(),
83
+ )
@@ -0,0 +1,289 @@
1
+ """Rigid SMPL-X mannequin model (numpy-only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from functools import cached_property
7
+ from typing import Any, Literal
8
+
9
+ import numpy as np
10
+ from jaxtyping import Float, Int
11
+ from nanomanifold import SO3
12
+ from trimesh import Trimesh
13
+
14
+ from mannequin import _constants as constants
15
+ from mannequin import _io as io
16
+ from mannequin import _rigid as rigid
17
+ from mannequin import identity as identity_ops
18
+
19
+ Array = Any
20
+ MannequinLod = Literal[0, 1, 2]
21
+
22
+
23
+ class SmplxMannequin:
24
+ """Rigid mannequin with SMPL-X pose and shape parameters.
25
+
26
+ Shape changes alter symmetric bone lengths and reposition rigid parts; they
27
+ never change link thickness or introduce skinning. All arrays are numpy.
28
+ """
29
+
30
+ NUM_BODY_JOINTS = 21
31
+ NUM_HAND_JOINTS = 30
32
+ NUM_HEAD_JOINTS = 3
33
+ NUM_SHAPE_COEFFS = 10
34
+ NUM_EXPR_COEFFS = 10
35
+
36
+ def __init__(self, *, lod: MannequinLod = 0) -> None:
37
+ self._weights = io.load(lod)
38
+ self._identity_template = identity_ops.build_template(self._weights)
39
+ self._calibration: io.ShapeCalibration | None = None
40
+
41
+ # ------------------------------------------------------------- structure
42
+ @property
43
+ def faces(self) -> Int[Array, "F 3"]:
44
+ return self._weights.faces
45
+
46
+ @property
47
+ def joint_names(self) -> list[str]:
48
+ return list(self._weights.joint_names)
49
+
50
+ @property
51
+ def parents(self) -> list[int]:
52
+ return list(self._weights.parents)
53
+
54
+ @property
55
+ def num_joints(self) -> int:
56
+ return len(self._weights.parents)
57
+
58
+ @property
59
+ def num_vertices(self) -> int:
60
+ return self._weights.vertices.shape[0]
61
+
62
+ @property
63
+ def link_names(self) -> list[str]:
64
+ return list(self._weights.link_names)
65
+
66
+ @cached_property
67
+ def link_meshes(self) -> Sequence[Trimesh]:
68
+ """Link-local meshes aligned with :attr:`link_names` and ``forward_links()``."""
69
+ return rigid.link_meshes(
70
+ self._weights.vertices,
71
+ self._weights.faces,
72
+ self._weights.link_vertex_starts,
73
+ self._weights.link_vertex_counts,
74
+ self._weights.link_face_starts,
75
+ self._weights.link_face_counts,
76
+ )
77
+
78
+ # --------------------------------------------------------------- forward
79
+ def prepare_identity(
80
+ self,
81
+ shape: Float[Array, "10"],
82
+ expression: Float[Array, "10"] | None = None,
83
+ *,
84
+ skip_vertices: bool = False,
85
+ ) -> identity_ops.SmplxMannequinIdentity:
86
+ """Prepare one reusable, length-only identity from an unbatched beta vector."""
87
+ del expression
88
+ shape_np = np.asarray(shape)
89
+ if np.any(shape_np) and self._calibration is None:
90
+ self._calibration = io.load_calibration()
91
+ return identity_ops.prepare(
92
+ self._weights,
93
+ self._identity_template,
94
+ self._calibration,
95
+ shape_np,
96
+ skip_vertices=skip_vertices,
97
+ )
98
+
99
+ def forward_skeleton(
100
+ self,
101
+ body_pose: Float[Array, "*batch 21 3"],
102
+ head_pose: Float[Array, "*batch 3 3"],
103
+ hand_pose: Float[Array, "*batch 30 3"],
104
+ *,
105
+ pelvis_rotation: Float[Array, "*batch 3"] | None = None,
106
+ shape: Float[Array, "10"] | None = None,
107
+ expression: Float[Array, "10"] | None = None,
108
+ identity: identity_ops.SmplxMannequinIdentity | None = None,
109
+ global_rotation: Float[Array, "*batch 3"] | None = None,
110
+ global_translation: Float[Array, "*batch 3"] | None = None,
111
+ ) -> Float[Array, "*batch J 4 4"]:
112
+ """Compute shape-adjusted mannequin joint transforms."""
113
+ identity = self._resolve_identity(identity, shape, expression, skip_vertices=True)
114
+ root_translation = identity["local_joint_offsets"][0]
115
+ if global_rotation is not None:
116
+ rotation = SO3.convert(global_rotation, src="axis_angle", dst="rotmat", xp=np)
117
+ root_translation = np.squeeze(rotation @ root_translation[..., None], axis=-1)
118
+ if global_translation is not None:
119
+ root_translation = root_translation + global_translation
120
+ if pelvis_rotation is not None:
121
+ if global_rotation is None:
122
+ global_rotation = pelvis_rotation
123
+ else:
124
+ global_rotation = SO3.convert(
125
+ SO3.multiply(
126
+ SO3.convert(global_rotation, src="axis_angle", dst="quat", xp=np),
127
+ SO3.convert(pelvis_rotation, src="axis_angle", dst="quat", xp=np),
128
+ xp=np,
129
+ ),
130
+ src="quat",
131
+ dst="axis_angle",
132
+ xp=np,
133
+ )
134
+ return rigid.forward_skeleton_from_local_rotations(
135
+ self._local_rotations_from_smplx(body_pose, hand_pose),
136
+ local_offsets=identity["local_joint_offsets"],
137
+ rest_local_rotations=self._weights.rest_local_rotations,
138
+ actuated_joint_indices=self._weights.actuated_joint_indices,
139
+ parents=self._weights.parents,
140
+ global_rotation=global_rotation,
141
+ global_translation=root_translation,
142
+ )
143
+
144
+ def forward_vertices(
145
+ self,
146
+ body_pose: Float[Array, "*batch 21 3"],
147
+ head_pose: Float[Array, "*batch 3 3"],
148
+ hand_pose: Float[Array, "*batch 30 3"],
149
+ *,
150
+ pelvis_rotation: Float[Array, "*batch 3"] | None = None,
151
+ shape: Float[Array, "10"] | None = None,
152
+ expression: Float[Array, "10"] | None = None,
153
+ identity: identity_ops.SmplxMannequinIdentity | None = None,
154
+ global_rotation: Float[Array, "*batch 3"] | None = None,
155
+ global_translation: Float[Array, "*batch 3"] | None = None,
156
+ ) -> Float[Array, "*batch V 3"]:
157
+ """Compute vertices for the shape-adjusted rigid parts."""
158
+ identity = self._resolve_identity(identity, shape, expression, skip_vertices=False)
159
+ skeleton = self.forward_skeleton(
160
+ body_pose,
161
+ head_pose,
162
+ hand_pose,
163
+ pelvis_rotation=pelvis_rotation,
164
+ identity=identity,
165
+ global_rotation=global_rotation,
166
+ global_translation=global_translation,
167
+ )
168
+ return self._vertices_from_skeleton(skeleton, identity["link_local_vertices"])
169
+
170
+ def forward_links(self, *args: Any, **kwargs: Any) -> Float[Array, "*batch L 4 4"]:
171
+ """Compute link transforms from SMPL-X parameters."""
172
+ skeleton = self.forward_skeleton(*args, **kwargs)
173
+ return rigid.forward_link_transforms(
174
+ skeleton,
175
+ self._weights.link_joint_indices,
176
+ self._weights.link_geom_positions,
177
+ self._weights.link_geom_rotations,
178
+ )
179
+
180
+ def forward_meshes(self, *args: Any, **kwargs: Any) -> list[Trimesh]:
181
+ """Build one posed mannequin mesh per batch element."""
182
+ vertices = np.asarray(self.forward_vertices(*args, **kwargs))
183
+ if vertices.ndim == 2:
184
+ vertices = vertices[None]
185
+ vertices = vertices.reshape(-1, vertices.shape[-2], 3)
186
+ return [Trimesh(vertices=item, faces=self.faces, process=False) for item in vertices]
187
+
188
+ # ----------------------------------------------------------------- poses
189
+ def get_rest_pose(
190
+ self,
191
+ *,
192
+ batch_dims: tuple[int, ...] = (),
193
+ dtype: Any | None = None,
194
+ hands: Literal["default", "flat", "rest"] = "default",
195
+ ) -> dict[str, Float[Array, "..."]]:
196
+ """Return the SMPL-X rest pose with configurable hand means."""
197
+ if hands not in ("default", "flat", "rest"):
198
+ raise ValueError(f"Invalid hands: {hands!r}")
199
+ dtype = np.float32 if dtype is None else dtype
200
+ shapes = {
201
+ "shape": (self.NUM_SHAPE_COEFFS,),
202
+ "expression": (self.NUM_EXPR_COEFFS,),
203
+ "body_pose": (self.NUM_BODY_JOINTS, 3),
204
+ "head_pose": (self.NUM_HEAD_JOINTS, 3),
205
+ "hand_pose": (self.NUM_HAND_JOINTS, 3),
206
+ "pelvis_rotation": (3,),
207
+ "global_rotation": (3,),
208
+ "global_translation": (3,),
209
+ }
210
+ params = {name: np.zeros((*batch_dims, *shape), dtype=dtype) for name, shape in shapes.items()}
211
+ if hands != "default":
212
+ hand_pose = np.asarray(getattr(self._load_calibration(), f"hand_{hands}"), dtype=dtype)
213
+ params["hand_pose"] = np.broadcast_to(hand_pose, (*batch_dims, *hand_pose.shape)).copy()
214
+ return params
215
+
216
+ def get_apose(
217
+ self,
218
+ *,
219
+ batch_dims: tuple[int, ...] = (),
220
+ dtype: Any | None = None,
221
+ hands: Literal["default", "flat", "rest"] = "default",
222
+ ) -> dict[str, Float[Array, "..."]]:
223
+ """Return the SMPL-X A-pose."""
224
+ params = self.get_rest_pose(batch_dims=batch_dims, dtype=dtype, hands=hands)
225
+ body_pose = np.asarray(self._load_calibration().body_a_pose, dtype=params["body_pose"].dtype)
226
+ params["body_pose"] = np.broadcast_to(body_pose, (*batch_dims, *body_pose.shape)).copy()
227
+ return params
228
+
229
+ # -------------------------------------------------------------- internals
230
+ def _load_calibration(self) -> io.ShapeCalibration:
231
+ if self._calibration is None:
232
+ self._calibration = io.load_calibration()
233
+ return self._calibration
234
+
235
+ def _local_rotations_from_smplx(
236
+ self,
237
+ body_pose: Float[Array, "*batch 21 3"],
238
+ hand_pose: Float[Array, "*batch 30 3"],
239
+ ) -> Float[Array, "*batch Q 3 3"]:
240
+ if body_pose.shape[-2:] != (self.NUM_BODY_JOINTS, 3):
241
+ raise ValueError(f"body_pose must have shape [..., 21, 3], got {tuple(body_pose.shape)}")
242
+ if hand_pose.shape[-2:] != (self.NUM_HAND_JOINTS, 3):
243
+ raise ValueError(f"hand_pose must have shape [..., 30, 3], got {tuple(hand_pose.shape)}")
244
+ padding = np.zeros((*body_pose.shape[:-2], 2, 3), dtype=body_pose.dtype)
245
+ padded_body_pose = np.concatenate((body_pose, padding), axis=-2)
246
+ ordered_body_pose = np.stack(
247
+ [padded_body_pose[..., index, :] for index in constants.SMPLX_BODY_ORDER],
248
+ axis=-2,
249
+ )
250
+ axis_angle = np.concatenate((ordered_body_pose, hand_pose), axis=-2)
251
+ return SO3.convert(axis_angle, src="axis_angle", dst="rotmat", xp=np)
252
+
253
+ def _resolve_identity(
254
+ self,
255
+ identity: identity_ops.SmplxMannequinIdentity | None,
256
+ shape: Float[Array, "10"] | None,
257
+ expression: Float[Array, "10"] | None,
258
+ *,
259
+ skip_vertices: bool,
260
+ ) -> identity_ops.SmplxMannequinIdentity:
261
+ if identity is not None:
262
+ conflicts = [name for name, value in (("shape", shape), ("expression", expression)) if value is not None]
263
+ if conflicts:
264
+ raise ValueError(f"identity cannot be combined with raw identity parameters: {', '.join(conflicts)}")
265
+ return identity
266
+ if shape is None:
267
+ shape = np.zeros((self.NUM_SHAPE_COEFFS,), dtype=self._weights.vertices.dtype)
268
+ return self.prepare_identity(shape, expression, skip_vertices=skip_vertices)
269
+
270
+ def _vertices_from_skeleton(
271
+ self,
272
+ skeleton: Float[Array, "*batch J 4 4"],
273
+ local_vertices: Float[Array, "V 3"],
274
+ ) -> Float[Array, "*batch V 3"]:
275
+ parts = []
276
+ for owner, start, count in zip(
277
+ self._weights.link_joint_indices,
278
+ self._weights.link_vertex_starts,
279
+ self._weights.link_vertex_counts,
280
+ strict=True,
281
+ ):
282
+ rotation = skeleton[..., owner, :3, :3]
283
+ translation = skeleton[..., owner, :3, 3]
284
+ local = local_vertices[start : start + count]
285
+ parts.append(np.squeeze(rotation[..., None, :, :] @ local[..., None], axis=-1) + translation[..., None, :])
286
+ return np.concatenate(parts, axis=-2)
287
+
288
+
289
+ __all__ = ["SmplxMannequin"]
@@ -0,0 +1,108 @@
1
+ """Numpy forward kinematics for the rigid mannequin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ from jaxtyping import Float, Int
9
+ from nanomanifold import SO3
10
+ from trimesh import Trimesh
11
+
12
+ Array = Any
13
+
14
+
15
+ def affine_transforms(
16
+ rotations: Float[Array, "... 3 3"],
17
+ translations: Float[Array, "... 3"],
18
+ ) -> Float[Array, "... 4 4"]:
19
+ """Assemble 4x4 transforms from rotations and translations."""
20
+ batch = np.broadcast_shapes(rotations.shape[:-2], translations.shape[:-1])
21
+ out = np.zeros((*batch, 4, 4), dtype=rotations.dtype)
22
+ out[..., :3, :3] = rotations
23
+ out[..., :3, 3] = translations
24
+ out[..., 3, 3] = 1.0
25
+ return out
26
+
27
+
28
+ def forward_skeleton_from_local_rotations(
29
+ body_rotations: Float[Array, "... Q 3 3"],
30
+ *,
31
+ local_offsets: Float[Array, "J 3"],
32
+ rest_local_rotations: Float[Array, "J 3 3"],
33
+ actuated_joint_indices: list[int],
34
+ parents: list[int],
35
+ global_translation: Float[Array, "... 3"] | None = None,
36
+ global_rotation: Float[Array, "... 3"] | None = None,
37
+ ) -> Float[Array, "... J 4 4"]:
38
+ """Compute rigid hierarchy transforms from local actuated joint rotations."""
39
+ batch_shape = tuple(body_rotations.shape[:-3])
40
+ dtype = body_rotations.dtype
41
+ num_joints = len(parents)
42
+
43
+ local_rot = np.broadcast_to(np.eye(3, dtype=dtype), (*batch_shape, num_joints, 3, 3)).copy()
44
+ local_rot[..., actuated_joint_indices, :, :] = body_rotations
45
+ local_rot = np.asarray(rest_local_rotations, dtype=dtype) @ local_rot
46
+ local_t = np.asarray(local_offsets, dtype=dtype)
47
+
48
+ rot_world: list[Any] = [None] * num_joints
49
+ pos_world: list[Any] = [None] * num_joints
50
+ rot_world[0] = local_rot[..., 0, :, :]
51
+ pos_world[0] = np.zeros((*batch_shape, 3), dtype=dtype)
52
+ for joint in range(1, num_joints):
53
+ parent = parents[joint]
54
+ rot_world[joint] = rot_world[parent] @ local_rot[..., joint, :, :]
55
+ pos_world[joint] = pos_world[parent] + np.squeeze(rot_world[parent] @ local_t[joint][..., None], axis=-1)
56
+
57
+ rot = np.stack(rot_world, axis=-3)
58
+ trans = np.stack(pos_world, axis=-2)
59
+ if global_rotation is not None:
60
+ global_rot = SO3.convert(global_rotation, src="axis_angle", dst="rotmat", xp=np)
61
+ rot = global_rot[..., None, :, :] @ rot
62
+ trans = np.squeeze(global_rot[..., None, :, :] @ trans[..., None], axis=-1)
63
+ if global_translation is not None:
64
+ trans = trans + global_translation[..., None, :]
65
+
66
+ return affine_transforms(rot, trans)
67
+
68
+
69
+ def forward_link_transforms(
70
+ skeleton: Float[Array, "... J 4 4"],
71
+ link_joint_indices: list[int],
72
+ link_geom_positions: Float[Array, "L 3"],
73
+ link_geom_rotations: Float[Array, "L 3 3"],
74
+ ) -> Float[Array, "... L 4 4"]:
75
+ """Apply each link's local geom transform to its parent joint transform."""
76
+ indices = list(link_joint_indices)
77
+ joint_rot = skeleton[..., indices, :3, :3]
78
+ joint_pos = skeleton[..., indices, :3, 3]
79
+ geom_pos = np.asarray(link_geom_positions, dtype=skeleton.dtype)
80
+ geom_rot = np.asarray(link_geom_rotations, dtype=skeleton.dtype)
81
+ rot = joint_rot @ geom_rot
82
+ trans = joint_pos + np.squeeze(joint_rot @ geom_pos[..., None], axis=-1)
83
+ return affine_transforms(rot, trans)
84
+
85
+
86
+ def link_meshes(
87
+ vertices: Float[Array, "V 3"],
88
+ faces: Int[Array, "F 3"],
89
+ link_vertex_starts: list[int],
90
+ link_vertex_counts: list[int],
91
+ link_face_starts: list[int],
92
+ link_face_counts: list[int],
93
+ ) -> list[Trimesh]:
94
+ """Build one link-local mesh per packed geometry range."""
95
+ vertices = np.asarray(vertices)
96
+ faces = np.asarray(faces)
97
+ meshes = []
98
+ for vertex_start, vertex_count, face_start, face_count in zip(
99
+ link_vertex_starts,
100
+ link_vertex_counts,
101
+ link_face_starts,
102
+ link_face_counts,
103
+ strict=True,
104
+ ):
105
+ link_vertices = vertices[vertex_start : vertex_start + vertex_count]
106
+ link_faces = faces[face_start : face_start + face_count] - vertex_start
107
+ meshes.append(Trimesh(vertices=link_vertices, faces=link_faces, process=False))
108
+ return meshes
@@ -0,0 +1,195 @@
1
+ """Viser integration for the rigid mannequin.
2
+
3
+ The mannequin has no skinning, so geometry is uploaded to the scene exactly
4
+ once: each link mesh sits under its owning joint's frame with a static local
5
+ offset, and pose updates only move the per-joint frame transforms (two
6
+ messages per joint instead of two per mesh, so a full pose fits in a single
7
+ viser message window).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ import numpy as np
15
+ from jaxtyping import Float
16
+ from nanomanifold import SO3
17
+
18
+ from mannequin._model import SmplxMannequin
19
+
20
+ if TYPE_CHECKING:
21
+ import viser
22
+
23
+ Array = Any
24
+
25
+ Color = tuple[int, int, int]
26
+
27
+ PALETTES: dict[str, tuple[Color, Color]] = {
28
+ "sand": ((196, 163, 112), (143, 107, 66)),
29
+ "ivory": ((236, 231, 221), (139, 131, 120)),
30
+ "charcoal": ((70, 72, 77), (176, 180, 187)),
31
+ "sage": ((168, 181, 157), (98, 113, 90)),
32
+ "clay": ((198, 124, 92), (117, 69, 49)),
33
+ "slate": ((128, 146, 167), (69, 82, 99)),
34
+ }
35
+ """Predefined (armor, joint) RGB pairs for :func:`add_mannequin`."""
36
+
37
+
38
+ class ViserMannequinHandle:
39
+ """Mannequin added to a viser scene as static meshes under per-joint frames.
40
+
41
+ ``set_pose`` accepts the same parameter names as ``SmplxMannequin`` forward
42
+ calls (so ``handle.set_pose(**params)`` works with full SMPL-X parameter
43
+ dicts); ``shape`` entries are routed to :meth:`set_shape` and
44
+ ``expression`` is ignored. Unchanged values are skipped, and meshes are
45
+ never re-uploaded.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ model: SmplxMannequin,
51
+ pose: dict[str, Float[np.ndarray, "..."]],
52
+ root_frame: viser.FrameHandle,
53
+ frames: list[viser.FrameHandle],
54
+ frame_joints: list[int],
55
+ links: list[viser.MeshHandle],
56
+ ) -> None:
57
+ self._model = model
58
+ self._pose = pose
59
+ self._root_frame = root_frame
60
+ self._frames = frames
61
+ self._frame_joints = frame_joints
62
+ self._links = links
63
+ self._shape = np.zeros(model.NUM_SHAPE_COEFFS, dtype=np.float32)
64
+ self._identity = model.prepare_identity(self._shape, skip_vertices=True)
65
+
66
+ @property
67
+ def name(self) -> str:
68
+ return self._root_frame.name
69
+
70
+ @property
71
+ def visible(self) -> bool:
72
+ return self._root_frame.visible
73
+
74
+ @visible.setter
75
+ def visible(self, value: bool) -> None:
76
+ self._root_frame.visible = value
77
+
78
+ @property
79
+ def shape(self) -> Float[np.ndarray, "10"]:
80
+ return self._shape.copy()
81
+
82
+ def set_shape(self, shape: Float[Array, "10"]) -> None:
83
+ """Update the SMPL-X betas; bone lengths are re-solved, meshes stay."""
84
+ if self._update_shape(shape):
85
+ self._apply_pose()
86
+
87
+ def get_pose(self) -> dict[str, Float[np.ndarray, "..."]]:
88
+ """Return a copy of the currently applied pose parameters."""
89
+ return {name: value.copy() for name, value in self._pose.items()}
90
+
91
+ def set_pose(self, **params: Float[Array, "..."]) -> None:
92
+ """Update any subset of the SMPL-X parameters and move the link meshes."""
93
+ changed = False
94
+ for name, value in params.items():
95
+ if name == "expression":
96
+ continue
97
+ if name == "shape":
98
+ changed |= self._update_shape(value)
99
+ continue
100
+ if name not in self._pose:
101
+ raise KeyError(f"Unknown parameter {name!r}; expected one of {sorted(self._pose)}")
102
+ value = np.asarray(value, dtype=self._pose[name].dtype)
103
+ if value.shape != self._pose[name].shape:
104
+ raise ValueError(
105
+ f"{name} must be unbatched with shape {self._pose[name].shape}, got {tuple(value.shape)}"
106
+ )
107
+ if np.array_equal(self._pose[name], value):
108
+ continue
109
+ self._pose[name] = value
110
+ changed = True
111
+ if changed:
112
+ self._apply_pose()
113
+
114
+ def remove(self) -> None:
115
+ """Remove the mannequin from the scene."""
116
+ for handle in (*self._links, *self._frames, self._root_frame):
117
+ handle.remove()
118
+
119
+ def _update_shape(self, shape: Float[Array, "10"]) -> bool:
120
+ shape = np.asarray(shape, dtype=self._shape.dtype)
121
+ if shape.shape != self._shape.shape:
122
+ raise ValueError(f"shape must be unbatched with shape {self._shape.shape}, got {tuple(shape.shape)}")
123
+ if np.array_equal(self._shape, shape):
124
+ return False
125
+ self._shape = shape
126
+ self._identity = self._model.prepare_identity(shape, skip_vertices=True)
127
+ return True
128
+
129
+ def _apply_pose(self) -> None:
130
+ skeleton = np.asarray(
131
+ self._model.forward_skeleton(
132
+ self._pose["body_pose"],
133
+ self._pose["head_pose"],
134
+ self._pose["hand_pose"],
135
+ pelvis_rotation=self._pose["pelvis_rotation"],
136
+ identity=self._identity,
137
+ global_rotation=self._pose["global_rotation"],
138
+ global_translation=self._pose["global_translation"],
139
+ )
140
+ )[self._frame_joints]
141
+ wxyzs = SO3.conversions.from_rotmat_to_quat(skeleton[:, :3, :3], convention="wxyz", xp=np)
142
+ positions = skeleton[:, :3, 3]
143
+ for frame, wxyz, position in zip(self._frames, wxyzs, positions, strict=True):
144
+ frame.wxyz = wxyz
145
+ frame.position = position
146
+
147
+
148
+ def add_mannequin(
149
+ scene: viser.SceneApi,
150
+ name: str,
151
+ model: SmplxMannequin,
152
+ *,
153
+ palette: str | tuple[Color, Color] = "sand",
154
+ flat_shading: bool = True,
155
+ ) -> ViserMannequinHandle:
156
+ """Add a mannequin to a viser scene and return a handle for posing it.
157
+
158
+ ``palette`` is either a name from :data:`PALETTES` or a custom
159
+ ``(armor, joint)`` RGB pair.
160
+ """
161
+ if isinstance(palette, str):
162
+ if palette not in PALETTES:
163
+ raise ValueError(f"Unknown palette {palette!r}; available: {sorted(PALETTES)}")
164
+ palette = PALETTES[palette]
165
+ armor_color, joint_color = palette
166
+
167
+ pose = model.get_rest_pose()
168
+ del pose["shape"], pose["expression"]
169
+ weights = model._weights
170
+
171
+ root_frame = scene.add_frame(name, show_axes=False)
172
+ frame_joints = sorted(set(weights.link_joint_indices))
173
+ frames = [scene.add_frame(f"{name}/{weights.joint_names[joint]}", show_axes=False) for joint in frame_joints]
174
+
175
+ links = []
176
+ for link, (link_name, mesh) in enumerate(zip(model.link_names, model.link_meshes, strict=True)):
177
+ part = link_name.split("__")[1]
178
+ joint_name = weights.joint_names[weights.link_joint_indices[link]]
179
+ links.append(
180
+ scene.add_mesh_simple(
181
+ f"{name}/{joint_name}/{part}",
182
+ vertices=np.asarray(mesh.vertices, dtype=np.float32),
183
+ faces=np.asarray(mesh.faces),
184
+ color=joint_color if "__joint_" in link_name else armor_color,
185
+ flat_shading=flat_shading,
186
+ wxyz=SO3.conversions.from_rotmat_to_quat(weights.link_geom_rotations[link], convention="wxyz", xp=np),
187
+ position=weights.link_geom_positions[link],
188
+ )
189
+ )
190
+ handle = ViserMannequinHandle(model, pose, root_frame, frames, frame_joints, links)
191
+ handle._apply_pose()
192
+ return handle
193
+
194
+
195
+ __all__ = ["PALETTES", "ViserMannequinHandle", "add_mannequin"]
@@ -0,0 +1,199 @@
1
+ """Shape-dependent identities for the rigid SMPL-X mannequin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, NotRequired, TypedDict
7
+
8
+ import numpy as np
9
+ from jaxtyping import Float
10
+
11
+ from mannequin import _io as io
12
+
13
+ Array = Any
14
+
15
+
16
+ class SmplxMannequinIdentity(TypedDict):
17
+ """Skeleton and rigid geometry prepared once for one beta vector."""
18
+
19
+ rest_joints: Float[Array, "J 3"]
20
+ local_joint_offsets: Float[Array, "J 3"]
21
+ rest_vertices: NotRequired[Float[Array, "V 3"]]
22
+ link_local_vertices: NotRequired[Float[Array, "V 3"]]
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class IdentityTemplate:
27
+ local_offsets: np.ndarray
28
+ rest_joints: np.ndarray
29
+ link_local_vertices: np.ndarray
30
+ joint_geom_anchors: tuple[int, ...]
31
+
32
+
33
+ def build_template(weights: io.MannequinWeights) -> IdentityTemplate:
34
+ """Convert the neutral asset geometry into its owning joints' frames."""
35
+ rest_joints = _joints_from_offsets(weights.local_offsets, weights.parents)
36
+ local_vertices = np.empty_like(weights.vertices)
37
+ anchors = list(weights.link_joint_indices)
38
+
39
+ for link, (start, count) in enumerate(zip(weights.link_vertex_starts, weights.link_vertex_counts, strict=True)):
40
+ vertices = weights.vertices[start : start + count]
41
+ rotation = weights.link_geom_rotations[link]
42
+ position = weights.link_geom_positions[link]
43
+ local_vertices[start : start + count] = vertices @ rotation.T + position
44
+
45
+ name = weights.link_names[link]
46
+ if "shoulder_ball_L" in name:
47
+ anchors[link] = weights.joint_names.index("L_Shoulder")
48
+ elif "shoulder_ball_R" in name:
49
+ anchors[link] = weights.joint_names.index("R_Shoulder")
50
+
51
+ return IdentityTemplate(
52
+ local_offsets=np.asarray(weights.local_offsets),
53
+ rest_joints=rest_joints,
54
+ link_local_vertices=local_vertices,
55
+ joint_geom_anchors=tuple(anchors),
56
+ )
57
+
58
+
59
+ def prepare(
60
+ weights: io.MannequinWeights,
61
+ template: IdentityTemplate,
62
+ calibration: io.ShapeCalibration | None,
63
+ shape: np.ndarray,
64
+ *,
65
+ skip_vertices: bool,
66
+ ) -> SmplxMannequinIdentity:
67
+ """Prepare a symmetric, length-only identity from one SMPL-X beta vector."""
68
+ shape = np.asarray(shape)
69
+ if shape.ndim != 1:
70
+ raise ValueError(f"shape must have shape [S], got {shape.shape}.")
71
+
72
+ local_offsets = template.local_offsets.copy()
73
+ if np.any(shape):
74
+ if calibration is None:
75
+ calibration = io.load_calibration()
76
+ shaped_joints = (calibration.joint_rest + calibration.joint_dirs @ shape).astype(local_offsets.dtype)
77
+ measured_offsets = _offsets_from_joints(shaped_joints, weights.parents)
78
+ local_offsets = _symmetric_length_offsets(template.local_offsets, measured_offsets, weights.joint_names)
79
+ rest_joints = _joints_from_offsets(local_offsets, weights.parents)
80
+ _, mannequin_vertices = _shape_vertices(weights, template, local_offsets, rest_joints)
81
+ smplx_floor = (calibration.sole_y_rest + calibration.sole_y_dirs @ shape).min()
82
+ floor_correction = smplx_floor - mannequin_vertices[:, 1].min()
83
+ ankle_indices = [weights.joint_names.index(name) for name in ("L_Ankle", "R_Ankle")]
84
+ local_offsets[ankle_indices, 1] += floor_correction
85
+
86
+ rest_joints = _joints_from_offsets(local_offsets, weights.parents)
87
+ identity: SmplxMannequinIdentity = {
88
+ "rest_joints": rest_joints,
89
+ "local_joint_offsets": local_offsets,
90
+ }
91
+ if skip_vertices:
92
+ return identity
93
+
94
+ local_vertices, rest_vertices = _shape_vertices(weights, template, local_offsets, rest_joints)
95
+ identity["link_local_vertices"] = local_vertices
96
+ identity["rest_vertices"] = rest_vertices
97
+ return identity
98
+
99
+
100
+ def _offsets_from_joints(joints: np.ndarray, parents: list[int]) -> np.ndarray:
101
+ offsets = np.zeros_like(joints)
102
+ offsets[0] = joints[0]
103
+ for joint in range(1, len(parents)):
104
+ offsets[joint] = joints[joint] - joints[parents[joint]]
105
+ return offsets
106
+
107
+
108
+ def _symmetric_length_offsets(
109
+ neutral_offsets: np.ndarray,
110
+ measured_offsets: np.ndarray,
111
+ joint_names: list[str],
112
+ ) -> np.ndarray:
113
+ result = neutral_offsets.copy()
114
+ result[0] = measured_offsets[0]
115
+ indices = {name: index for index, name in enumerate(joint_names)}
116
+ paired = set()
117
+ reflection = np.array((-1.0, 1.0, 1.0), dtype=result.dtype)
118
+
119
+ for name, left in indices.items():
120
+ if not name.startswith("L_"):
121
+ continue
122
+ right = indices[f"R_{name[2:]}"]
123
+ paired.update((left, right))
124
+ neutral_length = np.linalg.norm(neutral_offsets[left])
125
+ if neutral_length == 0.0:
126
+ result[[left, right]] = 0.0
127
+ continue
128
+ length = 0.5 * (np.linalg.norm(measured_offsets[left]) + np.linalg.norm(measured_offsets[right]))
129
+ result[left] *= length / neutral_length
130
+ result[right] = result[left] * reflection
131
+
132
+ for joint in range(1, len(result)):
133
+ if joint in paired:
134
+ continue
135
+ neutral_length = np.linalg.norm(neutral_offsets[joint])
136
+ if neutral_length > 0.0:
137
+ result[joint] *= np.linalg.norm(measured_offsets[joint]) / neutral_length
138
+ return result
139
+
140
+
141
+ def _shape_vertices(
142
+ weights: io.MannequinWeights,
143
+ template: IdentityTemplate,
144
+ local_offsets: np.ndarray,
145
+ rest_joints: np.ndarray,
146
+ ) -> tuple[np.ndarray, np.ndarray]:
147
+ transforms = _joint_transforms(template.local_offsets, local_offsets, weights.parents)
148
+ local_parts = []
149
+ rest_parts = []
150
+ for link, (owner, start, count, name) in enumerate(
151
+ zip(
152
+ weights.link_joint_indices,
153
+ weights.link_vertex_starts,
154
+ weights.link_vertex_counts,
155
+ weights.link_names,
156
+ strict=True,
157
+ )
158
+ ):
159
+ vertices = template.link_local_vertices[start : start + count]
160
+ if "__joint_" in name:
161
+ anchor = template.joint_geom_anchors[link]
162
+ neutral_anchor = template.rest_joints[anchor] - template.rest_joints[owner]
163
+ shaped_anchor = rest_joints[anchor] - rest_joints[owner]
164
+ vertices = vertices + shaped_anchor - neutral_anchor
165
+ else:
166
+ vertices = vertices @ transforms[owner].T
167
+ local_parts.append(vertices)
168
+ rest_parts.append(vertices + rest_joints[owner])
169
+ return np.concatenate(local_parts), np.concatenate(rest_parts)
170
+
171
+
172
+ def _joint_transforms(
173
+ neutral_offsets: np.ndarray,
174
+ target_offsets: np.ndarray,
175
+ parents: list[int],
176
+ ) -> np.ndarray:
177
+ transforms = np.repeat(np.eye(3, dtype=target_offsets.dtype)[None], len(parents), axis=0)
178
+ children = [[] for _ in parents]
179
+ for joint, parent in enumerate(parents):
180
+ if parent >= 0:
181
+ children[parent].append(joint)
182
+
183
+ for joint, joint_children in enumerate(children):
184
+ if joint_children:
185
+ neutral_axes = neutral_offsets[joint_children].T
186
+ target_axes = target_offsets[joint_children].T
187
+ transforms[joint] += (target_axes - neutral_axes) @ np.linalg.pinv(neutral_axes)
188
+ return transforms
189
+
190
+
191
+ def _joints_from_offsets(offsets: np.ndarray, parents: list[int]) -> np.ndarray:
192
+ joints = np.zeros_like(offsets)
193
+ joints[0] = offsets[0]
194
+ for joint in range(1, len(parents)):
195
+ joints[joint] = joints[parents[joint]] + offsets[joint]
196
+ return joints
197
+
198
+
199
+ __all__ = ["IdentityTemplate", "SmplxMannequinIdentity", "build_template", "prepare"]