15#include <pxr/base/tf/staticTokens.h>
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>
30#include <unordered_set>
32PXR_NAMESPACE_USING_DIRECTIVE
36 (displayColor)(Cd)(color)(vertexColor)(diffuseColor)((
38 "momentum:confidence"))((momentumBlendShapeName,
"momentum:blendShapeName")));
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]);
56Vector3b convertColorToBytes(
float r,
float g,
float b) {
58 const bool isNormalized = (r <= 1.0f && g <= 1.0f && b <= 1.0f);
59 const float scale = isNormalized ? 255.0f : 1.0f;
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))};
66std::vector<Vector3b> loadColorsFromMeshPrim(
const UsdGeomMesh& meshPrim,
size_t numVertices) {
67 std::vector<Vector3b> colors;
68 UsdGeomPrimvarsAPI primvarsAPI(meshPrim);
70 const std::array<TfToken, 5> colorPrimvarNames = {
71 _tokens->displayColor,
75 _tokens->diffuseColor};
77 for (
const auto& colorToken : colorPrimvarNames) {
78 UsdGeomPrimvar colorPrimvar = primvarsAPI.GetPrimvar(colorToken);
79 if (!colorPrimvar || !colorPrimvar.HasValue()) {
84 if (!colorPrimvar.Get(&colorValue)) {
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]));
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]));
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) {
124std::vector<Vector3i> loadFacesFromMeshPrim(
const UsdGeomMesh& meshPrim,
size_t numPoints) {
125 std::vector<Vector3i> faces;
126 VtArray<int> faceVertexCounts;
127 VtArray<int> faceVertexIndices;
129 if (!meshPrim.GetFaceVertexCountsAttr().Get(&faceVertexCounts) ||
130 !meshPrim.GetFaceVertexIndicesAttr().Get(&faceVertexIndices)) {
136 std::string validationReason;
138 !UsdGeomMesh::ValidateTopology(
139 faceVertexIndices, faceVertexCounts, numPoints, &validationReason),
140 "Invalid mesh topology: {}",
143 const bool allTriangles = std::all_of(
144 faceVertexCounts.cbegin(), faceVertexCounts.cend(), [](
int count) { return count == 3; });
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]);
155 size_t indexOffset = 0;
156 for (
int faceVertexCount : faceVertexCounts) {
157 if (faceVertexCount == 3) {
159 faceVertexIndices[indexOffset],
160 faceVertexIndices[indexOffset + 1],
161 faceVertexIndices[indexOffset + 2]);
162 }
else if (faceVertexCount == 4) {
164 faceVertexIndices[indexOffset],
165 faceVertexIndices[indexOffset + 1],
166 faceVertexIndices[indexOffset + 2]);
168 faceVertexIndices[indexOffset],
169 faceVertexIndices[indexOffset + 2],
170 faceVertexIndices[indexOffset + 3]);
172 indexOffset += faceVertexCount;
183 for (
const auto& prim : stage->Traverse()) {
184 if (!prim.IsA<UsdGeomMesh>()) {
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());
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());
204 "Confidence primvar size ({}) != vertex count ({}), skipping",
205 confidenceValues.size(),
222 skinWeights.
index.setZero();
223 skinWeights.
weight.setZero();
225 for (
const auto& prim : stage->Traverse()) {
226 if (!prim.IsA<UsdGeomMesh>()) {
230 UsdGeomMesh meshPrim(prim);
231 UsdSkelBindingAPI bindingAPI(meshPrim.GetPrim());
236 VtArray<int> jointIndices;
237 VtArray<float> jointWeights;
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);
245 if (influencesPerVertex > 0 && jointIndices.size() == numVertices * influencesPerVertex) {
246 for (
size_t v = 0; v < numVertices; ++v) {
247 int validInfluences = 0;
249 i < influencesPerVertex && validInfluences < static_cast<int>(
kMaxSkinJoints);
251 const size_t idx = v * influencesPerVertex + i;
252 int jointIndex = jointIndices[idx];
253 float weight = jointWeights[idx];
255 if (weight > 0.0f && jointIndex >= 0) {
256 skinWeights.
index(v, validInfluences) =
static_cast<uint32_t
>(jointIndex);
257 skinWeights.
weight(v, validInfluences) = weight;
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()));
279 meshPrim.GetPointsAttr().Set(points);
282 VtArray<int> faceVertexCounts;
283 VtArray<int> faceVertexIndices;
284 faceVertexCounts.reserve(mesh.
faces.size());
285 faceVertexIndices.reserve(mesh.
faces.size() * 3);
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());
294 meshPrim.GetFaceVertexCountsAttr().Set(faceVertexCounts);
295 meshPrim.GetFaceVertexIndicesAttr().Set(faceVertexIndices);
299 VtArray<GfVec3f> normals;
300 normals.reserve(mesh.
normals.size());
304 meshPrim.GetNormalsAttr().Set(normals);
305 meshPrim.SetNormalsInterpolation(UsdGeomTokens->vertex);
311 "Skipping vertex colors because color count ({}) does not match vertex count ({})",
314 }
else if (!mesh.
colors.empty()) {
315 UsdGeomPrimvarsAPI primvarsAPI(meshPrim);
316 auto colorPrimvar = primvarsAPI.CreatePrimvar(
317 _tokens->displayColor, SdfValueTypeNames->Color3fArray, UsdGeomTokens->vertex);
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));
324 colorPrimvar.Set(colors);
329 UsdGeomPrimvarsAPI primvarsAPI(meshPrim);
330 auto confidencePrimvar = primvarsAPI.CreatePrimvar(
331 _tokens->momentumConfidence, SdfValueTypeNames->FloatArray, UsdGeomTokens->vertex);
333 confidencePrimvar.Set(confidenceValues);
339 UsdGeomMesh& meshPrim,
340 const UsdSkelSkeleton& skelPrim) {
341 if (skinWeights.
index.rows() == 0) {
345 UsdSkelBindingAPI bindingAPI = UsdSkelBindingAPI::Apply(meshPrim.GetPrim());
346 bindingAPI.GetSkeletonRel().SetTargets({skelPrim.GetPath()});
348 VtArray<int> jointIndices;
349 VtArray<float> jointWeights;
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()));
356 jointIndices.reserve(numVertices * maxInfluences);
357 jointWeights.reserve(numVertices * maxInfluences);
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));
365 for (
int i = numJointsPerVertex; i < maxInfluences; ++i) {
366 jointIndices.push_back(0);
367 jointWeights.push_back(0.0f);
374 bindingAPI.CreateJointIndicesPrimvar(
false, maxInfluences).Set(jointIndices);
375 bindingAPI.CreateJointWeightsPrimvar(
false, maxInfluences).Set(jointWeights);
379 const auto numShapes = blendShape.
shapeSize();
380 const auto numVertices = blendShape.
modelSize();
381 if (numShapes == 0 || numVertices == 0) {
388 SdfPathVector blendShapePaths;
389 blendShapePaths.reserve(numShapes);
390 VtArray<TfToken> blendShapeTokens;
391 blendShapeTokens.reserve(numShapes);
393 auto stage = meshPrim.GetPrim().GetStage();
394 const auto meshPath = meshPrim.GetPath();
396 VtArray<GfVec3f> offsets;
397 offsets.reserve(numVertices);
400 std::unordered_set<std::string> usedSafeNames;
401 usedSafeNames.reserve(numShapes);
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())
407 :
"shape_" + std::to_string(s);
412 std::string baseName = safeName;
414 while (!usedSafeNames.insert(safeName).second) {
415 safeName = baseName +
"_" + std::to_string(suffix++);
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 '{}')",
428 .CreateAttribute(_tokens->momentumBlendShapeName, SdfValueTypeNames->String)
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)));
437 shapePrim.GetOffsetsAttr().Set(offsets);
439 blendShapePaths.push_back(shapePath);
440 blendShapeTokens.push_back(TfToken(safeName));
444 UsdSkelBindingAPI bindingAPI = UsdSkelBindingAPI::Apply(meshPrim.GetPrim());
445 bindingAPI.GetBlendShapesAttr().Set(blendShapeTokens);
446 bindingAPI.GetBlendShapeTargetsRel().SetTargets(blendShapePaths);
450 const UsdStageRefPtr& stage,
451 size_t numVertices) {
452 for (
const auto& prim : stage->Traverse()) {
453 if (!prim.IsA<UsdGeomMesh>()) {
457 UsdSkelBindingAPI bindingAPI(prim);
458 VtArray<TfToken> blendShapeTokens;
459 if (!bindingAPI.GetBlendShapesAttr().Get(&blendShapeTokens) || blendShapeTokens.empty()) {
463 SdfPathVector blendShapePaths;
464 if (!bindingAPI.GetBlendShapeTargetsRel().GetTargets(&blendShapePaths) ||
465 blendShapePaths.empty()) {
469 const auto numShapes =
static_cast<Eigen::Index
>(blendShapePaths.size());
472 std::vector<std::string> shapeNames;
473 shapeNames.reserve(numShapes);
474 MatrixXf shapeVectors = MatrixXf::Zero(3 * numVertices, numShapes);
476 VtArray<GfVec3f> offsets;
477 for (Eigen::Index s = 0; s < numShapes; ++s) {
479 auto shapePrim = UsdSkelBlendShape::Get(stage, blendShapePaths[s]);
481 shapeNames.push_back(blendShapePaths[s].GetName());
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));
489 shapeNames.push_back(blendShapePaths[s].GetName());
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];
504 UsdGeomMesh meshPrim(prim);
505 VtArray<GfVec3f> points;
506 if (!meshPrim.GetPointsAttr().Get(&points) || points.size() != numVertices) {
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]);
515 auto result = std::make_shared<BlendShape>(baseShape, numShapes, shapeNames);
516 result->setShapeVectors(shapeVectors, shapeNames);
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
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.
Vector3< std::uint8_t > Vector3b
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
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.
std::vector< T > confidence
List of per-vertex confidence values Higher values typically indicate higher confidence in the vertex...
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
std::vector< Eigen::Vector3< T > > normals
List of vertex normals (same size as vertices when computed).
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
std::vector< Eigen::Vector3b > colors
List of per-vertex RGB colors (0-255 for each channel).
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")))