Blender V5.3
usd_reader_stage.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2021 Tangent Animation and. NVIDIA Corporation. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "usd_reader_stage.hh"
6
7#include "usd_hook.hh"
9#include "usd_reader_curve.hh"
11#include "usd_reader_light.hh"
13#include "usd_reader_mesh.hh"
14#include "usd_reader_nurbs.hh"
17#include "usd_reader_points.hh"
18#include "usd_reader_prim.hh"
19#include "usd_reader_shape.hh"
21#include "usd_reader_volume.hh"
22#include "usd_reader_xform.hh"
23
24#include <pxr/usd/usd/primRange.h>
25#include <pxr/usd/usdGeom/camera.h>
26#include <pxr/usd/usdGeom/capsule.h>
27#include <pxr/usd/usdGeom/capsule_1.h>
28#include <pxr/usd/usdGeom/cone.h>
29#include <pxr/usd/usdGeom/cube.h>
30#include <pxr/usd/usdGeom/cylinder.h>
31#include <pxr/usd/usdGeom/cylinder_1.h>
32#include <pxr/usd/usdGeom/mesh.h>
33#include <pxr/usd/usdGeom/metrics.h>
34#include <pxr/usd/usdGeom/nurbsCurves.h>
35#include <pxr/usd/usdGeom/plane.h>
36#include <pxr/usd/usdGeom/pointInstancer.h>
37#include <pxr/usd/usdGeom/points.h>
38#include <pxr/usd/usdGeom/scope.h>
39#include <pxr/usd/usdGeom/sphere.h>
40#include <pxr/usd/usdGeom/tokens.h>
41#include <pxr/usd/usdGeom/xform.h>
42#include <pxr/usd/usdLux/boundableLightBase.h>
43#include <pxr/usd/usdLux/domeLight.h>
44#include <pxr/usd/usdLux/domeLight_1.h>
45#include <pxr/usd/usdLux/nonboundableLightBase.h>
46#include <pxr/usd/usdShade/material.h>
47
48#include "BLI_map.hh"
49#include "BLI_math_base_c.hh"
51#include "BLI_math_matrix.hh"
52#include "BLI_math_matrix_c.hh"
54#include "BLI_sort.hh"
55#include "BLI_string.hh"
56
57#include "BKE_collection.hh"
58#include "BKE_lib_id.hh"
59#include "BKE_modifier.hh"
60#include "BKE_object.hh"
61#include "BKE_report.hh"
62
63#include "CLG_log.h"
64
66#include "DNA_material_types.h"
67#include "DNA_object_types.h"
68
69#include "WM_types.hh"
70
71#include <fmt/core.h>
72#include <fmt/format.h>
73
74namespace blender {
75
76static CLG_LogRef LOG = {"io.usd"};
77
78namespace io::usd {
79
80static void decref(USDPrimReader *reader)
81{
82 reader->decref();
83
84 if (reader->refcount() == 0) {
85 delete reader;
86 }
87}
88
92static Collection *create_collection(Main *bmain, Collection *parent, const char *name)
93{
94 if (!bmain) {
95 return nullptr;
96 }
97
98 return BKE_collection_add(bmain, parent, name);
99}
100
106static void set_instance_collection(USDInstanceReader *instance_reader,
107 const Map<pxr::SdfPath, Collection *> &proto_collection_map)
108{
109 if (!instance_reader) {
110 return;
111 }
112
113 pxr::SdfPath proto_path = instance_reader->proto_path();
114
115 Collection *collection = proto_collection_map.lookup_default(proto_path, nullptr);
116 if (collection != nullptr) {
117 instance_reader->set_instance_collection(collection);
118 }
119 else {
120 CLOG_WARN(&LOG,
121 "Couldn't find prototype collection for %s",
122 instance_reader->prim_path().GetAsString().c_str());
123 }
124}
125
126/* Update the given import settings with the global rotation matrix to orient
127 * imported objects with Z-up, if necessary */
128static void convert_to_z_up(pxr::UsdStageRefPtr stage, ImportSettings &settings)
129{
130 if (!stage || pxr::UsdGeomGetStageUpAxis(stage) == pxr::UsdGeomTokens->z) {
131 return;
132 }
133
134 settings.do_convert_mat = true;
135
136 /* Rotate 90 degrees about the X-axis. */
138}
139
144static void find_prefix_to_skip(pxr::UsdStageRefPtr stage, ImportSettings &settings)
145{
146 if (!stage) {
147 return;
148 }
149
150 pxr::TfToken generated_key("Blender:generated");
151 pxr::SdfPath path("/");
152 auto prim = stage->GetPseudoRoot();
153 while (true) {
154
155 uint32_t child_count = 0;
156 for (auto child : prim.GetChildren()) {
157 if (child_count == 0) {
158 prim = child.GetPrim();
159 }
160 ++child_count;
161 }
162
163 if (child_count != 1) {
164 /* Our blender write out only supports a single root chain,
165 * so whenever we encounter more than one child, we should
166 * early exit */
167 break;
168 }
169
170 /* We only care about prims that have the key and the value doesn't matter */
171 if (!prim.HasCustomDataKey(generated_key)) {
172 break;
173 }
174 path = path.AppendChild(prim.GetName());
175 }
176
177 /* Treat the root as empty */
178 if (path == pxr::SdfPath("/")) {
179 path = pxr::SdfPath();
180 }
181
182 settings.skip_prefix = path;
183}
184
188static void determine_blender_compat(pxr::UsdStageRefPtr stage, ImportSettings &settings)
189{
190 const std::string doc = stage->GetRootLayer()->GetDocumentation();
191
192 /* Was the incoming Stage written by Blender? If so, set some broad compatibility flags. */
193 if (doc.starts_with("Blender v")) {
194 /* Set flag if the Blender Stage was from before version 4.4. */
195 settings.blender_stage_version_prior_44 = doc < "Blender v4.4";
196 }
197}
198
200 const USDImportParams &params,
201 const std::function<CacheFile *()> &get_cache_file_fn)
203{
207 settings_.get_cache_file = get_cache_file_fn;
208 settings_.stage_meters_per_unit = pxr::UsdGeomGetStageMetersPerUnit(stage);
212 }
213}
214
219
221{
222 return stage_;
223}
224
225bool USDStageReader::is_primitive_prim(const pxr::UsdPrim &prim) const
226{
227 return (prim.IsA<pxr::UsdGeomCapsule>() || prim.IsA<pxr::UsdGeomCapsule_1>() ||
228 prim.IsA<pxr::UsdGeomCylinder>() || prim.IsA<pxr::UsdGeomCylinder_1>() ||
229 prim.IsA<pxr::UsdGeomCone>() || prim.IsA<pxr::UsdGeomCube>() ||
230 prim.IsA<pxr::UsdGeomSphere>() || prim.IsA<pxr::UsdGeomPlane>());
231}
232
237
239{
240 if (params_.support_scene_instancing && prim.IsInstance()) {
241 return new USDInstanceReader(prim, params_, settings_);
242 }
243 if (params_.import_shapes && is_primitive_prim(prim)) {
244 return new USDShapeReader(prim, params_, settings_);
245 }
246 if (prim.IsA<pxr::UsdGeomPointInstancer>()) {
247 return new USDPointInstancerReader(prim, params_, settings_);
248 }
249 if (params_.import_cameras && prim.IsA<pxr::UsdGeomCamera>()) {
250 return new USDCameraReader(prim, params_, settings_);
251 }
252 if (params_.import_curves && prim.IsA<pxr::UsdGeomBasisCurves>()) {
253 return new USDBasisCurvesReader(prim, params_, settings_);
254 }
255 if (params_.import_curves && prim.IsA<pxr::UsdGeomNurbsCurves>()) {
256 return new USDNurbsReader(prim, params_, settings_);
257 }
258 if (params_.import_meshes && prim.IsA<pxr::UsdGeomMesh>()) {
259 return new USDMeshReader(prim, params_, settings_);
260 }
262 (prim.IsA<pxr::UsdLuxDomeLight>() || prim.IsA<pxr::UsdLuxDomeLight_1>()))
263 {
264 /* Dome lights are handled elsewhere. */
265 return nullptr;
266 }
268 (prim.IsA<pxr::UsdLuxBoundableLightBase>() || prim.IsA<pxr::UsdLuxNonboundableLightBase>()))
269 {
270 return new USDLightReader(prim, params_, settings_);
271 }
272 if (params_.import_volumes && prim.IsA<pxr::UsdVolVolume>()) {
273 return new USDVolumeReader(prim, params_, settings_);
274 }
275 if (prim.IsA<pxr::UsdVolParticleField3DGaussianSplat>()) {
276 return new USDParticleFieldReader(prim, params_, settings_);
277 }
278 if (params_.import_skeletons && prim.IsA<pxr::UsdSkelSkeleton>()) {
279 return new USDSkeletonReader(prim, params_, settings_);
280 }
281 if (params_.import_points && prim.IsA<pxr::UsdGeomPoints>()) {
282 return new USDPointsReader(prim, params_, settings_);
283 }
284 if (prim.IsA<pxr::UsdGeomImageable>()) {
285 return new USDXformReader(prim, params_, settings_);
286 }
287
288 return nullptr;
289}
290
292{
293 if (params_.support_scene_instancing && prim.IsInstance()) {
294 return new USDInstanceReader(prim, params_, settings_);
295 }
296 if (is_primitive_prim(prim)) {
297 return new USDShapeReader(prim, params_, settings_);
298 }
299 if (prim.IsA<pxr::UsdGeomCamera>()) {
300 return new USDCameraReader(prim, params_, settings_);
301 }
302 if (prim.IsA<pxr::UsdGeomBasisCurves>()) {
303 return new USDBasisCurvesReader(prim, params_, settings_);
304 }
305 if (prim.IsA<pxr::UsdGeomNurbsCurves>()) {
306 return new USDNurbsReader(prim, params_, settings_);
307 }
308 if (prim.IsA<pxr::UsdGeomMesh>()) {
309 return new USDMeshReader(prim, params_, settings_);
310 }
311 if (prim.IsA<pxr::UsdLuxDomeLight>() || prim.IsA<pxr::UsdLuxDomeLight_1>()) {
312 /* We don't handle dome lights. */
313 return nullptr;
314 }
315 if (prim.IsA<pxr::UsdLuxBoundableLightBase>() || prim.IsA<pxr::UsdLuxNonboundableLightBase>()) {
316 return new USDLightReader(prim, params_, settings_);
317 }
318 if (prim.IsA<pxr::UsdVolVolume>()) {
319 return new USDVolumeReader(prim, params_, settings_);
320 }
321 if (prim.IsA<pxr::UsdVolParticleField3DGaussianSplat>()) {
322 return new USDParticleFieldReader(prim, params_, settings_);
323 }
324 if (prim.IsA<pxr::UsdSkelSkeleton>()) {
325 return new USDSkeletonReader(prim, params_, settings_);
326 }
327 if (prim.IsA<pxr::UsdGeomPoints>()) {
328 return new USDPointsReader(prim, params_, settings_);
329 }
330 if (prim.IsA<pxr::UsdGeomPointInstancer>()) {
331 return new USDPointInstancerReader(prim, params_, settings_);
332 }
333 if (prim.IsA<pxr::UsdGeomImageable>()) {
334 return new USDXformReader(prim, params_, settings_);
335 }
336 return nullptr;
337}
338
339bool USDStageReader::include_by_visibility(const pxr::UsdGeomImageable &imageable) const
340{
342 /* Invisible prims are allowed. */
343 return true;
344 }
345
346 pxr::UsdAttribute visibility_attr = imageable.GetVisibilityAttr();
347
348 if (!visibility_attr) {
349 /* No visibility attribute, so allow. */
350 return true;
351 }
352
353 /* Include if the prim has an animating visibility attribute or is not invisible. */
354
355 if (visibility_attr.ValueMightBeTimeVarying()) {
356 return true;
357 }
358
359 pxr::TfToken visibility;
360 visibility_attr.Get(&visibility);
361 return visibility != pxr::UsdGeomTokens->invisible;
362}
363
364bool USDStageReader::include_by_purpose(const pxr::UsdGeomImageable &imageable) const
365{
366 if (params_.import_skeletons && imageable.GetPrim().IsA<pxr::UsdSkelSkeleton>()) {
367 /* Always include skeletons, if requested by the user, regardless of purpose. */
368 return true;
369 }
370
372 /* The options allow any purpose, so we trivially include the prim. */
373 return true;
374 }
375
376 pxr::UsdAttribute purpose_attr = imageable.GetPurposeAttr();
377
378 if (!purpose_attr) {
379 /* No purpose attribute, so trivially include the prim. */
380 return true;
381 }
382
383 pxr::TfToken purpose;
384 purpose_attr.Get(&purpose);
385
386 if (purpose == pxr::UsdGeomTokens->guide) {
387 return params_.import_guide;
388 }
389 if (purpose == pxr::UsdGeomTokens->proxy) {
390 return params_.import_proxy;
391 }
392 if (purpose == pxr::UsdGeomTokens->render) {
393 return params_.import_render;
394 }
395
396 return true;
397}
398
399bool USDStageReader::merge_with_parent(USDPrimReader *reader) const
400{
401 /* Don't merge if the param is set to false */
403 return false;
404 }
405
406 USDXformReader *xform_reader = dynamic_cast<USDXformReader *>(reader);
407
408 if (!xform_reader) {
409 return false;
410 }
411
412 /* Check if the Xform reader is already merged. */
413 if (xform_reader->use_parent_xform()) {
414 return false;
415 }
416
417 /* Only merge if the parent is an Xform. */
418 if (!xform_reader->prim().GetParent().IsA<pxr::UsdGeomXform>()) {
419 return false;
420 }
421
422 /* Don't merge Xform and Scope prims. */
423 if (xform_reader->prim().IsA<pxr::UsdGeomXform>() ||
424 xform_reader->prim().IsA<pxr::UsdGeomScope>())
425 {
426 return false;
427 }
428
429 /* Don't merge if the prim has authored transform ops. */
430 if (xform_reader->prim_has_xform_ops()) {
431 return false;
432 }
433
434 /* Flag the Xform reader as merged. */
435 xform_reader->set_use_parent_xform(true);
436
437 return true;
438}
439
440USDPrimReader *USDStageReader::collect_readers(const pxr::UsdPrim &prim,
441 const UsdPathSet &pruned_prims,
442 const bool defined_prims_only,
443 Vector<USDPrimReader *> &r_readers)
444{
445 if (prim.IsA<pxr::UsdGeomImageable>()) {
446 pxr::UsdGeomImageable imageable(prim);
447
448 if (!include_by_purpose(imageable)) {
449 return nullptr;
450 }
451
452 if (!include_by_visibility(imageable)) {
453 return nullptr;
454 }
455 }
456
457 if (prim.IsA<pxr::UsdLuxDomeLight>() || prim.IsA<pxr::UsdLuxDomeLight_1>()) {
458 USDDomeLightReader *reader = new USDDomeLightReader(prim, params_, settings_);
459 reader->incref();
460 dome_light_readers_.append(reader);
461 }
462
463 pxr::Usd_PrimFlagsConjunction filter_flags = pxr::UsdPrimIsActive && pxr::UsdPrimIsLoaded &&
464 !pxr::UsdPrimIsAbstract;
465
466 if (defined_prims_only) {
467 filter_flags &= pxr::UsdPrimIsDefined;
468 }
469
470 pxr::Usd_PrimFlagsPredicate filter_predicate(filter_flags);
472 filter_predicate = pxr::UsdTraverseInstanceProxies(filter_predicate);
473 }
474
475 Vector<USDPrimReader *> child_readers;
476
477 pxr::UsdPrimSiblingRange children = prim.GetFilteredChildren(filter_predicate);
478
479 for (const auto &child_prim : children) {
480 if (pruned_prims.contains(child_prim.GetPath())) {
481 continue;
482 }
483 if (USDPrimReader *child_reader = collect_readers(
484 child_prim, pruned_prims, defined_prims_only, r_readers))
485 {
486 child_readers.append(child_reader);
487 }
488 }
489
490 if (prim.IsPseudoRoot()) {
491 return nullptr;
492 }
493
494 /* If we find prims that have been auto generated by Blender, we skip them on import
495 * so that the imported scene can closely match the exported scene */
496 if (!settings_.skip_prefix.IsEmpty()) {
497 if (settings_.skip_prefix.HasPrefix(prim.GetPath())) {
498 return nullptr;
499 }
500 }
501
502 /* Check if we can merge an Xform with its child prim. */
503 if (child_readers.size() == 1) {
504
505 USDPrimReader *child_reader = child_readers.first();
506
507 if (merge_with_parent(child_reader)) {
508 return child_reader;
509 }
510 }
511
512 if (prim.IsA<pxr::UsdShadeMaterial>()) {
513 /* Record material path for later processing, if needed,
514 * e.g., when importing all materials. */
515 material_paths_.append(prim.GetPath());
516
517 /* We don't create readers for materials, so return early. */
518 return nullptr;
519 }
520
521 USDPrimReader *reader = create_reader_if_allowed(prim);
522
523 if (!reader) {
524 return nullptr;
525 }
526 if (!reader->valid()) {
527 return nullptr;
528 }
529
530 r_readers.append(reader);
531 reader->incref();
532
533 /* Set each child reader's parent. */
534 for (USDPrimReader *child_reader : child_readers) {
535 child_reader->parent(reader);
536 }
537
538 return reader;
539}
540
542{
543 if (!valid()) {
544 return;
545 }
546
548
549 /* Identify paths to point instancer prototypes, as these will be converted
550 * in a separate pass over the stage. */
551 UsdPathSet instancer_proto_paths = collect_point_instancer_proto_paths();
552
553 /* Iterate through the stage. */
554 pxr::UsdPrim root = stage_->GetPseudoRoot();
555
556 stage_->SetInterpolationType(pxr::UsdInterpolationType::UsdInterpolationTypeHeld);
557
558 /* Create readers, skipping over prototype prims in this pass. */
559 collect_readers(root, instancer_proto_paths, params_.import_defined_only, readers_);
560
562 /* Collect the scene-graph instance prototypes. */
563 std::vector<pxr::UsdPrim> protos = stage_->GetPrototypes();
564
565 for (const pxr::UsdPrim &proto_prim : protos) {
566 Vector<USDPrimReader *> proto_readers;
567 collect_readers(proto_prim, instancer_proto_paths, true, proto_readers);
568 proto_readers_.add(proto_prim.GetPath(), proto_readers);
569
570 for (USDPrimReader *reader : proto_readers) {
571 readers_.append(reader);
572 reader->incref();
573 }
574 }
575 }
576
577 if (!instancer_proto_paths.is_empty()) {
578 create_point_instancer_proto_readers(instancer_proto_paths);
579 }
580}
581
583{
584 /* Iterate over the skeleton readers to create the
585 * armature object map, which maps a USD skeleton prim
586 * path to the corresponding armature object. */
587 Map<pxr::SdfPath, Object *> usd_path_to_armature;
588 for (const USDPrimReader *reader : readers_) {
589 if (dynamic_cast<const USDSkeletonReader *>(reader) && reader->object()) {
590 usd_path_to_armature.add(reader->prim_path(), reader->object());
591 }
592 }
593
594 /* Iterate over the mesh readers and set armature objects on armature modifiers. */
595 for (const USDPrimReader *reader : readers_) {
596 if (!reader->object()) {
597 continue;
598 }
599 const USDMeshReader *mesh_reader = dynamic_cast<const USDMeshReader *>(reader);
600 if (!mesh_reader) {
601 continue;
602 }
603 /* Check if the mesh object has an armature modifier. */
605 if (!md) {
606 continue;
607 }
608
609 ArmatureModifierData *amd = reinterpret_cast<ArmatureModifierData *>(md);
610
611 /* Assign the armature based on the bound USD skeleton path of the skinned mesh. */
612 pxr::SdfPath skel_path = mesh_reader->get_skeleton_path();
613 Object *object = usd_path_to_armature.lookup_default(skel_path, nullptr);
614 if (object == nullptr) {
617 "%s: Couldn't find armature object corresponding to USD skeleton %s",
618 __func__,
619 skel_path.GetAsString().c_str());
620 continue;
621 }
622 amd->object = object;
623
624 /* Per the UsdSkel spec, a skinned mesh's own and ancestor xformOps below the SkelRoot do not
625 * position the skinned result: the geometry is placed by the bound Skeleton's world transform,
626 * with `primvars:skel:geomBindTransform` aligning it (skinned mesh world =
627 * skeleton world * geomBindTransform). Blender's armature deform reproduces this when the mesh
628 * object is a child of the armature with its local transform equal to the geomBindTransform.
629 * USDMeshReader::get_local_usd_xform already set the mesh local transform to the
630 * geomBindTransform (or the identity when no usable geomBindTransform is authored), so
631 * re-parent the mesh to the armature (with an identity parent-inverse) here. Otherwise the
632 * mesh keeps the transform of its USD-hierarchy parent and ends up mis-scaled/rotated whenever
633 * that differs from the skeleton's transform. */
634 Object *mesh_object = reader->object();
635
636 /* Guard against a parent cycle in the unusual case where the bound Skeleton prim is a USD
637 * descendant of the skinned mesh, in which case the armature is already parented to the mesh.
638 */
639 if (mesh_object == object || BKE_object_parent_loop_check(object, mesh_object)) {
640 continue;
641 }
642
643 mesh_object->parent = object;
644 unit_m4(mesh_object->parentinv);
645 }
646}
647
649{
650 BLI_assert(valid());
651
652 /* Build the material name map if it's not built yet. */
653 if (settings_.mat_name_to_mat.is_empty()) {
655 }
656
657 USDMaterialReader mtl_reader(params_, *bmain);
658 for (const pxr::SdfPath &mtl_path : material_paths_) {
659 pxr::UsdPrim prim = stage_->GetPrimAtPath(mtl_path);
660
661 pxr::UsdShadeMaterial usd_mtl(prim);
662 if (!usd_mtl) {
663 continue;
664 }
665
668 {
669 /* The material already exists. */
670 continue;
671 }
672
673 /* Can the material be handled by an import hook? */
674 const bool have_import_hook = settings_.mat_import_hook_sources.contains(mtl_path);
675
676 /* Add the Blender material. If we have an import hook which can handle this material
677 * we don't import USD Preview Surface shaders. */
678 Material *new_mtl = mtl_reader.add_material(usd_mtl, !have_import_hook);
679 BLI_assert_msg(new_mtl, "Failed to create material");
680
681 settings_.mat_name_to_mat.add_new(new_mtl->id.name + 2, new_mtl);
682
684 /* Record the Blender material we created for the USD material with the given path.
685 * This is to prevent importing the material again when assigning materials to objects
686 * elsewhere in the code. */
687 settings_.usd_path_to_mat.add_new(mtl_path, new_mtl);
688 }
689
690 if (have_import_hook) {
691 /* Defer invoking the hook to convert the material till we can do so from
692 * the main thread. */
693 settings_.usd_path_to_mat_for_hook.add_new(mtl_path, new_mtl);
694 }
695 }
696}
697
699{
700 /* Iterate over the imported materials and set a fake user for any unused
701 * materials. */
702 for (Material *mat : settings_.usd_path_to_mat.values()) {
703 if (mat->id.us == 0) {
704 id_fake_user_set(&mat->id);
705 }
706 }
707}
708
710{
711 pxr::UsdPrimRange range = stage_->Traverse();
712 for (pxr::UsdPrim prim : range) {
713 if (prim.IsA<pxr::UsdShadeMaterial>()) {
714 pxr::UsdShadeMaterial usd_mat(prim);
716 settings_.mat_import_hook_sources.add(prim.GetPath());
717 }
718 }
719 }
720}
721
723{
724 if (settings_.usd_path_to_mat_for_hook.is_empty()) {
725 /* No materials can be converted by a hook. */
726 return;
727 }
728
729 for (const auto item : settings_.usd_path_to_mat_for_hook.items()) {
730 pxr::UsdPrim prim = stage_->GetPrimAtPath(item.key);
731
732 pxr::UsdShadeMaterial usd_mtl(prim);
733 if (!usd_mtl) {
734 continue;
735 }
736
738 stage_, item.value, usd_mtl, params_, reports());
739
740 if (!success) {
741 /* None of the hooks succeeded, so fall back on importing USD Preview Surface if possible. */
742 CLOG_WARN(&LOG,
743 "USD hook 'on_material_import' for material %s failed, attempting to convert USD "
744 "Preview Surface material",
745 usd_mtl.GetPath().GetAsString().c_str());
746
747 USDMaterialReader mat_reader(this->params_, *bmain);
748 mat_reader.import_usd_preview(item.value, usd_mtl);
749 }
750 }
751}
752
754{
755 for (USDPrimReader *reader : readers_) {
756 decref(reader);
757 }
758 readers_.clear();
759
760 for (const auto item : proto_readers_.items()) {
761 for (USDPrimReader *reader : item.value) {
762 decref(reader);
763 }
764 }
766
767 for (const auto item : instancer_proto_readers_.items()) {
768 for (USDPrimReader *reader : item.value) {
769 decref(reader);
770 }
771 }
773
775 decref(reader);
776 }
777 dome_light_readers_.clear();
778}
779
781{
783 readers_.begin(), readers_.end(), [](const USDPrimReader *a, const USDPrimReader *b) {
784 int result = BLI_strcasecmp(a->name().c_str(), b->name().c_str());
785
786 /* The sorting should be deterministic and consistent regardless of how the list of readers
787 * was created. Use the original, unique, USD prim path to break ties. */
788 if (result == 0) {
789 return a->prim_path() < b->prim_path();
790 }
791
792 return result < 0;
793 });
794}
795
797{
798 if (proto_readers_.is_empty() && instancer_proto_readers_.is_empty()) {
799 return;
800 }
801
802 Collection *all_protos_collection = create_collection(bmain, parent_collection, "prototypes");
803
804 if (all_protos_collection) {
805 all_protos_collection->flag |= COLLECTION_HIDE_VIEWPORT;
806 all_protos_collection->flag |= COLLECTION_HIDE_RENDER;
807 if (parent_collection) {
808 DEG_id_tag_update(&parent_collection->id, ID_RECALC_HIERARCHY);
809 }
810 }
811
812 Map<pxr::SdfPath, Collection *> proto_collection_map;
813
814 for (const pxr::SdfPath &path : proto_readers_.keys()) {
815 Collection *proto_collection = create_collection(bmain, all_protos_collection, "proto");
816
817 proto_collection_map.add(path, proto_collection);
818 }
819
820 /* Set the instance collections on the readers, including the prototype
821 * readers (which are included in readers_), as instancing may be nested. */
822
823 for (USDPrimReader *reader : readers_) {
824 if (USDInstanceReader *instance_reader = dynamic_cast<USDInstanceReader *>(reader)) {
825 set_instance_collection(instance_reader, proto_collection_map);
826 }
827 }
828
829 /* Add the prototype objects to the collections. */
830 for (const auto &item : proto_readers_.items()) {
831 Collection *collection = proto_collection_map.lookup_default(item.key, nullptr);
832 if (collection == nullptr) {
833 CLOG_WARN(&LOG,
834 "Couldn't find collection when adding objects for prototype %s",
835 item.key.GetAsString().c_str());
836 continue;
837 }
838
839 for (const USDPrimReader *reader : item.value) {
840 Object *ob = reader->object();
841
842 if (!ob) {
843 continue;
844 }
845
846 BKE_collection_object_add(bmain, collection, ob);
847 }
848 }
849
850 /* Create collections for the point instancer prototypes. */
851
852 /* For every point instancer reader, create a "prototypes" collection and set it
853 * on the Collection Info node referenced by the geometry nodes modifier created by
854 * the reader. We also create collections containing prototype geometry as children
855 * of the "prototypes" collection. These child collections will be indexed for
856 * instancing by the Instance on Points geometry node.
857 *
858 * Note that the prototype collections will be ordered alphabetically by the Collection
859 * Info node. We must therefore take care to generate collection names that will maintain
860 * the original prototype order, so that the prototype indices will remain valid. We use
861 * the naming convention proto_<index>, where the index suffix may be zero padded (e.g.,
862 * "proto_00", "proto_01", "proto_02", etc.).
863 */
864
865 for (USDPrimReader *reader : readers_) {
866 USDPointInstancerReader *instancer_reader = dynamic_cast<USDPointInstancerReader *>(reader);
867 if (!instancer_reader) {
868 continue;
869 }
870
871 pxr::SdfPathVector proto_paths = instancer_reader->proto_paths();
872 const pxr::SdfPath &instancer_path = reader->prim().GetPath();
873 Collection *instancer_protos_coll = create_collection(
874 bmain, all_protos_collection, instancer_path.GetName().c_str());
875
876 /* Determine the max number of digits we will need for the possibly zero-padded
877 * string representing the prototype index. */
878 const int max_index_digits = integer_digits_i(proto_paths.size());
879
880 int proto_index = 0;
881
882 for (const pxr::SdfPath &proto_path : proto_paths) {
883 BLI_assert(max_index_digits > 0);
884
885 /* Format the collection name to follow the proto_<index> pattern. */
886 std::string coll_name = fmt::format("proto_{0:0{1}}", proto_index, max_index_digits);
887
888 /* Create the collection and populate it with the prototype objects. */
889 Collection *proto_coll = create_collection(bmain, instancer_protos_coll, coll_name.c_str());
890 Vector<USDPrimReader *> proto_readers = instancer_proto_readers_.lookup_default(proto_path,
891 {});
892 for (const USDPrimReader *proto : proto_readers) {
893 Object *ob = proto->object();
894 if (!ob) {
895 continue;
896 }
897 BKE_collection_object_add(bmain, proto_coll, ob);
898 }
899 ++proto_index;
900 }
901
902 instancer_reader->set_collection(bmain, *instancer_protos_coll);
903 }
904}
905
906void USDStageReader::create_point_instancer_proto_readers(const UsdPathSet &proto_paths)
907{
908 if (proto_paths.is_empty()) {
909 return;
910 }
911
912 for (const pxr::SdfPath &path : proto_paths) {
913
914 pxr::UsdPrim proto_prim = stage_->GetPrimAtPath(path);
915
916 if (!proto_prim) {
917 continue;
918 }
919
920 Vector<USDPrimReader *> proto_readers;
921
922 /* Note that point instancer prototypes may be defined as overs, so
923 * we must call collect readers with argument defined_prims_only = false. */
924 collect_readers(proto_prim, proto_paths, false /* include undefined prims */, proto_readers);
925
926 instancer_proto_readers_.add(path, proto_readers);
927
928 for (USDPrimReader *reader : proto_readers) {
929 reader->set_is_in_instancer_proto(true);
930 readers_.append(reader);
931 reader->incref();
932 }
933 }
934}
935
936void USDStageReader::collect_point_instancer_proto_paths(const pxr::UsdPrim &prim,
937 UsdPathSet &r_paths) const
938{
939 /* Note that we use custom filter flags to allow traversing undefined prims,
940 * because prototype prims may be defined as overs which are skipped by the
941 * default predicate. */
942 pxr::Usd_PrimFlagsConjunction filter_flags = pxr::UsdPrimIsActive && pxr::UsdPrimIsLoaded &&
943 !pxr::UsdPrimIsAbstract;
944
945 pxr::UsdPrimSiblingRange children = prim.GetFilteredChildren(filter_flags);
946
947 for (const auto &child_prim : children) {
948
949 /* Note we allow undefined prims in case prototypes are defined as overs.
950 * If the prim is defined, we apply additional checks for inclusion. */
951 if (child_prim.IsDefined()) {
952 const pxr::UsdGeomImageable imageable = pxr::UsdGeomImageable(child_prim);
953 if (!imageable) {
954 continue;
955 }
956
957 /* We should only traverse through a hierarchy, and any potential instancers, if they would
958 * be included by our purpose and visibility checks, matching what is inside
959 * #collect_readers. */
960 if (!include_by_purpose(imageable)) {
961 continue;
962 }
963
964 if (!include_by_visibility(imageable)) {
965 continue;
966 }
967 }
968
969 /* We should only consider potential point instancers if they would be included by the scene
970 * instancing flags. */
971 if (!params_.support_scene_instancing && child_prim.IsInPrototype()) {
972 continue;
973 }
974
975 if (pxr::UsdGeomPointInstancer instancer = pxr::UsdGeomPointInstancer(child_prim)) {
976 pxr::SdfPathVector paths;
977 instancer.GetPrototypesRel().GetTargets(&paths);
978 for (const pxr::SdfPath &path : paths) {
979 r_paths.add(path);
980 }
981 }
982
983 collect_point_instancer_proto_paths(child_prim, r_paths);
984 }
985}
986
987UsdPathSet USDStageReader::collect_point_instancer_proto_paths() const
988{
990
991 if (!stage_) {
992 return result;
993 }
994
995 collect_point_instancer_proto_paths(stage_->GetPseudoRoot(), result);
996
997 std::vector<pxr::UsdPrim> protos = stage_->GetPrototypes();
998
999 for (const pxr::UsdPrim &proto_prim : protos) {
1000 collect_point_instancer_proto_paths(proto_prim, result);
1001 }
1002
1003 return result;
1004}
1005
1006} // namespace io::usd
1007} // namespace blender
General operations, lookup, etc. for blender objects.
#define M_PI_2
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
Object groups, one object can be in many groups at once.
Object is a sort of wrapper for general info.
#define BLI_assert_msg(a, msg)
SIMD_FORCE_INLINE const btScalar & z() const
Return the z value.
Definition btQuadWord.h:117
void clear()
Definition BLI_map.hh:1038
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
Value lookup_default(const Key &key, const Value &default_value) const
Definition BLI_map.hh:570
ItemIterator items() const &
Definition BLI_map.hh:902
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
bool is_empty() const
Definition BLI_set.hh:614
USDBasisCurvesReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDCameraReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDDomeLightReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
void set_instance_collection(Collection *coll)
USDInstanceReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDLightReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
Material * add_material(const pxr::UsdShadeMaterial &usd_material, bool read_usd_preview=true) const
void import_usd_preview(Material *mtl, const pxr::UsdShadeMaterial &usd_material) const
USDMeshReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
pxr::SdfPath get_skeleton_path() const
USDNurbsReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDParticleFieldReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDPointInstancerReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
void set_collection(Main *bmain, Collection &coll)
USDPointsReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDShapeReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDSkeletonReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDPrimReader * create_reader(const pxr::UsdPrim &prim)
void call_material_import_hooks(struct Main *bmain) const
Vector< pxr::SdfPath > material_paths_
const USDImportParams & params() const
USDPrimReader * create_reader_if_allowed(const pxr::UsdPrim &prim)
USDStageReader(pxr::UsdStageRefPtr stage, const USDImportParams &params, const std::function< CacheFile *()> &get_cache_file_fn={})
void create_proto_collections(Main *bmain, Collection *parent_collection)
Vector< USDDomeLightReader * > dome_light_readers_
Vector< USDPrimReader * > readers_
void import_all_materials(struct Main *bmain)
USDVolumeReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
USDXformReader(const pxr::UsdPrim &prim, const USDImportParams &import_params, const ImportSettings &settings)
bool have_material_import_hook(pxr::UsdStageRefPtr stage, const pxr::UsdShadeMaterial &usd_material, const USDImportParams &import_params, ReportList *reports)
Definition usd_hook.cc:652
static void set_instance_collection(USDInstanceReader *instance_reader, const Map< pxr::SdfPath, Collection * > &proto_collection_map)
static void decref(USDPrimReader *reader)
static void convert_to_z_up(pxr::UsdStageRefPtr stage, ImportSettings &settings)
static Collection * create_collection(Main *bmain, Collection *parent, const char *name)
bool call_material_import_hooks(pxr::UsdStageRefPtr stage, Material *material, const pxr::UsdShadeMaterial &usd_material, const USDImportParams &import_params, ReportList *reports)
Definition usd_hook.cc:667
static void find_prefix_to_skip(pxr::UsdStageRefPtr stage, ImportSettings &settings)
static void determine_blender_compat(pxr::UsdStageRefPtr stage, ImportSettings &settings)
Material * find_existing_material(const pxr::SdfPath &usd_mat_path, const USDImportParams &params, const Map< std::string, Material * > &mat_map, const Map< pxr::SdfPath, Material * > &usd_path_to_mat)
Set< pxr::SdfPath > UsdPathSet
void build_material_map(const Main *bmain, Map< std::string, Material * > &r_mat_map)
EulerXYZBase< float > EulerXYZ
MatT from_rotation(const RotationT &rotation)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
@ RPT_WARNING
Definition BKE_report.hh:40
MINLINE int integer_digits_i(int i)
void id_fake_user_set(ID *id)
Definition lib_id.cc:471
bool BKE_object_parent_loop_check(const Object *parent, const Object *ob)
Definition object.cc:4898
void parallel_sort(RandomAccessIterator begin, RandomAccessIterator end)
Definition BLI_sort.hh:37
unsigned int uint32_t
Definition BKE_text.h:81
void DEG_id_tag_update(ID *id, unsigned int flags)
bool BKE_collection_object_add(Main *bmain, Collection *collection, Object *ob)
void unit_m4(float m[4][4])
ModifierData * BKE_modifiers_findby_type(const Object *ob, ModifierType type)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
@ ID_RECALC_HIERARCHY
Definition DNA_ID.h:1158
static CLG_LogRef LOG
Definition logging.cpp:12
Collection * BKE_collection_add(Main *bmain, Collection *collection_parent, const char *name_custom)
struct Object * parent
float parentinv[4][4]
Set< pxr::SdfPath > mat_import_hook_sources
Map< pxr::SdfPath, Material * > usd_path_to_mat_for_hook
Map< std::string, Material * > mat_name_to_mat
Map< pxr::SdfPath, Material * > usd_path_to_mat
std::function< CacheFile *()> get_cache_file
MtlNameCollisionMode mtl_name_collision_mode
Definition usd.hh:230
wmJobWorkerStatus * worker_status
Definition usd.hh:242