Blender V5.0
usd_reader_mesh.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later
4 * Adapted from the Blender Alembic importer implementation.
5 * Modifications Copyright 2021 Tangent Animation and
6 * NVIDIA Corporation. All rights reserved. */
7
8#include "usd_reader_mesh.hh"
9#include "usd.hh"
11#include "usd_hash_types.hh"
12#include "usd_mesh_utils.hh"
14#include "usd_skel_convert.hh"
15#include "usd_utils.hh"
16
17#include "BKE_attribute.hh"
18#include "BKE_customdata.hh"
19#include "BKE_geometry_set.hh"
20#include "BKE_main.hh"
21#include "BKE_material.hh"
22#include "BKE_mesh.hh"
23#include "BKE_object.hh"
24#include "BKE_report.hh"
25#include "BKE_subdiv.hh"
26
27#include "BLI_array.hh"
28#include "BLI_map.hh"
30#include "BLI_ordered_edge.hh"
31#include "BLI_set.hh"
32#include "BLI_span.hh"
33#include "BLI_task.hh"
34#include "BLI_vector_set.hh"
35
36#include "BLT_translation.hh"
37
39#include "DNA_material_types.h"
40#include "DNA_modifier_types.h"
41#include "DNA_object_types.h"
43
44#include <pxr/base/gf/matrix4f.h>
45#include <pxr/base/vt/array.h>
46#include <pxr/base/vt/types.h>
47#include <pxr/usd/sdf/types.h>
48#include <pxr/usd/usdGeom/primvarsAPI.h>
49#include <pxr/usd/usdGeom/subset.h>
50#include <pxr/usd/usdShade/materialBindingAPI.h>
51#include <pxr/usd/usdShade/tokens.h>
52#include <pxr/usd/usdSkel/bindingAPI.h>
53
54#include <fmt/core.h>
55
56#include <algorithm>
57
58#include "CLG_log.h"
59static CLG_LogRef LOG = {"io.usd"};
60
61namespace usdtokens {
62/* Materials */
63static const pxr::TfToken st("st", pxr::TfToken::Immortal);
64static const pxr::TfToken normalsPrimvar("normals", pxr::TfToken::Immortal);
65} // namespace usdtokens
66
67namespace blender::io::usd {
68
69namespace utils {
70
71static pxr::UsdShadeMaterial compute_bound_material(const pxr::UsdPrim &prim,
72 eUSDMtlPurpose mtl_purpose)
73{
74 const pxr::UsdShadeMaterialBindingAPI api = pxr::UsdShadeMaterialBindingAPI(prim);
75
76 /* See the following documentation for material resolution behavior:
77 * https://openusd.org/release/api/class_usd_shade_material_binding_a_p_i.html#UsdShadeMaterialBindingAPI_MaterialResolution
78 */
79
80 pxr::UsdShadeMaterial mtl;
81 switch (mtl_purpose) {
83 mtl = api.ComputeBoundMaterial(pxr::UsdShadeTokens->full);
84 if (!mtl) {
85 /* Add an additional Blender-specific fallback to help with oddly authored USD files. */
86 mtl = api.ComputeBoundMaterial(pxr::UsdShadeTokens->preview);
87 }
88 break;
90 mtl = api.ComputeBoundMaterial(pxr::UsdShadeTokens->preview);
91 break;
93 mtl = api.ComputeBoundMaterial(pxr::UsdShadeTokens->allPurpose);
94 break;
95 }
96
97 return mtl;
98}
99
100static void assign_materials(Main *bmain,
101 Object *ob,
102 const blender::Map<pxr::SdfPath, int> &mat_index_map,
103 const USDImportParams &params,
104 pxr::UsdStageRefPtr stage,
105 const ImportSettings &settings)
106{
107 if (!(stage && bmain && ob)) {
108 return;
109 }
110
111 if (mat_index_map.size() > MAXMAT) {
112 return;
113 }
114
115 USDMaterialReader mat_reader(params, *bmain);
116
117 for (const auto item : mat_index_map.items()) {
118 Material *assigned_mat = find_existing_material(
119 item.key, params, settings.mat_name_to_mat, settings.usd_path_to_mat);
120 if (!assigned_mat) {
121 /* Blender material doesn't exist, so create it now. */
122
123 /* Look up the USD material. */
124 pxr::UsdPrim prim = stage->GetPrimAtPath(item.key);
125 pxr::UsdShadeMaterial usd_mat(prim);
126
127 if (!usd_mat) {
128 CLOG_WARN(
129 &LOG, "Couldn't construct USD material from prim %s", item.key.GetAsString().c_str());
130 continue;
131 }
132
133 const bool have_import_hook = settings.mat_import_hook_sources.contains(item.key);
134
135 /* Add the Blender material. If we have an import hook which can handle this material
136 * we don't import USD Preview Surface shaders. */
137 assigned_mat = mat_reader.add_material(usd_mat, !have_import_hook);
138
139 if (!assigned_mat) {
140 CLOG_WARN(&LOG,
141 "Couldn't create Blender material from USD material %s",
142 item.key.GetAsString().c_str());
143 continue;
144 }
145
146 settings.mat_name_to_mat.add_new(assigned_mat->id.name + 2, assigned_mat);
147
148 if (params.mtl_name_collision_mode == USD_MTL_NAME_COLLISION_MAKE_UNIQUE) {
149 /* Record the Blender material we created for the USD material with the given path. */
150 settings.usd_path_to_mat.add_new(item.key, assigned_mat);
151 }
152
153 if (have_import_hook) {
154 /* Defer invoking the hook to convert the material till we can do so from
155 * the main thread. */
156 settings.usd_path_to_mat_for_hook.add_new(item.key, assigned_mat);
157 }
158 }
159
160 if (assigned_mat) {
161 BKE_object_material_assign_single_obdata(bmain, ob, assigned_mat, item.value);
162 }
163 else {
164 /* This shouldn't happen. */
165 CLOG_WARN(&LOG, "Couldn't assign material %s", item.key.GetAsString().c_str());
166 }
167 }
168 if (ob->totcol > 0) {
169 ob->actcol = 1;
170 }
171}
172
173} // namespace utils
174
176{
177 Mesh *mesh = BKE_mesh_add(bmain, name_.c_str());
178
180 object_->data = mesh;
181}
182
183void USDMeshReader::read_object_data(Main *bmain, const pxr::UsdTimeCode time)
184{
185 Mesh *mesh = (Mesh *)object_->data;
186
187 is_initial_load_ = true;
188 const USDMeshReadParams params = create_mesh_read_params(time.GetValue(),
189 import_params_.mesh_read_flag);
190
191 Mesh *read_mesh = this->read_mesh(mesh, params, nullptr);
192
193 is_initial_load_ = false;
194 if (read_mesh != mesh) {
195 BKE_mesh_nomain_to_mesh(read_mesh, mesh, object_);
196 }
197
198 readFaceSetsSample(bmain, mesh, time);
199
200 if (mesh_prim_.GetPointsAttr().ValueMightBeTimeVarying() ||
201 mesh_prim_.GetNormalsAttr().ValueMightBeTimeVarying() ||
202 mesh_prim_.GetVelocitiesAttr().ValueMightBeTimeVarying() ||
203 mesh_prim_.GetCreaseSharpnessesAttr().ValueMightBeTimeVarying() ||
204 mesh_prim_.GetCreaseLengthsAttr().ValueMightBeTimeVarying() ||
205 mesh_prim_.GetCreaseIndicesAttr().ValueMightBeTimeVarying() ||
206 mesh_prim_.GetCornerSharpnessesAttr().ValueMightBeTimeVarying() ||
207 mesh_prim_.GetCornerIndicesAttr().ValueMightBeTimeVarying())
208 {
209 is_time_varying_ = true;
210 }
211
212 if (is_time_varying_) {
214 }
215
216 if (import_params_.import_subdivision) {
217 pxr::TfToken subdivScheme;
218 mesh_prim_.GetSubdivisionSchemeAttr().Get(&subdivScheme, time);
219
220 if (subdivScheme == pxr::UsdGeomTokens->catmullClark) {
222 read_subdiv();
223 }
224 }
225
226 if (import_params_.import_blendshapes) {
228 }
229
230 if (import_params_.import_skeletons) {
232 }
233
235}
236
237bool USDMeshReader::topology_changed(const Mesh *existing_mesh, const pxr::UsdTimeCode time)
238{
239 /* TODO(makowalski): Is it the best strategy to cache the mesh
240 * geometry in this function? This needs to be revisited. */
241
242 mesh_prim_.GetFaceVertexIndicesAttr().Get(&face_indices_, time);
243 mesh_prim_.GetFaceVertexCountsAttr().Get(&face_counts_, time);
244 mesh_prim_.GetPointsAttr().Get(&positions_, time);
245
246 const pxr::UsdGeomPrimvarsAPI primvarsAPI(mesh_prim_);
247
248 /* TODO(makowalski): Reading normals probably doesn't belong in this function,
249 * as this is not required to determine if the topology has changed. */
250
251 /* If 'normals' and 'primvars:normals' are both specified, the latter has precedence. */
252 const pxr::UsdGeomPrimvar primvar = primvarsAPI.GetPrimvar(usdtokens::normalsPrimvar);
253 if (primvar.HasValue()) {
254 primvar.ComputeFlattened(&normals_, time);
255 normal_interpolation_ = primvar.GetInterpolation();
256 }
257 else {
258 mesh_prim_.GetNormalsAttr().Get(&normals_, time);
259 normal_interpolation_ = mesh_prim_.GetNormalsInterpolation();
260 }
261
262 return positions_.size() != existing_mesh->verts_num ||
263 face_counts_.size() != existing_mesh->faces_num ||
264 face_indices_.size() != existing_mesh->corners_num;
265}
266
267bool USDMeshReader::read_faces(Mesh *mesh) const
268{
269 MutableSpan<int> face_offsets = mesh->face_offsets_for_write();
270 MutableSpan<int> corner_verts = mesh->corner_verts_for_write();
271
272 int loop_index = 0;
273
274 for (int i = 0; i < face_counts_.size(); i++) {
275 const int face_size = face_counts_[i];
276
277 face_offsets[i] = loop_index;
278
279 /* Polygons are always assumed to be smooth-shaded. If the mesh should be flat-shaded,
280 * this is encoded in custom loop normals. */
281
282 if (is_left_handed_) {
283 int loop_end_index = loop_index + (face_size - 1);
284 for (int f = 0; f < face_size; ++f, ++loop_index) {
285 corner_verts[loop_index] = face_indices_[loop_end_index - f];
286 }
287 }
288 else {
289 for (int f = 0; f < face_size; ++f, ++loop_index) {
290 corner_verts[loop_index] = face_indices_[loop_index];
291 }
292 }
293 }
294
295 /* Check for faces with duplicate vertex indices. These will require a mesh validate to fix. */
296 const OffsetIndices<int> faces = mesh->faces();
297 const bool all_faces_ok = threading::parallel_reduce(
298 faces.index_range(),
299 1024,
300 true,
301 [&](const IndexRange part, const bool ok_so_far) {
302 bool current_faces_ok = ok_so_far;
303 if (ok_so_far) {
304 for (const int i : part) {
305 const IndexRange face_range = faces[i];
306 const Set<int, 32> used_verts(corner_verts.slice(face_range));
307 current_faces_ok = current_faces_ok && used_verts.size() == face_range.size();
308 }
309 }
310 return current_faces_ok;
311 },
312 std::logical_and<>());
313
314 /* If we detect bad faces it would be unsafe to continue beyond this point without first
315 * performing a destructive validate. Any operation requiring mesh connectivity information can
316 * assert or crash if the problem isn't addressed. Performing the check here, before most of the
317 * data has been loaded, unfortunately means any remaining data will be lost. */
318 if (!all_faces_ok) {
319 if (is_initial_load_) {
320 const char *message = N_(
321 "Invalid face data detected for mesh '%s'. Automatic correction will be used, but some "
322 "data will most likely be lost");
323 const std::string prim_path = this->prim_path().GetAsString();
324 BKE_reportf(this->reports(), RPT_WARNING, message, prim_path.c_str());
325 CLOG_WARN(&LOG, message, prim_path.c_str());
326 }
327 BKE_mesh_validate(mesh, false, false);
328 }
329
330 bke::mesh_calc_edges(*mesh, false, false);
331
332 /* It's possible that the number of faces, indices, and verts remain the same but the topology
333 * itself is different. Until finer-grained topology detection can be implemented, always tag the
334 * mesh as needing updated topology mappings. Without this, a time varying mesh could trigger
335 * undefined behavior. */
336 mesh->tag_topology_changed();
337
338 return all_faces_ok;
339}
340
341void USDMeshReader::read_uv_data_primvar(Mesh *mesh,
342 const pxr::UsdGeomPrimvar &primvar,
343 const pxr::UsdTimeCode time)
344{
345 const StringRef primvar_name(
346 pxr::UsdGeomPrimvar::StripPrimvarsName(primvar.GetName()).GetString());
347
348 const pxr::VtVec2fArray usd_uvs = get_primvar_array<pxr::GfVec2f>(primvar, time);
349 if (usd_uvs.empty()) {
350 return;
351 }
352
353 const pxr::TfToken varying_type = primvar.GetInterpolation();
354 BLI_assert(ELEM(varying_type,
355 pxr::UsdGeomTokens->vertex,
356 pxr::UsdGeomTokens->faceVarying,
357 pxr::UsdGeomTokens->varying));
358
359 if ((varying_type == pxr::UsdGeomTokens->faceVarying && usd_uvs.size() != mesh->corners_num) ||
360 (varying_type == pxr::UsdGeomTokens->vertex && usd_uvs.size() != mesh->verts_num) ||
361 (varying_type == pxr::UsdGeomTokens->varying && usd_uvs.size() != mesh->verts_num))
362 {
363 BKE_reportf(reports(),
365 "USD Import: UV attribute value '%s' count inconsistent with interpolation type",
366 primvar.GetName().GetText());
367 return;
368 }
369
370 bke::MutableAttributeAccessor attributes = mesh->attributes_for_write();
371 bke::SpanAttributeWriter<float2> uv_data = attributes.lookup_or_add_for_write_only_span<float2>(
372 primvar_name, bke::AttrDomain::Corner);
373
374 if (!uv_data) {
375 BKE_reportf(reports(),
377 "USD Import: couldn't add UV attribute '%s'",
378 primvar.GetBaseName().GetText());
379 return;
380 }
381
382 if (varying_type == pxr::UsdGeomTokens->faceVarying) {
383 if (is_left_handed_) {
384 /* Reverse the index order. */
385 const OffsetIndices faces = mesh->faces();
386 for (const int i : faces.index_range()) {
387 const IndexRange face = faces[i];
388 for (int j : face.index_range()) {
389 const int rev_index = face.last(j);
390 uv_data.span[face.start() + j] = float2(usd_uvs[rev_index][0], usd_uvs[rev_index][1]);
391 }
392 }
393 }
394 else {
395 for (int i = 0; i < uv_data.span.size(); ++i) {
396 uv_data.span[i] = float2(usd_uvs[i][0], usd_uvs[i][1]);
397 }
398 }
399 }
400 else {
401 /* Handle vertex interpolation. */
402 const Span<int> corner_verts = mesh->corner_verts();
403 BLI_assert(mesh->verts_num == usd_uvs.size());
404 for (int i = 0; i < uv_data.span.size(); ++i) {
405 /* Get the vertex index for this corner. */
406 int vi = corner_verts[i];
407 uv_data.span[i] = float2(usd_uvs[vi][0], usd_uvs[vi][1]);
408 }
409 }
410
411 uv_data.finish();
412}
413
414void USDMeshReader::read_subdiv()
415{
416 ModifierData *md = (ModifierData *)(object_->modifiers.last);
417 SubsurfModifierData *subdiv_data = reinterpret_cast<SubsurfModifierData *>(md);
418
419 pxr::TfToken uv_smooth;
420 mesh_prim_.GetFaceVaryingLinearInterpolationAttr().Get(&uv_smooth);
421
422 if (uv_smooth == pxr::UsdGeomTokens->all) {
423 subdiv_data->uv_smooth = SUBSURF_UV_SMOOTH_NONE;
424 }
425 else if (uv_smooth == pxr::UsdGeomTokens->cornersOnly) {
427 }
428 else if (uv_smooth == pxr::UsdGeomTokens->cornersPlus1) {
430 }
431 else if (uv_smooth == pxr::UsdGeomTokens->cornersPlus2) {
433 }
434 else if (uv_smooth == pxr::UsdGeomTokens->boundaries) {
436 }
437 else if (uv_smooth == pxr::UsdGeomTokens->none) {
438 subdiv_data->uv_smooth = SUBSURF_UV_SMOOTH_ALL;
439 }
440
441 pxr::TfToken boundary_smooth;
442 mesh_prim_.GetInterpolateBoundaryAttr().Get(&boundary_smooth);
443
444 if (boundary_smooth == pxr::UsdGeomTokens->edgeOnly) {
446 }
447 else if (boundary_smooth == pxr::UsdGeomTokens->edgeAndCorner) {
449 }
450}
451
452void USDMeshReader::read_vertex_creases(Mesh *mesh, const pxr::UsdTimeCode time)
453{
454 pxr::VtIntArray usd_corner_indices;
455 if (!mesh_prim_.GetCornerIndicesAttr().Get(&usd_corner_indices, time)) {
456 return;
457 }
458
459 pxr::VtFloatArray usd_corner_sharpnesses;
460 if (!mesh_prim_.GetCornerSharpnessesAttr().Get(&usd_corner_sharpnesses, time)) {
461 return;
462 }
463
464 /* Prevent the creation of the `crease_vert` attribute if we have no data. */
465 if (usd_corner_indices.empty() || usd_corner_sharpnesses.empty()) {
466 return;
467 }
468
469 /* It is fine to have fewer indices than vertices, but never the other way other. */
470 if (usd_corner_indices.size() > mesh->verts_num) {
471 CLOG_WARN(
472 &LOG, "Too many vertex creases for mesh %s", this->prim_path().GetAsString().c_str());
473 return;
474 }
475
476 if (usd_corner_indices.size() != usd_corner_sharpnesses.size()) {
477 CLOG_WARN(&LOG,
478 "Vertex crease and sharpness count mismatch for mesh %s",
479 this->prim_path().GetAsString().c_str());
480 return;
481 }
482
483 bke::MutableAttributeAccessor attributes = mesh->attributes_for_write();
484 bke::SpanAttributeWriter creases = attributes.lookup_or_add_for_write_only_span<float>(
485 "crease_vert", bke::AttrDomain::Point);
486 creases.span.fill(0.0f);
487
488 Span<int> corner_indices = Span(usd_corner_indices.cdata(), usd_corner_indices.size());
489 Span<float> corner_sharpnesses = Span(usd_corner_sharpnesses.cdata(),
490 usd_corner_sharpnesses.size());
491
492 for (size_t i = 0; i < corner_indices.size(); i++) {
493 const float crease = settings_->blender_stage_version_prior_44 ?
494 corner_sharpnesses[i] :
495 bke::subdiv::sharpness_to_crease(corner_sharpnesses[i]);
496 creases.span[corner_indices[i]] = std::clamp(crease, 0.0f, 1.0f);
497 }
498 creases.finish();
499}
500
501void USDMeshReader::read_edge_creases(Mesh *mesh, const pxr::UsdTimeCode time)
502{
503 pxr::VtArray<int> usd_crease_lengths;
504 pxr::VtArray<int> usd_crease_indices;
505 pxr::VtArray<float> usd_crease_sharpness;
506 mesh_prim_.GetCreaseLengthsAttr().Get(&usd_crease_lengths, time);
507 mesh_prim_.GetCreaseIndicesAttr().Get(&usd_crease_indices, time);
508 mesh_prim_.GetCreaseSharpnessesAttr().Get(&usd_crease_sharpness, time);
509
510 /* Prevent the creation of the `crease_edge` attribute if we have no data. */
511 if (usd_crease_lengths.empty() || usd_crease_indices.empty() || usd_crease_sharpness.empty()) {
512 return;
513 }
514
515 /* There should be as many sharpness values as lengths. */
516 if (usd_crease_lengths.size() != usd_crease_sharpness.size()) {
517 CLOG_WARN(&LOG,
518 "Edge crease and sharpness count mismatch for mesh %s",
519 this->prim_path().GetAsString().c_str());
520 return;
521 }
522
523 /* Build mapping from vert pairs to edge index. */
524 using EdgeMap = VectorSet<OrderedEdge,
525 16,
527 DefaultHash<OrderedEdge>,
528 DefaultEquality<OrderedEdge>,
529 SimpleVectorSetSlot<OrderedEdge, int>,
530 GuardedAllocator>;
531 Span<int2> edges = mesh->edges();
532 EdgeMap edge_map;
533 edge_map.reserve(edges.size());
534
535 for (const int i : edges.index_range()) {
536 edge_map.add(edges[i]);
537 }
538
539 bke::MutableAttributeAccessor attributes = mesh->attributes_for_write();
540 bke::SpanAttributeWriter creases = attributes.lookup_or_add_for_write_only_span<float>(
541 "crease_edge", bke::AttrDomain::Edge);
542 creases.span.fill(0.0f);
543
544 Span<int> crease_lengths = Span(usd_crease_lengths.cdata(), usd_crease_lengths.size());
545 Span<int> crease_indices = Span(usd_crease_indices.cdata(), usd_crease_indices.size());
546 Span<float> crease_sharpness = Span(usd_crease_sharpness.cdata(), usd_crease_sharpness.size());
547
548 size_t index_start = 0;
549 for (size_t i = 0; i < crease_lengths.size(); i++) {
550 const int length = crease_lengths[i];
551 if (length < 2) {
552 /* Since each crease must be at least one edge long, each element of this array must be at
553 * least two. If this is not the case it would not be safe to continue. */
554 CLOG_WARN(&LOG,
555 "Edge crease length %d is invalid for mesh %s",
556 length,
557 this->prim_path().GetAsString().c_str());
558 break;
559 }
560
561 if (index_start + length > crease_indices.size()) {
562 CLOG_WARN(&LOG,
563 "Edge crease lengths are out of bounds for mesh %s",
564 this->prim_path().GetAsString().c_str());
565 break;
566 }
567
568 float crease = settings_->blender_stage_version_prior_44 ?
569 crease_sharpness[i] :
570 bke::subdiv::sharpness_to_crease(crease_sharpness[i]);
571 crease = std::clamp(crease, 0.0f, 1.0f);
572 for (size_t j = 0; j < length - 1; j++) {
573 const int v1 = crease_indices[index_start + j];
574 const int v2 = crease_indices[index_start + j + 1];
575 const int edge_i = edge_map.index_of_try({v1, v2});
576 if (edge_i < 0) {
577 continue;
578 }
579
580 creases.span[edge_i] = crease;
581 }
582
583 index_start += length;
584 }
585
586 creases.finish();
587}
588
589void USDMeshReader::read_velocities(Mesh *mesh, const pxr::UsdTimeCode time)
590{
591 pxr::VtVec3fArray velocities;
592 mesh_prim_.GetVelocitiesAttr().Get(&velocities, time);
593
594 if (!velocities.empty()) {
595 bke::MutableAttributeAccessor attributes = mesh->attributes_for_write();
596 bke::SpanAttributeWriter<float3> velocity =
597 attributes.lookup_or_add_for_write_only_span<float3>("velocity", bke::AttrDomain::Point);
598
599 Span<pxr::GfVec3f> usd_data(velocities.cdata(), velocities.size());
600 velocity.span.copy_from(usd_data.cast<float3>());
601 velocity.finish();
602 }
603}
604
605void USDMeshReader::process_normals_vertex_varying(Mesh *mesh)
606{
607 if (normals_.empty()) {
608 return;
609 }
610
611 if (normals_.size() != mesh->verts_num) {
612 CLOG_WARN(&LOG,
613 "Vertex varying normals count mismatch for mesh '%s'",
614 this->prim_path().GetAsString().c_str());
615 return;
616 }
617
618 BLI_STATIC_ASSERT(sizeof(normals_[0]) == sizeof(float3), "Expected float3 normals size");
620 *mesh, {reinterpret_cast<float3 *>(normals_.data()), int64_t(normals_.size())});
621}
622
623void USDMeshReader::process_normals_face_varying(Mesh *mesh) const
624{
625 if (normals_.empty()) {
626 return;
627 }
628
629 /* Check for normals count mismatches to prevent crashes. */
630 if (normals_.size() != mesh->corners_num) {
631 CLOG_WARN(
632 &LOG, "Loop normal count mismatch for mesh '%s'", this->prim_path().GetAsString().c_str());
633 return;
634 }
635
636 Array<float3> corner_normals(mesh->corners_num);
637
638 const OffsetIndices faces = mesh->faces();
639 for (const int i : faces.index_range()) {
640 const IndexRange face = faces[i];
641 for (int j : face.index_range()) {
642 const int corner = face.start() + j;
643
644 int usd_index = face.start();
645 if (is_left_handed_) {
646 usd_index += face.size() - 1 - j;
647 }
648 else {
649 usd_index += j;
650 }
651
652 corner_normals[corner] = detail::convert_value<pxr::GfVec3f, float3>(normals_[usd_index]);
653 }
654 }
655
656 bke::mesh_set_custom_normals(*mesh, corner_normals);
657}
658
659void USDMeshReader::process_normals_uniform(Mesh *mesh) const
660{
661 if (normals_.empty()) {
662 return;
663 }
664
665 /* Check for normals count mismatches to prevent crashes. */
666 if (normals_.size() != mesh->faces_num) {
667 CLOG_WARN(&LOG,
668 "Uniform normal count mismatch for mesh '%s'",
669 this->prim_path().GetAsString().c_str());
670 return;
671 }
672
673 Array<float3> corner_normals(mesh->corners_num);
674
675 const OffsetIndices faces = mesh->faces();
676 for (const int i : faces.index_range()) {
677 for (const int corner : faces[i]) {
678 corner_normals[corner] = detail::convert_value<pxr::GfVec3f, float3>(normals_[i]);
679 }
680 }
681
682 bke::mesh_set_custom_normals(*mesh, corner_normals);
683}
684
685void USDMeshReader::read_mesh_sample(ImportSettings *settings,
686 Mesh *mesh,
687 const pxr::UsdTimeCode time,
688 const bool new_mesh)
689{
690 /* Note that for new meshes we always want to read verts and faces,
691 * regardless of the value of the read_flag, to avoid a crash downstream
692 * in code that expect this data to be there. */
693
694 if (new_mesh || (settings->read_flag & MOD_MESHSEQ_READ_VERT) != 0) {
695 MutableSpan<float3> vert_positions = mesh->vert_positions_for_write();
696 vert_positions.copy_from(Span(positions_.cdata(), positions_.size()).cast<float3>());
697 mesh->tag_positions_changed();
698
699 read_vertex_creases(mesh, time);
700 }
701
702 if (new_mesh || (settings->read_flag & MOD_MESHSEQ_READ_POLY) != 0) {
703 if (!read_faces(mesh)) {
704 return;
705 }
706 read_edge_creases(mesh, time);
707
708 if (normal_interpolation_ == pxr::UsdGeomTokens->faceVarying) {
709 process_normals_face_varying(mesh);
710 }
711 else if (normal_interpolation_ == pxr::UsdGeomTokens->uniform) {
712 process_normals_uniform(mesh);
713 }
714 }
715
716 /* Process point normals after reading faces. */
717 if ((settings->read_flag & MOD_MESHSEQ_READ_VERT) != 0 &&
718 normal_interpolation_ == pxr::UsdGeomTokens->vertex)
719 {
720 process_normals_vertex_varying(mesh);
721 }
722
723 /* Custom Data layers. */
724 if ((settings->read_flag & MOD_MESHSEQ_READ_VERT) ||
725 (settings->read_flag & MOD_MESHSEQ_READ_COLOR) ||
726 (settings->read_flag & MOD_MESHSEQ_READ_ATTRIBUTES))
727 {
728 read_velocities(mesh, time);
729 read_custom_data(settings, mesh, time, new_mesh);
730 }
731}
732
733void USDMeshReader::read_custom_data(const ImportSettings *settings,
734 Mesh *mesh,
735 const pxr::UsdTimeCode time,
736 const bool new_mesh)
737{
738 if (!(mesh && mesh->corners_num > 0)) {
739 return;
740 }
741
742 pxr::UsdGeomPrimvarsAPI pv_api = pxr::UsdGeomPrimvarsAPI(mesh_prim_);
743 std::vector<pxr::UsdGeomPrimvar> primvars = pv_api.GetPrimvarsWithValues();
744
745 pxr::TfToken active_color_name;
746 pxr::TfToken active_uv_set_name;
747
748 /* Convert primvars to custom layer data. */
749 for (const pxr::UsdGeomPrimvar &pv : primvars) {
750 const pxr::SdfValueTypeName type = pv.GetTypeName();
751 if (!type.IsArray()) {
752 continue; /* Skip non-array primvar attributes. */
753 }
754
755 const pxr::TfToken varying_type = pv.GetInterpolation();
756 const pxr::TfToken name = pxr::UsdGeomPrimvar::StripPrimvarsName(pv.GetPrimvarName());
757
758 /* To avoid unnecessarily reloading static primvars during animation,
759 * early out if not first load and this primvar isn't animated. */
760 if (!new_mesh && primvar_varying_map_.contains(name) && !primvar_varying_map_.lookup(name)) {
761 continue;
762 }
763
764 /* We handle the non-standard primvar:velocity elsewhere. */
765 if (ELEM(name, "velocity")) {
766 continue;
767 }
768
769 if (ELEM(type,
770 pxr::SdfValueTypeNames->StringArray,
771 pxr::SdfValueTypeNames->QuatdArray,
772 pxr::SdfValueTypeNames->QuathArray))
773 {
774 /* Skip creating known unsupported types, and avoid noisy error prints. */
775 continue;
776 }
777
778 /* Read Color primvars. */
780 if ((settings->read_flag & MOD_MESHSEQ_READ_COLOR) != 0) {
781 /* Set the active color name to 'displayColor', if a color primvar
782 * with this name exists. Otherwise, use the name of the first
783 * color primvar we find for the active color. */
784 if (active_color_name.IsEmpty() || name == usdtokens::displayColor) {
785 active_color_name = name;
786 }
787
788 read_generic_mesh_primvar(mesh, pv, time, is_left_handed_);
789 }
790 }
791
792 /* Read UV primvars. */
793 else if (ELEM(varying_type,
794 pxr::UsdGeomTokens->vertex,
795 pxr::UsdGeomTokens->faceVarying,
796 pxr::UsdGeomTokens->varying) &&
798 {
799 if ((settings->read_flag & MOD_MESHSEQ_READ_UV) != 0) {
800 /* Set the active uv set name to 'st', if a uv set primvar
801 * with this name exists. Otherwise, use the name of the first
802 * uv set primvar we find for the active uv set. */
803 if (active_uv_set_name.IsEmpty() || name == usdtokens::st) {
804 active_uv_set_name = name;
805 }
806 this->read_uv_data_primvar(mesh, pv, time);
807 }
808 }
809
810 /* Read all other primvars. */
811 else {
812 if ((settings->read_flag & MOD_MESHSEQ_READ_ATTRIBUTES) != 0) {
813 read_generic_mesh_primvar(mesh, pv, time, is_left_handed_);
814 }
815 }
816
817 /* Record whether the primvar attribute might be time varying. */
818 if (!primvar_varying_map_.contains(name)) {
819 bool might_be_time_varying = pv.ValueMightBeTimeVarying();
820 primvar_varying_map_.add(name, might_be_time_varying);
821 if (might_be_time_varying) {
822 is_time_varying_ = true;
823 }
824 }
825 } /* End primvar attribute loop. */
826
827 if (!active_color_name.IsEmpty()) {
828 BKE_id_attributes_default_color_set(&mesh->id, active_color_name.GetText());
829 BKE_id_attributes_active_color_set(&mesh->id, active_color_name.GetText());
830 }
831
832 if (!active_uv_set_name.IsEmpty()) {
833 int layer_index = CustomData_get_named_layer_index(
834 &mesh->corner_data, CD_PROP_FLOAT2, active_uv_set_name.GetText());
835 if (layer_index > -1) {
838 }
839 }
840}
841
842void USDMeshReader::assign_facesets_to_material_indices(pxr::UsdTimeCode time,
843 MutableSpan<int> material_indices,
844 blender::Map<pxr::SdfPath, int> *r_mat_map)
845{
846 if (r_mat_map == nullptr) {
847 return;
848 }
849
850 /* Find the geom subsets that have bound materials.
851 * We don't call #pxr::UsdShadeMaterialBindingAPI::GetMaterialBindSubsets()
852 * because this function returns only those subsets that are in the 'materialBind'
853 * family, but, in practice, applications (like Houdini) might export subsets
854 * in different families that are bound to materials.
855 * TODO(makowalski): Reassess if the above is the best approach. */
856 const std::vector<pxr::UsdGeomSubset> subsets = pxr::UsdGeomSubset::GetAllGeomSubsets(
857 mesh_prim_);
858
859 int current_mat = 0;
860 if (!subsets.empty()) {
861 for (const pxr::UsdGeomSubset &subset : subsets) {
862 pxr::UsdPrim subset_prim = subset.GetPrim();
863 pxr::UsdShadeMaterial subset_mtl = utils::compute_bound_material(subset_prim,
864 import_params_.mtl_purpose);
865 if (!subset_mtl) {
866 continue;
867 }
868
869 pxr::SdfPath subset_mtl_path = subset_mtl.GetPath();
870 if (subset_mtl_path.IsEmpty()) {
871 continue;
872 }
873
874 pxr::TfToken element_type;
875 subset.GetElementTypeAttr().Get(&element_type, time);
876 if (element_type != pxr::UsdGeomTokens->face) {
877 CLOG_WARN(&LOG,
878 "UsdGeomSubset '%s' uses unsupported elementType: %s",
879 subset_prim.GetName().GetText(),
880 element_type.GetText());
881 continue;
882 }
883
884 const int mat_idx = r_mat_map->lookup_or_add(subset_mtl_path, 1 + current_mat++);
885 const int max_element_idx = std::max(0, int(material_indices.size() - 1));
886
887 pxr::VtIntArray indices;
888 subset.GetIndicesAttr().Get(&indices, time);
889
890 int bad_element_count = 0;
891 for (const int element_idx : indices.AsConst()) {
892 const int safe_element_idx = std::clamp(element_idx, 0, max_element_idx);
893 bad_element_count += (safe_element_idx != element_idx) ? 1 : 0;
894 material_indices[safe_element_idx] = mat_idx - 1;
895 }
896
897 if (bad_element_count > 0) {
898 CLOG_WARN(&LOG,
899 "UsdGeomSubset '%s' contains invalid indices; material assignment may be "
900 "incorrect (%d were out of range)",
901 subset_prim.GetName().GetText(),
902 bad_element_count);
903 }
904 }
905 }
906
907 if (r_mat_map->is_empty()) {
908 pxr::UsdShadeMaterial mtl = utils::compute_bound_material(prim_, import_params_.mtl_purpose);
909 if (mtl) {
910 pxr::SdfPath mtl_path = mtl.GetPath();
911
912 if (!mtl_path.IsEmpty()) {
913 r_mat_map->add(mtl.GetPath(), 1);
914 }
915 }
916 }
917}
918
919void USDMeshReader::readFaceSetsSample(Main *bmain, Mesh *mesh, const pxr::UsdTimeCode time)
920{
921 if (!import_params_.import_materials) {
922 return;
923 }
924
925 blender::Map<pxr::SdfPath, int> mat_map;
926
927 bke::MutableAttributeAccessor attributes = mesh->attributes_for_write();
928 bke::SpanAttributeWriter<int> material_indices = attributes.lookup_or_add_for_write_span<int>(
929 "material_index", bke::AttrDomain::Face);
930 this->assign_facesets_to_material_indices(time, material_indices.span, &mat_map);
931 material_indices.finish();
932 /* Build material name map if it's not built yet. */
933 if (this->settings_->mat_name_to_mat.is_empty()) {
934 build_material_map(bmain, this->settings_->mat_name_to_mat);
935 }
936 utils::assign_materials(
937 bmain, object_, mat_map, this->import_params_, this->prim_.GetStage(), *this->settings_);
938}
939
940Mesh *USDMeshReader::read_mesh(Mesh *existing_mesh,
941 const USDMeshReadParams params,
942 const char ** /*r_err_str*/)
943{
944 mesh_prim_.GetOrientationAttr().Get(&orientation_);
945 if (orientation_ == pxr::UsdGeomTokens->leftHanded) {
946 is_left_handed_ = true;
947 }
948
949 Mesh *active_mesh = existing_mesh;
950 bool new_mesh = false;
951
952 /* TODO(makowalski): implement the optimization of only updating the mesh points when
953 * the topology is consistent, as in the Alembic importer. */
954
955 ImportSettings settings;
956 settings.read_flag |= params.read_flags;
957
958 if (topology_changed(existing_mesh, params.motion_sample_time)) {
959 new_mesh = true;
961 existing_mesh, positions_.size(), 0, face_counts_.size(), face_indices_.size());
962 }
963
964 read_mesh_sample(
965 &settings, active_mesh, params.motion_sample_time, new_mesh || is_initial_load_);
966
967 if (new_mesh) {
968 /* Here we assume that the number of materials doesn't change, i.e. that
969 * the material slots that were created when the object was loaded from
970 * USD are still valid now. */
971 if (active_mesh->faces_num != 0 && import_params_.import_materials) {
972 blender::Map<pxr::SdfPath, int> mat_map;
973 bke::MutableAttributeAccessor attributes = active_mesh->attributes_for_write();
974 bke::SpanAttributeWriter<int> material_indices =
975 attributes.lookup_or_add_for_write_span<int>("material_index", bke::AttrDomain::Face);
976 assign_facesets_to_material_indices(
977 params.motion_sample_time, material_indices.span, &mat_map);
978 material_indices.finish();
979 }
980 }
981
982 if (import_params_.validate_meshes) {
983 if (BKE_mesh_validate(active_mesh, false, false)) {
984 BKE_reportf(reports(), RPT_INFO, "Fixed mesh for prim: %s", mesh_prim_.GetPath().GetText());
985 }
986 }
987
988 return active_mesh;
989}
990
993 const char **r_err_str)
994{
995 Mesh *existing_mesh = geometry_set.get_mesh_for_write();
996 Mesh *new_mesh = read_mesh(existing_mesh, params, r_err_str);
997
998 if (new_mesh != existing_mesh) {
999 geometry_set.replace_mesh(new_mesh);
1000 }
1001}
1002
1004{
1005 /* Make sure we can apply UsdSkelBindingAPI to the prim.
1006 * Attempting to apply the API to instance proxies generates
1007 * a USD error. */
1008 if (!prim_ || prim_.IsInstanceProxy()) {
1009 return {};
1010 }
1011
1012 pxr::UsdSkelBindingAPI skel_api(prim_);
1013
1014 if (pxr::UsdSkelSkeleton skel = skel_api.GetInheritedSkeleton()) {
1015 return skel.GetPath();
1016 }
1017
1018 return {};
1019}
1020
1021std::optional<XformResult> USDMeshReader::get_local_usd_xform(const pxr::UsdTimeCode time) const
1022{
1023 if (!import_params_.import_skeletons || prim_.IsInstanceProxy()) {
1024 /* Use the standard transform computation, since we are ignoring
1025 * skinning data. Note that applying the UsdSkelBinding API to an
1026 * instance proxy generates a USD error. */
1028 }
1029
1030 pxr::UsdSkelBindingAPI skel_api = pxr::UsdSkelBindingAPI(prim_);
1031 if (pxr::UsdAttribute xf_attr = skel_api.GetGeomBindTransformAttr()) {
1032 if (xf_attr.HasAuthoredValue()) {
1033 pxr::GfMatrix4d bind_xf;
1034 if (skel_api.GetGeomBindTransformAttr().Get(&bind_xf)) {
1035 /* The USD bind transform is a matrix of doubles,
1036 * but we cast it to GfMatrix4f because Blender expects
1037 * a matrix of floats. Also, we assume the transform
1038 * is constant over time. */
1039 return XformResult(pxr::GfMatrix4f(bind_xf), true);
1040 }
1041
1042 BKE_reportf(reports(),
1044 "%s: Couldn't compute geom bind transform for %s",
1045 __func__,
1046 prim_.GetPath().GetAsString().c_str());
1047 }
1048 }
1049
1050 return USDXformReader::get_local_usd_xform(time);
1051}
1052
1053} // namespace blender::io::usd
void BKE_id_attributes_default_color_set(struct ID *id, std::optional< blender::StringRef > name)
void BKE_id_attributes_active_color_set(struct ID *id, std::optional< blender::StringRef > name)
Definition attribute.cc:985
CustomData interface, see also DNA_customdata_types.h.
void CustomData_set_layer_render_index(CustomData *data, eCustomDataType type, int n)
int CustomData_get_named_layer_index(const CustomData *data, eCustomDataType type, blender::StringRef name)
void CustomData_set_layer_active_index(CustomData *data, eCustomDataType type, int n)
General operations, lookup, etc. for materials.
void BKE_object_material_assign_single_obdata(Main *bmain, Object *ob, Material *ma, short act)
Mesh * BKE_mesh_new_nomain_from_template(const Mesh *me_src, int verts_num, int edges_num, int faces_num, int corners_num)
bool BKE_mesh_validate(Mesh *mesh, bool do_verbose, bool cddata_check_mask)
Mesh * BKE_mesh_add(Main *bmain, const char *name)
void BKE_mesh_nomain_to_mesh(Mesh *mesh_src, Mesh *mesh_dst, Object *ob, bool process_shape_keys=true)
General operations, lookup, etc. for blender objects.
Object * BKE_object_add_only_object(Main *bmain, int type, const char *name) ATTR_RETURNS_NONNULL
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
@ RPT_INFO
Definition BKE_report.hh:35
@ RPT_WARNING
Definition BKE_report.hh:38
#define BLI_STATIC_ASSERT(a, msg)
Definition BLI_assert.h:83
#define BLI_assert(a)
Definition BLI_assert.h:46
#define ELEM(...)
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
@ CD_PROP_FLOAT2
#define MAXMAT
struct Mesh Mesh
@ SUBSURF_BOUNDARY_SMOOTH_ALL
@ SUBSURF_BOUNDARY_SMOOTH_PRESERVE_CORNERS
struct ModifierData ModifierData
@ MOD_MESHSEQ_READ_COLOR
@ MOD_MESHSEQ_READ_VERT
@ MOD_MESHSEQ_READ_ATTRIBUTES
@ MOD_MESHSEQ_READ_UV
@ MOD_MESHSEQ_READ_POLY
struct SubsurfModifierData SubsurfModifierData
@ SUBSURF_UV_SMOOTH_PRESERVE_CORNERS_AND_JUNCTIONS
@ SUBSURF_UV_SMOOTH_ALL
@ SUBSURF_UV_SMOOTH_PRESERVE_CORNERS
@ SUBSURF_UV_SMOOTH_NONE
@ SUBSURF_UV_SMOOTH_PRESERVE_BOUNDARIES
@ SUBSURF_UV_SMOOTH_PRESERVE_CORNERS_JUNCTIONS_AND_CONCAVE
Object is a sort of wrapper for general info.
@ OB_MESH
ATTR_WARN_UNUSED_RESULT const BMVert * v2
long long int int64_t
SIMD_FORCE_INLINE btScalar length() const
Return the length of the vector.
Definition btVector3.h:257
constexpr int64_t last(const int64_t n=0) const
constexpr int64_t size() const
constexpr int64_t start() const
constexpr IndexRange index_range() const
void add_new(const Key &key, const Value &value)
Definition BLI_map.hh:265
constexpr int64_t size() const
Definition BLI_span.hh:493
constexpr void copy_from(Span< T > values) const
Definition BLI_span.hh:739
constexpr int64_t size() const
Definition BLI_span.hh:252
constexpr IndexRange index_range() const
Definition BLI_span.hh:401
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
int64_t size() const
Definition BLI_map.hh:976
bool is_empty() const
Definition BLI_map.hh:986
ItemIterator items() const &
Definition BLI_map.hh:902
Value & lookup_or_add(const Key &key, const Value &value)
Definition BLI_map.hh:588
bool contains(const Key &key) const
Definition BLI_set.hh:310
Material * add_material(const pxr::UsdShadeMaterial &usd_material, bool read_usd_preview=true) const
bool topology_changed(const Mesh *existing_mesh, pxr::UsdTimeCode time) override
pxr::SdfPath get_skeleton_path() const
void read_geometry(bke::GeometrySet &geometry_set, USDMeshReadParams params, const char **r_err_str) override
void create_object(Main *bmain) override
void read_object_data(Main *bmain, pxr::UsdTimeCode time) override
const USDImportParams & import_params_
void read_object_data(Main *bmain, pxr::UsdTimeCode time) override
virtual std::optional< XformResult > get_local_usd_xform(pxr::UsdTimeCode time) const
static ushort indices[]
bool all(VecOp< bool, D >) RET
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
#define LOG(level)
Definition log.h:97
static char faces[256]
VectorSet< OrderedEdge, 16, DefaultProbingStrategy, DefaultHash< OrderedEdge >, DefaultEquality< OrderedEdge >, SimpleVectorSetSlot< OrderedEdge, int >, GuardedAllocator > EdgeMap
BLI_INLINE float sharpness_to_crease(float sharpness)
void mesh_calc_edges(Mesh &mesh, bool keep_existing_edges, bool select_new_edges)
void mesh_set_custom_normals_from_verts(Mesh &mesh, MutableSpan< float3 > vert_normals)
void mesh_set_custom_normals(Mesh &mesh, MutableSpan< float3 > corner_normals)
void read_custom_data(const std::string &iobject_full_name, const ICompoundProperty &prop, const CDStreamConfig &config, const Alembic::Abc::ISampleSelector &iss)
static pxr::UsdShadeMaterial compute_bound_material(const pxr::UsdPrim &prim, eUSDMtlPurpose mtl_purpose)
static void assign_materials(Main *bmain, Object *ob, const blender::Map< pxr::SdfPath, int > &mat_index_map, const USDImportParams &params, pxr::UsdStageRefPtr stage, const ImportSettings &settings)
void import_mesh_skel_bindings(Object *mesh_obj, const pxr::UsdPrim &prim, ReportList *reports)
void build_material_map(const Main *bmain, blender::Map< std::string, Material * > &r_mat_map)
Material * find_existing_material(const pxr::SdfPath &usd_mat_path, const USDImportParams &params, const blender::Map< std::string, Material * > &mat_map, const blender::Map< pxr::SdfPath, Material * > &usd_path_to_mat)
USDMeshReadParams create_mesh_read_params(const double motion_sample_time, const int read_flags)
@ USD_MTL_PURPOSE_FULL
Definition usd.hh:46
@ USD_MTL_PURPOSE_ALL
Definition usd.hh:44
@ USD_MTL_PURPOSE_PREVIEW
Definition usd.hh:45
void import_blendshapes(Main *bmain, Object *mesh_obj, const pxr::UsdPrim &prim, ReportList *reports, const bool import_anim)
std::optional< bke::AttrType > convert_usd_type_to_blender(const pxr::SdfValueTypeName usd_type)
@ USD_MTL_NAME_COLLISION_MAKE_UNIQUE
Definition usd.hh:36
void read_generic_mesh_primvar(Mesh *mesh, const pxr::UsdGeomPrimvar &primvar, const pxr::UsdTimeCode time, const bool is_left_handed)
Value parallel_reduce(IndexRange range, int64_t grain_size, const Value &identity, const Function &function, const Reduction &reduction)
Definition BLI_task.hh:151
VecBase< float, 2 > float2
PythonProbingStrategy<> DefaultProbingStrategy
VecBase< float, 3 > float3
static const pxr::TfToken st("st", pxr::TfToken::Immortal)
static const pxr::TfToken normalsPrimvar("normals", pxr::TfToken::Immortal)
const pxr::TfToken displayColor("displayColor", pxr::TfToken::Immortal)
const char * name
char name[258]
Definition DNA_ID.h:432
int corners_num
CustomData corner_data
int faces_num
int verts_num
void replace_mesh(Mesh *mesh, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
blender::Map< std::string, Material * > mat_name_to_mat
blender::Set< pxr::SdfPath > mat_import_hook_sources
blender::Map< pxr::SdfPath, Material * > usd_path_to_mat_for_hook
blender::Map< pxr::SdfPath, Material * > usd_path_to_mat
i
Definition text_draw.cc:230
#define N_(msgid)