Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
usd_mesh_io.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
12#include "momentum/common/log.h"
14
15#include <pxr/base/tf/staticTokens.h>
16
17#include <pxr/base/gf/vec3f.h>
18#include <pxr/base/gf/vec4f.h>
19#include <pxr/base/vt/array.h>
20#include <pxr/usd/sdf/valueTypeName.h>
21#include <pxr/usd/usd/primRange.h>
22#include <pxr/usd/usdGeom/primvarsAPI.h>
23#include <pxr/usd/usdGeom/tokens.h>
24#include <pxr/usd/usdSkel/bindingAPI.h>
25#include <pxr/usd/usdSkel/blendShape.h>
26
27#include <algorithm>
28#include <array>
29#include <string>
30#include <unordered_set>
31
32PXR_NAMESPACE_USING_DIRECTIVE
33
35 _tokens,
36 (displayColor)(Cd)(color)(vertexColor)(diffuseColor)((
37 momentumConfidence,
38 "momentum:confidence"))((momentumBlendShapeName, "momentum:blendShapeName")));
39
40namespace momentum {
41
42namespace {
43
44std::vector<Vector3f> loadVerticesFromMeshPrim(const UsdGeomMesh& meshPrim) {
45 std::vector<Vector3f> vertices;
46 VtArray<GfVec3f> points;
47 if (meshPrim.GetPointsAttr().Get(&points)) {
48 vertices.reserve(points.size());
49 for (const auto& point : points) {
50 vertices.emplace_back(point[0], point[1], point[2]);
51 }
52 }
53 return vertices;
54}
55
56Vector3b convertColorToBytes(float r, float g, float b) {
57 // Detect 0-1 float range vs 0-255 byte range
58 const bool isNormalized = (r <= 1.0f && g <= 1.0f && b <= 1.0f);
59 const float scale = isNormalized ? 255.0f : 1.0f;
60 return {
61 static_cast<uint8_t>(std::clamp(r * scale, 0.0f, 255.0f)),
62 static_cast<uint8_t>(std::clamp(g * scale, 0.0f, 255.0f)),
63 static_cast<uint8_t>(std::clamp(b * scale, 0.0f, 255.0f))};
64}
65
66std::vector<Vector3b> loadColorsFromMeshPrim(const UsdGeomMesh& meshPrim, size_t numVertices) {
67 std::vector<Vector3b> colors;
68 UsdGeomPrimvarsAPI primvarsAPI(meshPrim);
69
70 const std::array<TfToken, 5> colorPrimvarNames = {
71 _tokens->displayColor,
72 _tokens->Cd,
73 _tokens->color,
74 _tokens->vertexColor,
75 _tokens->diffuseColor};
76
77 for (const auto& colorToken : colorPrimvarNames) {
78 UsdGeomPrimvar colorPrimvar = primvarsAPI.GetPrimvar(colorToken);
79 if (!colorPrimvar || !colorPrimvar.HasValue()) {
80 continue;
81 }
82
83 VtValue colorValue;
84 if (!colorPrimvar.Get(&colorValue)) {
85 continue;
86 }
87
88 if (colorValue.IsHolding<VtArray<GfVec3f>>()) {
89 VtArray<GfVec3f> rawColors = colorValue.Get<VtArray<GfVec3f>>();
90 if (rawColors.size() == numVertices) {
91 colors.reserve(rawColors.size());
92 for (const auto& color : rawColors) {
93 colors.push_back(convertColorToBytes(color[0], color[1], color[2]));
94 }
95 break;
96 }
97 } else if (colorValue.IsHolding<VtArray<GfVec4f>>()) {
98 VtArray<GfVec4f> rawColors = colorValue.Get<VtArray<GfVec4f>>();
99 if (rawColors.size() == numVertices) {
100 colors.reserve(rawColors.size());
101 for (const auto& color : rawColors) {
102 colors.push_back(convertColorToBytes(color[0], color[1], color[2]));
103 }
104 break;
105 }
106 }
107 }
108
109 return colors;
110}
111
112std::vector<Vector3f> loadNormalsFromMeshPrim(const UsdGeomMesh& meshPrim, size_t numVertices) {
113 std::vector<Vector3f> normals;
114 VtArray<GfVec3f> rawNormals;
115 if (meshPrim.GetNormalsAttr().Get(&rawNormals) && rawNormals.size() == numVertices) {
116 normals.reserve(rawNormals.size());
117 for (const auto& normal : rawNormals) {
118 normals.emplace_back(normal[0], normal[1], normal[2]);
119 }
120 }
121 return normals;
122}
123
124std::vector<Vector3i> loadFacesFromMeshPrim(const UsdGeomMesh& meshPrim, size_t numPoints) {
125 std::vector<Vector3i> faces;
126 VtArray<int> faceVertexCounts;
127 VtArray<int> faceVertexIndices;
128
129 if (!meshPrim.GetFaceVertexCountsAttr().Get(&faceVertexCounts) ||
130 !meshPrim.GetFaceVertexIndicesAttr().Get(&faceVertexIndices)) {
131 return faces;
132 }
133
134 // Validate that faceVertexCounts and faceVertexIndices are consistent
135 // (e.g., sum of counts == indices length) before accessing indices.
136 std::string validationReason;
138 !UsdGeomMesh::ValidateTopology(
139 faceVertexIndices, faceVertexCounts, numPoints, &validationReason),
140 "Invalid mesh topology: {}",
141 validationReason);
142
143 const bool allTriangles = std::all_of(
144 faceVertexCounts.cbegin(), faceVertexCounts.cend(), [](int count) { return count == 3; });
145
146 if (allTriangles && faceVertexIndices.size() == faceVertexCounts.size() * 3) {
147 faces.reserve(faceVertexCounts.size());
148 const int* indices = faceVertexIndices.cdata();
149 for (size_t i = 0; i < faceVertexCounts.size(); ++i) {
150 faces.emplace_back(indices[i * 3], indices[i * 3 + 1], indices[i * 3 + 2]);
151 }
152 return faces;
153 }
154
155 size_t indexOffset = 0;
156 for (int faceVertexCount : faceVertexCounts) {
157 if (faceVertexCount == 3) {
158 faces.emplace_back(
159 faceVertexIndices[indexOffset],
160 faceVertexIndices[indexOffset + 1],
161 faceVertexIndices[indexOffset + 2]);
162 } else if (faceVertexCount == 4) {
163 faces.emplace_back(
164 faceVertexIndices[indexOffset],
165 faceVertexIndices[indexOffset + 1],
166 faceVertexIndices[indexOffset + 2]);
167 faces.emplace_back(
168 faceVertexIndices[indexOffset],
169 faceVertexIndices[indexOffset + 2],
170 faceVertexIndices[indexOffset + 3]);
171 }
172 indexOffset += faceVertexCount;
173 }
174
175 return faces;
176}
177
178} // namespace
179
180Mesh loadMeshFromUsd(const UsdStageRefPtr& stage) {
181 Mesh mesh;
182
183 for (const auto& prim : stage->Traverse()) {
184 if (!prim.IsA<UsdGeomMesh>()) {
185 continue;
186 }
187
188 UsdGeomMesh meshPrim(prim);
189 mesh.vertices = loadVerticesFromMeshPrim(meshPrim);
190 mesh.colors = loadColorsFromMeshPrim(meshPrim, mesh.vertices.size());
191 mesh.normals = loadNormalsFromMeshPrim(meshPrim, mesh.vertices.size());
192 mesh.faces = loadFacesFromMeshPrim(meshPrim, mesh.vertices.size());
193
194 // Load per-vertex confidence from custom primvar
195 UsdGeomPrimvarsAPI primvarsAPI(meshPrim);
196 UsdGeomPrimvar confidencePrimvar = primvarsAPI.GetPrimvar(_tokens->momentumConfidence);
197 if (confidencePrimvar && confidencePrimvar.HasValue()) {
198 VtArray<float> confidenceValues;
199 if (confidencePrimvar.Get(&confidenceValues)) {
200 if (confidenceValues.size() == mesh.vertices.size()) {
201 mesh.confidence.assign(confidenceValues.begin(), confidenceValues.end());
202 } else {
203 MT_LOGW(
204 "Confidence primvar size ({}) != vertex count ({}), skipping",
205 confidenceValues.size(),
206 mesh.vertices.size());
207 }
208 }
209 }
210
211 break; // Use first mesh found
212 }
213
214 return mesh;
215}
216
217SkinWeights loadSkinWeightsFromUsd(const UsdStageRefPtr& stage, size_t numVertices) {
218 SkinWeights skinWeights;
219
220 skinWeights.index.resize(numVertices, kMaxSkinJoints);
221 skinWeights.weight.resize(numVertices, kMaxSkinJoints);
222 skinWeights.index.setZero();
223 skinWeights.weight.setZero();
224
225 for (const auto& prim : stage->Traverse()) {
226 if (!prim.IsA<UsdGeomMesh>()) {
227 continue;
228 }
229
230 UsdGeomMesh meshPrim(prim);
231 UsdSkelBindingAPI bindingAPI(meshPrim.GetPrim());
232 if (!bindingAPI) {
233 continue;
234 }
235
236 VtArray<int> jointIndices;
237 VtArray<float> jointWeights;
238
239 if (bindingAPI.GetJointIndicesAttr().Get(&jointIndices) &&
240 bindingAPI.GetJointWeightsAttr().Get(&jointWeights)) {
241 if (!jointIndices.empty() && !jointWeights.empty() &&
242 jointIndices.size() == jointWeights.size()) {
243 const int influencesPerVertex = static_cast<int>(jointIndices.size() / numVertices);
244
245 if (influencesPerVertex > 0 && jointIndices.size() == numVertices * influencesPerVertex) {
246 for (size_t v = 0; v < numVertices; ++v) {
247 int validInfluences = 0;
248 for (int i = 0;
249 i < influencesPerVertex && validInfluences < static_cast<int>(kMaxSkinJoints);
250 ++i) {
251 const size_t idx = v * influencesPerVertex + i;
252 int jointIndex = jointIndices[idx];
253 float weight = jointWeights[idx];
254
255 if (weight > 0.0f && jointIndex >= 0) {
256 skinWeights.index(v, validInfluences) = static_cast<uint32_t>(jointIndex);
257 skinWeights.weight(v, validInfluences) = weight;
258 validInfluences++;
259 }
260 }
261 }
262 }
263 }
264 }
265
266 break; // Use first skinned mesh found
267 }
268
269 return skinWeights;
270}
271
272void saveMeshToUsd(const Mesh& mesh, UsdGeomMesh& meshPrim) {
273 // Write vertices
274 VtArray<GfVec3f> points;
275 points.reserve(mesh.vertices.size());
276 for (const auto& vertex : mesh.vertices) {
277 points.push_back(GfVec3f(vertex.x(), vertex.y(), vertex.z()));
278 }
279 meshPrim.GetPointsAttr().Set(points);
280
281 // Write faces
282 VtArray<int> faceVertexCounts;
283 VtArray<int> faceVertexIndices;
284 faceVertexCounts.reserve(mesh.faces.size());
285 faceVertexIndices.reserve(mesh.faces.size() * 3);
286
287 for (const auto& face : mesh.faces) {
288 faceVertexCounts.push_back(3);
289 faceVertexIndices.push_back(face.x());
290 faceVertexIndices.push_back(face.y());
291 faceVertexIndices.push_back(face.z());
292 }
293
294 meshPrim.GetFaceVertexCountsAttr().Set(faceVertexCounts);
295 meshPrim.GetFaceVertexIndicesAttr().Set(faceVertexIndices);
296
297 // Write normals
298 if (!mesh.normals.empty()) {
299 VtArray<GfVec3f> normals;
300 normals.reserve(mesh.normals.size());
301 for (const auto& normal : mesh.normals) {
302 normals.push_back(GfVec3f(normal.x(), normal.y(), normal.z()));
303 }
304 meshPrim.GetNormalsAttr().Set(normals);
305 meshPrim.SetNormalsInterpolation(UsdGeomTokens->vertex);
306 }
307
308 // Write vertex colors
309 if (!mesh.colors.empty() && mesh.colors.size() != mesh.vertices.size()) {
310 MT_LOGW(
311 "Skipping vertex colors because color count ({}) does not match vertex count ({})",
312 mesh.colors.size(),
313 mesh.vertices.size());
314 } else if (!mesh.colors.empty()) {
315 UsdGeomPrimvarsAPI primvarsAPI(meshPrim);
316 auto colorPrimvar = primvarsAPI.CreatePrimvar(
317 _tokens->displayColor, SdfValueTypeNames->Color3fArray, UsdGeomTokens->vertex);
318
319 VtArray<GfVec3f> colors;
320 colors.reserve(mesh.colors.size());
321 for (const auto& color : mesh.colors) {
322 colors.push_back(GfVec3f(color.x() / 255.0f, color.y() / 255.0f, color.z() / 255.0f));
323 }
324 colorPrimvar.Set(colors);
325 }
326
327 // Write per-vertex confidence
328 if (!mesh.confidence.empty()) {
329 UsdGeomPrimvarsAPI primvarsAPI(meshPrim);
330 auto confidencePrimvar = primvarsAPI.CreatePrimvar(
331 _tokens->momentumConfidence, SdfValueTypeNames->FloatArray, UsdGeomTokens->vertex);
332 VtArray<float> confidenceValues(mesh.confidence.begin(), mesh.confidence.end());
333 confidencePrimvar.Set(confidenceValues);
334 }
335}
336
338 const SkinWeights& skinWeights,
339 UsdGeomMesh& meshPrim,
340 const UsdSkelSkeleton& skelPrim) {
341 if (skinWeights.index.rows() == 0) {
342 return;
343 }
344
345 UsdSkelBindingAPI bindingAPI = UsdSkelBindingAPI::Apply(meshPrim.GetPrim());
346 bindingAPI.GetSkeletonRel().SetTargets({skelPrim.GetPath()});
347
348 VtArray<int> jointIndices;
349 VtArray<float> jointWeights;
350
351 const int maxInfluences = 4;
352 const int numVertices = static_cast<int>(skinWeights.index.rows());
353 const int numJointsPerVertex =
354 std::min(maxInfluences, static_cast<int>(skinWeights.index.cols()));
355
356 jointIndices.reserve(numVertices * maxInfluences);
357 jointWeights.reserve(numVertices * maxInfluences);
358
359 for (int v = 0; v < numVertices; ++v) {
360 for (int i = 0; i < numJointsPerVertex; ++i) {
361 jointIndices.push_back(skinWeights.index(v, i));
362 jointWeights.push_back(skinWeights.weight(v, i));
363 }
364
365 for (int i = numJointsPerVertex; i < maxInfluences; ++i) {
366 jointIndices.push_back(0);
367 jointWeights.push_back(0.0f);
368 }
369 }
370
371 // Create primvars with correct elementSize and "vertex" interpolation.
372 // Without elementSize, UsdSkel viewers can't determine how many influences
373 // per vertex exist and the skinning silently fails.
374 bindingAPI.CreateJointIndicesPrimvar(false, maxInfluences).Set(jointIndices);
375 bindingAPI.CreateJointWeightsPrimvar(false, maxInfluences).Set(jointWeights);
376}
377
378void saveBlendShapesToUsd(const BlendShape& blendShape, UsdGeomMesh& meshPrim) {
379 const auto numShapes = blendShape.shapeSize();
380 const auto numVertices = blendShape.modelSize();
381 if (numShapes == 0 || numVertices == 0) {
382 return;
383 }
384
385 const auto& shapeVectors = blendShape.getShapeVectors();
386 const auto& shapeNames = blendShape.getShapeNames();
387
388 SdfPathVector blendShapePaths;
389 blendShapePaths.reserve(numShapes);
390 VtArray<TfToken> blendShapeTokens;
391 blendShapeTokens.reserve(numShapes);
392
393 auto stage = meshPrim.GetPrim().GetStage();
394 const auto meshPath = meshPrim.GetPath();
395
396 VtArray<GfVec3f> offsets;
397 offsets.reserve(numVertices);
398
399 // Track sanitized names to detect collisions from different original names
400 std::unordered_set<std::string> usedSafeNames;
401 usedSafeNames.reserve(numShapes);
402
403 for (Eigen::Index s = 0; s < numShapes; ++s) {
404 const std::string originalName =
405 (s < static_cast<Eigen::Index>(shapeNames.size()) && !shapeNames[s].empty())
406 ? shapeNames[s]
407 : "shape_" + std::to_string(s);
408
409 std::string safeName = sanitizePrimName(originalName);
410
411 // Disambiguate if sanitized name collides with an existing one
412 std::string baseName = safeName;
413 int suffix = 1;
414 while (!usedSafeNames.insert(safeName).second) {
415 safeName = baseName + "_" + std::to_string(suffix++);
416 }
417
418 auto shapePath = meshPath.AppendChild(TfToken(safeName));
419 auto shapePrim = UsdSkelBlendShape::Define(stage, shapePath);
421 !shapePrim.GetPrim().IsValid(),
422 "Failed to create blend shape prim '{}' (from '{}')",
423 safeName,
424 originalName);
425
426 // Store the original unsanitized name for round-trip fidelity
427 shapePrim.GetPrim()
428 .CreateAttribute(_tokens->momentumBlendShapeName, SdfValueTypeNames->String)
429 .Set(originalName);
430
431 // Extract per-vertex offsets from the shape vector column
432 offsets.clear();
433 for (size_t v = 0; v < numVertices; ++v) {
434 offsets.push_back(GfVec3f(
435 shapeVectors(3 * v + 0, s), shapeVectors(3 * v + 1, s), shapeVectors(3 * v + 2, s)));
436 }
437 shapePrim.GetOffsetsAttr().Set(offsets);
438
439 blendShapePaths.push_back(shapePath);
440 blendShapeTokens.push_back(TfToken(safeName));
441 }
442
443 // Bind blend shapes to the mesh
444 UsdSkelBindingAPI bindingAPI = UsdSkelBindingAPI::Apply(meshPrim.GetPrim());
445 bindingAPI.GetBlendShapesAttr().Set(blendShapeTokens);
446 bindingAPI.GetBlendShapeTargetsRel().SetTargets(blendShapePaths);
447}
448
449std::shared_ptr<BlendShape> loadBlendShapesFromUsd(
450 const UsdStageRefPtr& stage,
451 size_t numVertices) {
452 for (const auto& prim : stage->Traverse()) {
453 if (!prim.IsA<UsdGeomMesh>()) {
454 continue;
455 }
456
457 UsdSkelBindingAPI bindingAPI(prim);
458 VtArray<TfToken> blendShapeTokens;
459 if (!bindingAPI.GetBlendShapesAttr().Get(&blendShapeTokens) || blendShapeTokens.empty()) {
460 continue;
461 }
462
463 SdfPathVector blendShapePaths;
464 if (!bindingAPI.GetBlendShapeTargetsRel().GetTargets(&blendShapePaths) ||
465 blendShapePaths.empty()) {
466 continue;
467 }
468
469 const auto numShapes = static_cast<Eigen::Index>(blendShapePaths.size());
470
471 // Collect shape names and offsets
472 std::vector<std::string> shapeNames;
473 shapeNames.reserve(numShapes);
474 MatrixXf shapeVectors = MatrixXf::Zero(3 * numVertices, numShapes);
475
476 VtArray<GfVec3f> offsets;
477 for (Eigen::Index s = 0; s < numShapes; ++s) {
478 // Prefer the stored original name over the sanitized prim name
479 auto shapePrim = UsdSkelBlendShape::Get(stage, blendShapePaths[s]);
480 if (!shapePrim) {
481 shapeNames.push_back(blendShapePaths[s].GetName());
482 continue;
483 }
484 std::string shapeName;
485 if (auto nameAttr = shapePrim.GetPrim().GetAttribute(_tokens->momentumBlendShapeName);
486 nameAttr && nameAttr.Get(&shapeName)) {
487 shapeNames.push_back(std::move(shapeName));
488 } else {
489 shapeNames.push_back(blendShapePaths[s].GetName());
490 }
491
492 offsets.clear();
493 if (shapePrim.GetOffsetsAttr().Get(&offsets)) {
494 const size_t count = std::min(offsets.size(), numVertices);
495 for (size_t v = 0; v < count; ++v) {
496 shapeVectors(3 * v + 0, s) = offsets[v][0];
497 shapeVectors(3 * v + 1, s) = offsets[v][1];
498 shapeVectors(3 * v + 2, s) = offsets[v][2];
499 }
500 }
501 }
502
503 // Build base shape from mesh vertices
504 UsdGeomMesh meshPrim(prim);
505 VtArray<GfVec3f> points;
506 if (!meshPrim.GetPointsAttr().Get(&points) || points.size() != numVertices) {
507 continue;
508 }
509 std::vector<Vector3f> baseShape;
510 baseShape.reserve(points.size());
511 for (const auto& p : points) {
512 baseShape.emplace_back(p[0], p[1], p[2]);
513 }
514
515 auto result = std::make_shared<BlendShape>(baseShape, numShapes, shapeNames);
516 result->setShapeVectors(shapeVectors, shapeNames);
517
518 return result;
519 }
520
521 return nullptr;
522}
523
524} // namespace momentum
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
#define MT_LOGW(...)
Definition log.h:180
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
Definition random-inl.h:382
void saveMeshToUsd(const Mesh &mesh, UsdGeomMesh &meshPrim)
Save a mesh to a USD stage.
std::shared_ptr< BlendShape > loadBlendShapesFromUsd(const UsdStageRefPtr &stage, size_t numVertices)
Load blend shapes from a USD stage.
void saveBlendShapesToUsd(const BlendShape &blendShape, UsdGeomMesh &meshPrim)
Save blend shapes to a USD stage.
std::string sanitizePrimName(const std::string &name)
Sanitize a string for use as a USD SDF prim name.
Definition usd_utils.cpp:14
Vector3< std::uint8_t > Vector3b
Definition types.h:269
MeshT< float > Mesh
Definition fwd.h:20
SkinWeights loadSkinWeightsFromUsd(const UsdStageRefPtr &stage, size_t numVertices)
Load skin weights from a USD stage.
void saveSkinWeightsToUsd(const SkinWeights &skinWeights, UsdGeomMesh &meshPrim, const UsdSkelSkeleton &skelPrim)
Save skin weights to a USD stage.
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
Mesh loadMeshFromUsd(const UsdStageRefPtr &stage)
Load a mesh from a USD stage.
MatrixX< float > MatrixXf
Definition types.h:82
const MatrixXf & getShapeVectors() const
const std::vector< std::string > & getShapeNames() const
Eigen::Index shapeSize() const
Skinning class that combines blend shape vectors with a base shape.
Definition blend_shape.h:19
std::vector< T > confidence
List of per-vertex confidence values Higher values typically indicate higher confidence in the vertex...
Definition mesh.h:39
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
std::vector< Eigen::Vector3< T > > normals
List of vertex normals (same size as vertices when computed).
Definition mesh.h:25
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
Definition mesh.h:28
std::vector< Eigen::Vector3b > colors
List of per-vertex RGB colors (0-255 for each channel).
Definition mesh.h:35
Linear blend skinning weights for a character mesh: per-vertex joint indices and influence weights.
WeightMatrix weight
Joint influence weights per vertex.
IndexMatrix index
Joint indices influencing each vertex.
PXR_NAMESPACE_USING_DIRECTIVE TF_DEFINE_PRIVATE_TOKENS(_tokens,(displayColor)(Cd)(color)(vertexColor)(diffuseColor)((momentumConfidence, "momentum:confidence"))((momentumBlendShapeName, "momentum:blendShapeName")))