Blender V5.3
usd_capi_export.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2019 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include <fmt/core.h>
6#include <fmt/format.h>
7
9#include "usd.hh"
12#include "usd_hook.hh"
14#include "usd_light_convert.hh"
15#include "usd_private.hh"
16
17#include <pxr/base/tf/token.h>
18#include <pxr/pxr.h>
19#include <pxr/usd/sdf/assetPath.h>
20#include <pxr/usd/sdf/path.h>
21#include <pxr/usd/usd/primRange.h>
22#include <pxr/usd/usd/stage.h>
23#include <pxr/usd/usdGeom/metrics.h>
24#include <pxr/usd/usdGeom/pointInstancer.h>
25#include <pxr/usd/usdGeom/tokens.h>
26#include <pxr/usd/usdGeom/xform.h>
27#include <pxr/usd/usdGeom/xformCommonAPI.h>
28#include <pxr/usd/usdUI/accessibilityAPI.h>
29#include <pxr/usd/usdUtils/usdzPackage.h>
30
31#include "MEM_guardedalloc.h"
32
33#include "DEG_depsgraph.hh"
36
38#include "DNA_scene_types.h"
39
40#include "BKE_appdir.hh"
41#include "BKE_blender_version.h"
42#include "BKE_context.hh"
43#include "BKE_global.hh"
44#include "BKE_image.hh"
45#include "BKE_image_save.hh"
46#include "BKE_lib_id.hh"
47#include "BKE_report.hh"
48#include "BKE_scene.hh"
49
50#include "BLI_fileops.hh"
51#include "BLI_math_matrix.hh"
54#include "BLI_math_vector_c.hh"
55#include "BLI_path_utils.hh"
56#include "BLI_string.hh"
57#include "BLI_timeit.hh"
58
59#include "ED_util.hh"
60
61#include <IMB_imbuf.hh>
62#include <IMB_imbuf_types.hh>
63
64#include "WM_api.hh"
65#include "WM_types.hh"
66
67#include "CLG_log.h"
68
69namespace blender {
70
71static CLG_LogRef LOG = {"io.usd"};
72
73namespace io::usd {
74
76 Main *bmain = nullptr;
77 Depsgraph *depsgraph = nullptr;
78 wmWindowManager *wm = nullptr;
79 Scene *scene = nullptr;
80
85
86 bool export_ok = false;
88
89 bool targets_usdz() const
90 {
91 return usdz_filepath[0] != '\0';
92 }
93
94 const char *export_filepath() const
95 {
96 if (targets_usdz()) {
97 return usdz_filepath;
98 }
100 }
101};
102
103/* Returns true if the given prim path is valid, per
104 * the requirements of the prim path manipulation logic
105 * of the exporter. Also returns true if the path is
106 * the empty string. Returns false otherwise. */
107static bool prim_path_valid(const std::string &path)
108{
109 if (path.empty()) {
110 /* Empty paths are ignored in the code,
111 * so they can be passed through. */
112 return true;
113 }
114
115 /* Check path syntax. */
116 std::string errMsg;
117 if (!pxr::SdfPath::IsValidPathString(path, &errMsg)) {
119 RPT_ERROR, "USD Export: invalid path string '%s': %s", path.c_str(), errMsg.c_str());
120 return false;
121 }
122
123 /* Verify that an absolute prim path can be constructed
124 * from this path string. */
125
126 pxr::SdfPath sdf_path(path);
127 if (!sdf_path.IsAbsolutePath()) {
128 WM_global_reportf(RPT_ERROR, "USD Export: path '%s' is not an absolute path", path.c_str());
129 return false;
130 }
131
132 if (!sdf_path.IsPrimPath()) {
133 WM_global_reportf(RPT_ERROR, "USD Export: path string '%s' is not a prim path", path.c_str());
134 return false;
135 }
136
137 return true;
138}
139
146static bool export_params_valid(const USDExportParams &params)
147{
148 bool valid = true;
149
150 if (!prim_path_valid(params.root_prim_path)) {
151 valid = false;
152 }
153
154 return valid;
155}
156
163static void ensure_root_prim(pxr::UsdStageRefPtr stage, const USDExportParams &params)
164{
165 if (params.root_prim_path.empty()) {
166 return;
167 }
168
169 pxr::UsdGeomXform root_xf = pxr::UsdGeomXform::Define(stage,
170 pxr::SdfPath(params.root_prim_path));
171
172 if (!root_xf) {
173 return;
174 }
175
176 pxr::UsdGeomXformCommonAPI xf_api(root_xf.GetPrim());
177
178 if (!xf_api) {
179 return;
180 }
181
183 xf_api.SetScale(pxr::GfVec3f(float(1.0 / get_meters_per_unit(params))));
184 }
185
186 if (params.convert_orientation) {
187 float3x3 mrot;
189 IO_AXIS_Y, IO_AXIS_Z, params.forward_axis, params.up_axis, mrot.ptr());
190
192 xf_api.SetRotate(pxr::GfVec3f(eul.x().degree(), eul.y().degree(), eul.z().degree()));
193 }
194
195 /* Color-space on the root prim. It's also applied on all individual prims that need
196 * it, but perhaps this is useful to signal the overall color-space of the file. */
197 colorspace_apply_to_prim(root_xf.GetPrim());
198
199 for (const auto &path : pxr::SdfPath(params.root_prim_path).GetPrefixes()) {
200 auto xform = pxr::UsdGeomXform::Define(stage, path);
201 /* Tag generated primitives to allow filtering on import. */
202 xform.GetPrim().SetCustomDataByKey(pxr::TfToken("Blender:generated"), pxr::VtValue(true));
203 }
204}
205
212static void write_root_accessibility_information(pxr::UsdStageRefPtr stage,
213 const USDExportParams &params)
214{
215 /* Don't apply the API if both the label and description are empty. */
216 if (params.accessibility_label.empty() && params.accessibility_description.empty()) {
217 return;
218 }
219
220 pxr::UsdUIAccessibilityAPI accessibility_api = pxr::UsdUIAccessibilityAPI::ApplyDefaultAPI(
221 stage->GetDefaultPrim());
222 if (!accessibility_api) {
223 return;
224 }
225
226 if (!params.accessibility_label.empty()) {
227 accessibility_api.CreateLabelAttr().Set(params.accessibility_label);
228 }
229
230 if (!params.accessibility_description.empty()) {
231 accessibility_api.CreateDescriptionAttr().Set(params.accessibility_description);
232 }
233}
234
236{
237 timeit::Nanoseconds duration = timeit::Clock::now() - data->start_time;
238 const char *export_filepath = data->export_filepath();
239 fmt::print("USD export of '{}' took ", export_filepath);
240 timeit::print_duration(duration);
241 fmt::print("\n");
242}
243
244static void process_usdz_textures(const ExportJobData *data, const char *path)
245{
246 const TextureDownscaleSize enum_value = data->params.usdz_downscale_size;
247 if (enum_value == TextureDownscaleSize::Keep) {
248 return;
249 }
250
251 const int image_size = (enum_value == TextureDownscaleSize::Custom) ?
252 data->params.usdz_downscale_custom_size :
253 int(enum_value);
254
255 char texture_path[FILE_MAX];
256 STRNCPY(texture_path, path);
257 BLI_path_append(texture_path, FILE_MAX, "textures");
258 BLI_path_slash_ensure(texture_path, sizeof(texture_path));
259
260 direntry *entries;
261 uint num_files = BLI_filelist_dir_contents(texture_path, &entries);
262
263 for (int index = 0; index < num_files; index++) {
264 /* We can skip checking extensions as this folder is only created
265 * when we're doing a USDZ export. */
266 if (!BLI_is_dir(entries[index].path)) {
267 Image *im = BKE_image_load(data->bmain, entries[index].path);
268 if (!im) {
269 CLOG_WARN(&LOG, "Unable to open file for downscaling: %s", entries[index].path);
270 continue;
271 }
272
273 int width, height;
274 BKE_image_get_size(im, nullptr, &width, &height);
275 const int longest = width >= height ? width : height;
276 const float scale = 1.0 / (float(longest) / float(image_size));
277
278 if (longest > image_size) {
279 const int width_adjusted = float(width) * scale;
280 const int height_adjusted = float(height) * scale;
281 BKE_image_scale(im, width_adjusted, height_adjusted, nullptr);
282
283 ImageSaveOptions opts;
284
286 &opts, data->bmain, data->scene, im, nullptr, false, false))
287 {
288 bool result = BKE_image_save(nullptr, data->bmain, im, nullptr, &opts);
289 if (!result) {
291 "Unable to resave '%s' (new size: %dx%d)",
292 data->usdz_filepath,
293 width_adjusted,
294 height_adjusted);
295 }
296 else {
298 "Downscaled '%s' to %dx%d",
299 entries[index].path,
300 width_adjusted,
301 height_adjusted);
302 }
303 }
304
306 }
307
308 /* Make sure to free the image so it doesn't stick
309 * around in the library of the open file. */
310 BKE_id_free(data->bmain, static_cast<void *>(im));
311 }
312 }
313
314 BLI_filelist_free(entries, num_files);
315}
316
326{
327 char usdc_temp_dir[FILE_MAX], usdc_file[FILE_MAX];
328 BLI_path_split_dir_file(data->unarchived_filepath,
329 usdc_temp_dir,
330 sizeof(usdc_temp_dir),
331 usdc_file,
332 sizeof(usdc_file));
333
334 char usdz_file[FILE_MAX];
335 BLI_path_split_file_part(data->usdz_filepath, usdz_file, FILE_MAX);
336
337 char original_working_dir_buff[FILE_MAX];
338 const char *original_working_dir = BLI_current_working_dir(original_working_dir_buff,
339 sizeof(original_working_dir_buff));
340 /* Buffer is expected to be returned by #BLI_current_working_dir, although in theory other
341 * returns are possible on some platforms, this is not handled by this code. */
342 BLI_assert(original_working_dir == original_working_dir_buff);
343
344 BLI_change_working_dir(usdc_temp_dir);
345
346 process_usdz_textures(data, usdc_temp_dir);
347
348 pxr::UsdUtilsCreateNewUsdzPackage(pxr::SdfAssetPath(usdc_file), usdz_file);
349 BLI_change_working_dir(original_working_dir);
350
351 char usdz_temp_full_path[FILE_MAX];
352 BLI_path_join(usdz_temp_full_path, FILE_MAX, usdc_temp_dir, usdz_file);
353
354 int result = 0;
355 if (BLI_exists(data->usdz_filepath)) {
356 result = BLI_delete(data->usdz_filepath, false, false);
357 if (result != 0) {
358 BKE_reportf(data->params.worker_status->reports,
359 RPT_ERROR,
360 "USD Export: Unable to delete existing usdz file %s",
361 data->usdz_filepath);
362 return false;
363 }
364 }
365 result = BLI_path_move(usdz_temp_full_path, data->usdz_filepath);
366 if (result != 0) {
367 BKE_reportf(data->params.worker_status->reports,
368 RPT_ERROR,
369 "USD Export: Couldn't move new usdz file from temporary location %s to %s",
370 usdz_temp_full_path,
371 data->usdz_filepath);
372 return false;
373 }
374
375 return true;
376}
377
379{
380 char dir_path[FILE_MAX];
381 BLI_path_join(dir_path, sizeof(dir_path), BKE_tempdir_session(), "usd", "image_cache");
382 return dir_path;
383}
384
385std::string get_image_cache_file(const std::string &file_name, bool mkdir)
386{
387 std::string dir_path = image_cache_file_path();
388 if (mkdir) {
389 BLI_dir_create_recursive(dir_path.c_str());
390 }
391
392 char file_path[FILE_MAX];
393 BLI_path_join(file_path, sizeof(file_path), dir_path.c_str(), file_name.c_str());
394 return file_path;
395}
396
397std::string cache_image_color(const float color[4])
398{
399 std::string name = fmt::format("color_{:02X}{:02X}{:02X}.exr",
400 int(color[0] * 255),
401 int(color[1] * 255),
402 int(color[2] * 255));
403 std::string file_path = get_image_cache_file(name);
404 if (BLI_exists(file_path.c_str())) {
405 return file_path;
406 }
407
409 IMB_rectfill(ibuf, color);
410 ibuf->ftype = IMB_FTYPE_OPENEXR;
412
413 if (IMB_save_image(ibuf, file_path.c_str(), ImBufFlags::FloatData)) {
414 CLOG_INFO(&LOG, "%s", file_path.c_str());
415 }
416 else {
417 CLOG_ERROR(&LOG, "Can't save %s", file_path.c_str());
418 file_path = "";
419 }
420 IMB_freeImBuf(ibuf);
421
422 return file_path;
423}
424
426 pxr::UsdGeomPointInstancer instancer,
427 const pxr::UsdStageRefPtr &stage,
428 const pxr::SdfPath &wrapper_path,
429 std::vector<pxr::UsdPrim> &proto_list)
430{
431 /* Compute extent of the current point instancer. */
432 pxr::VtArray<pxr::GfVec3f> extent;
433 instancer.ComputeExtentAtTime(&extent, pxr::UsdTimeCode::Default(), pxr::UsdTimeCode::Default());
434 instancer.CreateExtentAttr().Set(extent);
435
436 pxr::UsdPrim wrapper_prim = stage->GetPrimAtPath(wrapper_path);
437 if (!wrapper_prim || !wrapper_prim.IsValid()) {
438 return;
439 }
440
441 std::string real_path_str;
442
443 for (const pxr::SdfPrimSpecHandle &primSpec : wrapper_prim.GetPrimStack()) {
444 if (!primSpec || !primSpec->HasReferences()) {
445 continue;
446 }
447
448 for (const pxr::SdfReference &ref : primSpec->GetReferenceList().GetPrependedItems()) {
449 if (ref.GetAssetPath().empty() && !ref.GetPrimPath().IsEmpty()) {
450 real_path_str = ref.GetPrimPath().GetString();
451 break;
452 }
453 }
454 if (!real_path_str.empty()) {
455 break;
456 }
457 }
458
459 if (real_path_str.empty()) {
460 CLOG_WARN(&LOG, "No prototype reference found for: %s", wrapper_path.GetText());
461 return;
462 }
463
464 const pxr::SdfPath real_path(real_path_str);
465 pxr::UsdPrim proto_prim = stage->GetPrimAtPath(real_path);
466
467 if (!proto_prim || !proto_prim.IsValid()) {
468 CLOG_WARN(&LOG, "Referenced prototype not found at: %s", real_path.GetText());
469 return;
470 }
471
472 proto_list.push_back(proto_prim);
473 proto_list.push_back(wrapper_prim.GetParent());
474
475 std::string doc_message = fmt::format(
476 "This prim is used as a prototype by the PointInstancer \"{}\" so we override the def "
477 "with an \"over\" so that it isn't imaged in the scene, but is available as a prototype "
478 "that can be referenced.",
479 wrapper_prim.GetName().GetString());
480 proto_prim.SetDocumentation(doc_message);
481
482 /* Check if the proto prim itself is a PointInstancer. */
483 if (proto_prim.IsA<pxr::UsdGeomPointInstancer>()) {
484 pxr::UsdGeomPointInstancer nested_instancer(proto_prim);
485 pxr::SdfPathVector nested_targets;
486 if (nested_instancer.GetPrototypesRel().GetTargets(&nested_targets)) {
487 for (const pxr::SdfPath &nested_wrapper_path : nested_targets) {
489 nested_instancer, stage, nested_wrapper_path, proto_list);
490 }
491 }
492 }
493
494 /* Also check all children of the proto prim for nested PointInstancers. */
495 for (const pxr::UsdPrim &child : proto_prim.GetAllChildren()) {
496 if (child.IsA<pxr::UsdGeomPointInstancer>()) {
497 pxr::UsdGeomPointInstancer nested_instancer(child);
498 pxr::SdfPathVector nested_targets;
499 if (nested_instancer.GetPrototypesRel().GetTargets(&nested_targets)) {
500 for (const pxr::SdfPath &nested_wrapper_path : nested_targets) {
502 nested_instancer, stage, nested_wrapper_path, proto_list);
503 }
504 }
505 }
506 }
507}
508
509pxr::UsdStageRefPtr export_to_stage(const USDExportParams &params,
510 Depsgraph *depsgraph,
511 const char *filepath)
512{
513 pxr::UsdStageRefPtr usd_stage = pxr::UsdStage::CreateNew(filepath);
514 if (!usd_stage) {
515 return usd_stage;
516 }
517
518 wmJobWorkerStatus *worker_status = params.worker_status;
519 Scene *scene = DEG_get_input_scene(depsgraph);
520 Main *bmain = DEG_get_bmain(depsgraph);
521
522 SubdivModifierDisabler mod_disabler(depsgraph);
523
524 /* If we want to set the subdiv scheme, then we need to the export the mesh
525 * without the subdiv modifier applied. */
527 mod_disabler.disable_modifiers();
528 BKE_scene_graph_update_tagged(depsgraph, bmain);
529 }
530
531 /* This whole `export_to_stage` function is assumed to cover about 80% of the whole export
532 * process, from 0.1f to 0.9f. */
533 worker_status->progress = 0.10f;
534 worker_status->do_update = true;
535
536 usd_stage->SetMetadata(pxr::UsdGeomTokens->metersPerUnit, double(scene->unit.scale_length));
537 usd_stage->GetRootLayer()->SetDocumentation(std::string("Blender v") +
539
540 /* Set up the stage for animated data. */
541 if (params.export_animation) {
542 usd_stage->SetTimeCodesPerSecond(scene->frames_per_second());
543 usd_stage->SetFramesPerSecond(scene->frames_per_second());
544 usd_stage->SetStartTimeCode(scene->r.sfra);
545 usd_stage->SetEndTimeCode(scene->r.efra);
546 }
547
548 /* For restoring the current frame after exporting animation is done. */
549 const int orig_frame = scene->r.cfra;
550
551 /* Ensure Python types for invoking hooks are registered. */
553
554 pxr::VtValue upAxis = pxr::VtValue(pxr::UsdGeomTokens->z);
555 if (params.convert_orientation) {
556 if (params.up_axis == IO_AXIS_X) {
557 upAxis = pxr::VtValue(pxr::UsdGeomTokens->x);
558 }
559 else if (params.up_axis == IO_AXIS_Y) {
560 upAxis = pxr::VtValue(pxr::UsdGeomTokens->y);
561 }
562 }
563
564 usd_stage->SetMetadata(pxr::UsdGeomTokens->upAxis, upAxis);
565
566 const double meters_per_unit = get_meters_per_unit(params);
567 pxr::UsdGeomSetStageMetersPerUnit(usd_stage, meters_per_unit);
568
569 ensure_root_prim(usd_stage, params);
570
571 USDHierarchyIterator iter(bmain, depsgraph, usd_stage, params);
572
573 worker_status->progress = 0.11f;
574 worker_status->do_update = true;
575
576 if (params.export_animation) {
577 /* Writing the animated frames is not 100% of the work, here it's assumed to be 75% of it. */
578 float progress_per_frame = 0.75f / std::max(1, (scene->r.efra - scene->r.sfra + 1));
579 int exported_frame_count = 0;
580
581 for (float frame = scene->r.sfra; frame <= scene->r.efra; frame++) {
582 if (G.is_break || worker_status->stop) {
583 break;
584 }
585
586 /* Update the scene for the next frame to render. */
587 scene->r.cfra = int(frame);
588 scene->r.subframe = frame - scene->r.cfra;
590
591 iter.set_export_frame(frame);
592 iter.iterate_and_write();
593
594 /* Check if we need to perform an incremental save. A value of 0 will never trigger. */
595 exported_frame_count++;
596 if (exported_frame_count == params.incremental_frames) {
597 usd_stage->GetRootLayer()->Save();
598 exported_frame_count = 0;
599 }
600
601 worker_status->progress += progress_per_frame;
602 worker_status->do_update = true;
603 }
604 }
605 else {
606 /* If we're not animating, a single iteration over all objects is enough. */
607 iter.iterate_and_write();
608 }
609
610 worker_status->progress = 0.86f;
611 worker_status->do_update = true;
612
613 iter.release_writers();
614
615 if (params.export_shapekeys || params.export_armatures) {
616 iter.process_usd_skel();
617 }
618
619 /* Creating dome lights should be called after writers have
620 * completed, to avoid a name collision when creating the light
621 * prim. */
622 if (params.convert_world_material) {
623 world_material_to_dome_light(params, scene, usd_stage);
624 }
625
626 /* Set the default prim if it doesn't exist */
627 if (!usd_stage->GetDefaultPrim()) {
628 /* Use TraverseAll since it's guaranteed to be depth first and will get the first top level
629 * prim, and is less verbose than getting the PseudoRoot + iterating its children. */
630 for (auto prim : usd_stage->TraverseAll()) {
631 usd_stage->SetDefaultPrim(prim);
632 break;
633 }
634 }
635
636 /* Write accessibility information to the default prim. */
637 write_root_accessibility_information(usd_stage, params);
638
639 if (params.use_instancing) {
640 process_scene_graph_instances(params, usd_stage);
641 }
642
643 call_export_hooks(depsgraph, &iter, params.worker_status->reports);
644
645 worker_status->progress = 0.88f;
646 worker_status->do_update = true;
647
648 /* Finish up by going back to the keyframe that was current before we started. */
649 if (scene->r.cfra != orig_frame) {
650 scene->r.cfra = orig_frame;
652 }
653
654 worker_status->progress = 0.9f;
655 worker_status->do_update = true;
656
657 return usd_stage;
658}
659
660static void export_startjob(void *customdata, wmJobWorkerStatus *worker_status)
661{
662 ExportJobData *data = static_cast<ExportJobData *>(customdata);
663 data->export_ok = false;
664 data->start_time = timeit::Clock::now();
665
666 G.is_rendering = true;
667 if (data->wm) {
668 WM_locked_interface_set(data->wm, true);
669 }
670 G.is_break = false;
671
672 worker_status->progress = 0.01f;
673 worker_status->do_update = true;
674
675 /* Evaluate the depsgraph for exporting.
676 *
677 * Note that, unlike with its building, this is expected to be safe to perform from worker
678 * thread, since UI is locked during export, so there should not be any more changes in the Main
679 * original data concurrently done from the main thread at this point. All necessary (deferred)
680 * changes are expected to have been triggered and processed during depsgraph building in
681 * #USD_export. */
682 BKE_scene_graph_update_tagged(data->depsgraph, data->bmain);
683
684 worker_status->progress = 0.1f;
685 worker_status->do_update = true;
686 data->params.worker_status = worker_status;
687
688 pxr::UsdStageRefPtr usd_stage = export_to_stage(
689 data->params, data->depsgraph, data->unarchived_filepath);
690 if (!usd_stage) {
691 /* This happens when the USD JSON files cannot be found. When that happens,
692 * the USD library doesn't know it has the functionality to write USDA and
693 * USDC files, and creating a new UsdStage fails. */
694 BKE_reportf(worker_status->reports,
695 RPT_ERROR,
696 "USD Export: unable to find suitable USD plugin to write %s",
697 data->unarchived_filepath);
698 return;
699 }
700
701 /* Traverse the point instancer to make sure the prototype referenced by nested point instancers
702 * are also marked as over. */
703 std::vector<pxr::UsdPrim> proto_list;
704 for (const pxr::UsdPrim &prim : usd_stage->Traverse()) {
705 if (!prim.IsA<pxr::UsdGeomPointInstancer>()) {
706 continue;
707 }
708 pxr::UsdGeomPointInstancer instancer(prim);
709 pxr::SdfPathVector targets;
710 if (instancer.GetPrototypesRel().GetTargets(&targets)) {
711 for (const pxr::SdfPath &wrapper_path : targets) {
713 instancer, usd_stage, wrapper_path, proto_list);
714 }
715 }
716 }
717
718 /* The standard way is to mark the point instancer's prototypes as over. Reference in OpenUSD:
719 * https://openusd.org/docs/api/class_usd_geom_point_instancer.html#:~:text=place%20them%20under%20a%20prim%20that%20is%20just%20an%20%22over%22
720 */
721 for (pxr::UsdPrim &proto : proto_list) {
722 proto.SetSpecifier(pxr::SdfSpecifierOver);
723 }
724
725 usd_stage->GetRootLayer()->Save();
726
727 data->export_ok = true;
728 worker_status->progress = 1.0f;
729 worker_status->do_update = true;
730}
731
733{
734 if (!BLI_exists(data->unarchived_filepath)) {
735 return;
736 }
737
738 char dir[FILE_MAX];
739 BLI_path_split_dir_part(data->unarchived_filepath, dir, FILE_MAX);
740
741 char usdc_temp_dir[FILE_MAX];
742 BLI_path_join(usdc_temp_dir, FILE_MAX, BKE_tempdir_session(), "USDZ", SEP_STR);
743
744 BLI_assert_msg(BLI_strcasecmp(dir, usdc_temp_dir) == 0,
745 "USD Export: Attempting to delete directory that doesn't match the expected "
746 "temporary directory for usdz export.");
747 BLI_delete(usdc_temp_dir, true, true);
748}
749
750static void export_endjob(void *customdata)
751{
752 ExportJobData *data = static_cast<ExportJobData *>(customdata);
753
754 DEG_graph_free(data->depsgraph);
755
756 if (data->targets_usdz()) {
757 /* NOTE: call to #perform_usdz_conversion has to be done here instead of the main threaded
758 * worker callback (#export_startjob) because USDZ conversion requires changing the current
759 * working directory. This is not safe to do from a non-main thread. Once the USD library fix
760 * this weird requirement, this call can be moved back at the end of #export_startjob, and not
761 * block the main user interface anymore. */
762 bool usd_conversion_success = perform_usdz_conversion(data);
763 if (!usd_conversion_success) {
764 data->export_ok = false;
765 }
766
768 }
769
770 if (!data->export_ok && BLI_exists(data->unarchived_filepath)) {
771 BLI_delete(data->unarchived_filepath, false, false);
772 }
773
774 G.is_rendering = false;
775 if (data->wm) {
776 WM_locked_interface_set(data->wm, false);
777 }
779}
780
786static void create_temp_path_for_usdz_export(const char *filepath, io::usd::ExportJobData *job)
787{
788 char usdc_file[FILE_MAX];
789 STRNCPY(usdc_file, BLI_path_basename(filepath));
790
791 if (BLI_path_extension_check(usdc_file, ".usdz")) {
792 BLI_path_extension_replace(usdc_file, sizeof(usdc_file), ".usdc");
793 }
794
795 char usdc_temp_filepath[FILE_MAX];
796 BLI_path_join(usdc_temp_filepath, FILE_MAX, BKE_tempdir_session(), "USDZ", usdc_file);
797
798 STRNCPY(job->unarchived_filepath, usdc_temp_filepath);
799 STRNCPY(job->usdz_filepath, filepath);
800}
801
802static void set_job_filepath(io::usd::ExportJobData *job, const char *filepath)
803{
804 if (BLI_path_extension_check_n(filepath, ".usdz", nullptr)) {
806 return;
807 }
808
809 STRNCPY(job->unarchived_filepath, filepath);
810 job->usdz_filepath[0] = '\0';
811}
812
814 const char *filepath,
815 const USDExportParams *params,
816 bool as_background_job,
817 ReportList *reports)
818{
819 if (!io::usd::export_params_valid(*params)) {
820 return false;
821 }
822
823 ViewLayer *view_layer = CTX_data_view_layer(C);
824 Scene *scene = CTX_data_scene(C);
825
826 io::usd::ExportJobData *job = MEM_new<io::usd::ExportJobData>("ExportJobData");
827
828 job->bmain = CTX_data_main(C);
829 job->wm = CTX_wm_manager(C);
830 job->scene = scene;
831 job->export_ok = false;
832 set_job_filepath(job, filepath);
833
835
836 job->depsgraph = DEG_graph_new(job->bmain, scene, view_layer, params->evaluation_mode);
837 job->params = *params;
838
839 /* Construct the depsgraph for exporting.
840 *
841 * Has to be done from main thread currently, as it may affect Main original data (e.g. when
842 * doing deferred update of the view-layers, see #112534 for details). */
843 if (job->params.collection[0]) {
844 Collection *collection = reinterpret_cast<Collection *>(
846 if (!collection) {
847 BKE_reportf(reports,
848 RPT_ERROR,
849 "USD Export: Unable to find collection '%s'",
850 job->params.collection);
851 return false;
852 }
853
855 }
856 else {
858 }
859
860 bool export_ok = false;
861 if (as_background_job) {
862 wmJob *wm_job = WM_jobs_get(job->wm,
864 scene,
865 "Exporting USD...",
868
869 /* setup job */
871 wm_job, job, [](void *j) { MEM_delete(static_cast<io::usd::ExportJobData *>(j)); });
874
876 }
877 else {
878 wmJobWorkerStatus worker_status = {};
879 /* Use the operator's reports in non-background case. */
880 worker_status.reports = reports;
881
882 io::usd::export_startjob(job, &worker_status);
884 export_ok = job->export_ok;
885
886 MEM_delete(job);
887 }
888
889 return export_ok;
890}
891
893{
894 /* USD 19.11 defines:
895 *
896 * #define PXR_MAJOR_VERSION 0
897 * #define PXR_MINOR_VERSION 19
898 * #define PXR_PATCH_VERSION 11
899 * #define PXR_VERSION 1911
900 *
901 * So the major version is implicit/invisible in the public version number.
902 */
903 return PXR_VERSION;
904}
905
907{
908 double result;
909 switch (params.convert_scene_units) {
911 result = 0.01;
912 break;
914 result = 0.001;
915 break;
917 result = 1000.0;
918 break;
920 result = 0.0254;
921 break;
922 case SceneUnits::Feet:
923 result = 0.3048;
924 break;
926 result = 0.9144;
927 break;
929 result = double(params.custom_meters_per_unit);
930 break;
931 default:
932 result = 1.0;
933 break;
934 }
935
936 return result;
937}
938
939} // namespace io::usd
940} // namespace blender
File and directory operations.
#define FILE_MAX
#define BLI_path_join(...)
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
Object groups, one object can be in many groups at once.
Read Blender memory allocation and freeing.
#define C
Definition RandGen.cpp:29
#define NC_SCENE
Definition WM_types.hh:391
#define ND_FRAME
Definition WM_types.hh:453
#define ELEM(...)
#define BLI_assert_msg(a, msg)
SIMD_FORCE_INLINE const btScalar & z() const
Return the z value.
Definition btQuadWord.h:117
float3x3 scale(float3x3 mat, float2 scale)
std::string image_cache_file_path()
void world_material_to_dome_light(const USDExportParams &params, const Scene *scene, pxr::UsdStageRefPtr stage)
static void collect_point_instancer_prototypes_and_set_extent(pxr::UsdGeomPointInstancer instancer, const pxr::UsdStageRefPtr &stage, const pxr::SdfPath &wrapper_path, std::vector< pxr::UsdPrim > &proto_list)
static bool perform_usdz_conversion(const ExportJobData *data)
std::string cache_image_color(const float color[4])
static void report_job_duration(const ExportJobData *data)
std::string get_image_cache_file(const std::string &file_name, bool mkdir)
static void write_root_accessibility_information(pxr::UsdStageRefPtr stage, const USDExportParams &params)
static bool export_params_valid(const USDExportParams &params)
static void export_endjob_usdz_cleanup(const ExportJobData *data)
static void set_job_filepath(io::usd::ExportJobData *job, const char *filepath)
void process_scene_graph_instances(const USDExportParams &export_params, pxr::UsdStageRefPtr stage)
void colorspace_apply_to_prim(const pxr::UsdPrim &prim)
bool USD_export(const bContext *C, const char *filepath, const USDExportParams *params, bool as_background_job, ReportList *reports)
static void ensure_root_prim(pxr::UsdStageRefPtr stage, const USDExportParams &params)
static void create_temp_path_for_usdz_export(const char *filepath, io::usd::ExportJobData *job)
static bool prim_path_valid(const std::string &path)
pxr::UsdStageRefPtr export_to_stage(const USDExportParams &params, Depsgraph *depsgraph, const char *filepath)
void call_export_hooks(Depsgraph *depsgraph, const USDHierarchyIterator *iter, ReportList *reports)
Definition usd_hook.cc:594
static void export_startjob(void *customdata, wmJobWorkerStatus *worker_status)
double get_meters_per_unit(const USDExportParams &params)
static void process_usdz_textures(const ExportJobData *data, const char *path)
static void export_endjob(void *customdata)
void register_hook_converters()
Definition usd_hook.cc:299
MatBase< T, NumCol, NumRow > transpose(const MatBase< T, NumRow, NumCol > &mat)
EulerXYZBase< float > EulerXYZ
Euler3Base< T > to_euler(const AxisAngleBase< T, AngleT > &axis_angle, EulerOrder order)
std::chrono::nanoseconds Nanoseconds
Definition BLI_timeit.hh:21
Clock::time_point TimePoint
Definition BLI_timeit.hh:20
void print_duration(Nanoseconds duration)
Definition timeit.cc:45
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
int char char int BLI_strcasecmp(const char *s1, const char *s2) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
void WM_global_reportf(eReportType type, const char *format,...)
void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph)
Definition scene.cc:2953
char * STRNCPY(char(&dst)[N], const char *src)
bool BKE_image_scale(Image *image, int width, int height, ImageUser *iuser)
ID * BKE_libblock_find_name(Main *bmain, short type, const char *name, const std::optional< Library * > lib=std::nullopt) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition lib_id.cc:1808
bool ED_editors_flush_edits(Main *bmain)
Definition ed_util.cc:335
void DEG_graph_build_from_view_layer(Depsgraph *graph)
void DEG_graph_build_from_collection(Depsgraph *graph, Collection *collection)
void WM_jobs_callbacks(wmJob *wm_job, wm_jobs_start_callback startjob, void(*initjob)(void *), void(*update)(void *), void(*endjob)(void *))
Definition wm_jobs.cc:407
bool BLI_change_working_dir(const char *dir)
Definition storage.cc:65
unsigned int uint
Definition BKE_text.h:55
unsigned int BLI_filelist_dir_contents(const char *dirname, struct direntry **r_filelist)
void DEG_graph_free(Depsgraph *graph)
Definition depsgraph.cc:307
void BKE_image_get_size(Image *image, ImageUser *iuser, int *r_width, int *r_height)
bool BLI_dir_create_recursive(const char *dirname) ATTR_NONNULL()
Definition fileops_c.cc:416
bool BLI_exists(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:404
@ WM_JOB_TYPE_USD_EXPORT
Definition WM_api.hh:2039
void IMB_rectfill(ImBuf *drect, const float col[4])
Definition rectop.cc:1165
Depsgraph * DEG_graph_new(Main *bmain, Scene *scene, ViewLayer *view_layer, eEvaluationMode mode)
Definition depsgraph.cc:279
size_t BLI_path_append(char *__restrict dst, size_t dst_maxncpy, const char *__restrict file) ATTR_NONNULL(1
wmWindow * CTX_wm_window(const bContext *C)
void WM_jobs_customdata_set(wmJob *wm_job, void *customdata, void(*free)(void *customdata))
Definition wm_jobs.cc:377
@ WM_JOB_PROGRESS
Definition WM_api.hh:1997
bool BKE_image_save_options_init(ImageSaveOptions *opts, Main *bmain, Scene *scene, Image *ima, ImageUser *iuser, bool guess_path, bool save_as_render)
Definition image_save.cc:51
const char * BKE_tempdir_session() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
Definition appdir.cc:1283
ViewLayer * CTX_data_view_layer(const bContext *C)
void WM_jobs_start(wmWindowManager *wm, wmJob *wm_job)
Definition wm_jobs.cc:498
Global G
Definition blender.cc:57
void WM_locked_interface_set(wmWindowManager *wm, bool lock)
bool IMB_save_image(ImBuf *ibuf, const char *filepath, ImBufFlags flags)
Definition writeimage.cc:40
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
void IMB_freeImBuf(ImBuf *ibuf)
Main * DEG_get_bmain(const Depsgraph *graph)
BMesh const char void * data
wmWindowManager * CTX_wm_manager(const bContext *C)
int BLI_delete(const char *path, bool dir, bool recursive) ATTR_NONNULL()
int BLI_path_move(const char *path_src, const char *path_dst) ATTR_NONNULL()
void BKE_scene_graph_update_tagged(Depsgraph *depsgraph, Main *bmain)
Definition scene.cc:2867
bool mat3_from_axis_conversion(int src_forward, int src_up, int dst_forward, int dst_up, float r_mat[3][3])
int BLI_path_slash_ensure(char *path, size_t path_maxncpy) ATTR_NONNULL(1)
bool BLI_path_extension_replace(char *path, size_t path_maxncpy, const char *ext) ATTR_NONNULL(1
MatBase< float, 3, 3 > float3x3
void BKE_id_free(Main *bmain, void *idv)
bool BLI_is_dir(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:457
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
void BLI_filelist_free(struct direntry *filelist, unsigned int nrentries)
void void void BLI_path_split_file_part(const char *filepath, char *file, size_t file_maxncpy) ATTR_NONNULL(1
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
Main * CTX_data_main(const bContext *C)
wmJob * WM_jobs_get(wmWindowManager *wm, wmWindow *win, const void *owner, const char *name, const eWM_JobFlag flag, const eWM_JobType job_type)
Definition wm_jobs.cc:228
bool BLI_path_extension_check(const char *path, const char *ext) ATTR_NONNULL(1
void BKE_image_save_options_free(ImageSaveOptions *opts)
Scene * DEG_get_input_scene(const Depsgraph *graph)
void BLI_path_split_dir_file(const char *filepath, char *dir, size_t dir_maxncpy, char *file, size_t file_maxncpy) ATTR_NONNULL(1
static CLG_LogRef LOG
Definition logging.cpp:12
Scene * CTX_data_scene(const bContext *C)
char * BLI_current_working_dir(char *dir, size_t maxncpy) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:83
void WM_jobs_timer(wmJob *wm_job, double time_step, uint note, uint endnote, void(*timer_step)(void *))
Definition wm_jobs.cc:393
bool BLI_path_extension_check_n(const char *path,...) ATTR_NONNULL(1) ATTR_SENTINEL(0)
const char * BKE_blender_version_string()
Definition blender.cc:147
bool BKE_image_save(ReportList *reports, Main *bmain, Image *ima, ImageUser *iuser, const ImageSaveOptions *opts)
Image * BKE_image_load(Main *bmain, const char *filepath, bool check_open=true)
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
ImbFormatOptions foptions
eImbFileType ftype
const c_style_mat & ptr() const
struct UnitSettings unit
struct RenderData r
const char * export_filepath() const
char collection[MAX_ID_NAME - 2]
Definition usd.hh:171
enum eEvaluationMode evaluation_mode
Definition usd.hh:149
SubdivExportMode export_subdiv
Definition usd.hh:148
wmJobWorkerStatus * worker_status
Definition usd.hh:184
std::string accessibility_description
Definition usd.hh:175
#define SEP_STR
Definition unit.cc:41