Blender V5.3
usd_light_convert.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
6
7#include "usd.hh"
8#include "usd_asset_utils.hh"
10#include "usd_private.hh"
11#include "usd_utils.hh"
13
14#include <pxr/base/gf/rotation.h>
15#include <pxr/base/gf/vec3f.h>
16#include <pxr/usd/usdGeom/metrics.h>
17#include <pxr/usd/usdGeom/tokens.h>
18#include <pxr/usd/usdGeom/xformCache.h>
19#include <pxr/usd/usdGeom/xformCommonAPI.h>
20#include <pxr/usd/usdLux/domeLight.h>
21#include <pxr/usd/usdLux/tokens.h>
22
23#include "BKE_image.hh"
24#include "BKE_library.hh"
25#include "BKE_main.hh"
26#include "BKE_node.hh"
28#include "BKE_node_runtime.hh"
30
31#include "BLI_fileops.hh"
32#include "BLI_math_vector_c.hh"
33#include "BLI_path_utils.hh"
34#include "BLI_span.hh"
35#include "BLI_string_ref.hh"
36#include "BLI_string_utils.hh"
37#include "BLI_utildefines.hh"
38
39#include "DNA_image_types.h"
40#include "DNA_node_types.h"
41#include "DNA_scene_types.h"
42#include "DNA_world_types.h"
43
44#include <cmath>
45#include <string>
46
47#include "CLG_log.h"
48
49namespace blender {
50
51static CLG_LogRef LOG = {"io.usd"};
52
53namespace usdtokens {
54// Attribute values.
55static const pxr::TfToken pole_axis_z("Z", pxr::TfToken::Immortal);
56} // namespace usdtokens
57
58namespace {
59
60struct WorldNtreeSearchPayload {
61 const io::usd::USDExportParams &params;
62 pxr::UsdStageRefPtr stage;
63
64 WorldNtreeSearchPayload(const io::usd::USDExportParams &in_params, pxr::UsdStageRefPtr in_stage)
65 : params(in_params), stage(in_stage)
66 {
67 }
68};
69
70} // End anonymous namespace.
71
72namespace io::usd {
73
78static Image *load_image(std::string tex_path, Main *bmain, const USDImportParams &params)
79{
80 /* Optionally copy the asset if it's inside a USDZ package. */
81 const bool import_textures = params.import_textures_mode != TexImportMode::None &&
82 should_import_asset(tex_path);
83
84 std::string imported_file_source_path = tex_path;
85
86 if (import_textures) {
87 /* If we are packing the imported textures, we first write them
88 * to a temporary directory. */
89 const char *textures_dir = params.import_textures_mode == TexImportMode::Pack ?
92
93 const TexNameCollisionMode name_collision_mode = params.import_textures_mode ==
97
98 tex_path = import_asset(tex_path, textures_dir, name_collision_mode, nullptr);
99 }
100
101 Image *image = BKE_image_load_exists(bmain, tex_path.c_str());
102 if (!image) {
103 return nullptr;
104 }
105
106 if (import_textures && imported_file_source_path != tex_path) {
107 ensure_usd_source_path_prop(imported_file_source_path, &image->id);
108 }
109
110 if (import_textures && params.import_textures_mode == TexImportMode::Pack &&
112 {
113 BKE_image_packfiles(nullptr, image, ID_BLEND_PATH(bmain, &image->id));
115 BLI_delete(temp_textures_dir(), true, true);
116 }
117 }
118
119 return image;
120}
121
122/* Create a new node of type 'new_node_type' and connect it
123 * as an upstream source to 'dst_node' with the given sockets. */
124static bNode *append_node(bNode *dst_node,
125 int new_node_type,
126 const StringRef out_sock,
127 const StringRef in_sock,
128 bNodeTree *ntree,
129 float offset)
130{
131 bNode *src_node = bke::node_add_static_node(nullptr, *ntree, new_node_type);
132 bke::node_add_link(*ntree,
133 *src_node,
134 *bke::node_find_socket(*src_node, SOCK_OUT, UString(out_sock)),
135 *dst_node,
136 *bke::node_find_socket(*dst_node, SOCK_IN, UString(in_sock)));
137
138 src_node->location[0] = dst_node->location[0] - offset;
139 src_node->location[1] = dst_node->location[1];
140
141 return src_node;
142}
143
145 const Scene *scene,
146 pxr::UsdStageRefPtr stage)
147{
148 if (!(stage && scene && scene->world)) {
149 return;
150 }
151
154
155 if (!(res.color_found || res.image)) {
156 /* No nodes to convert */
157 return;
158 }
159
160 std::string image_filepath;
161 if (res.image) {
162 /* Compute image filepath and export if needed. */
163 image_filepath = get_tex_image_asset_filepath(res.image, stage, params);
164 if (image_filepath.empty()) {
165 return;
166 }
167 if (params.export_textures) {
168 export_texture(res.image, stage, params.overwrite_textures);
169 }
170 }
171
172 /* Create USD dome light. */
173 pxr::SdfPath env_light_path = get_unique_path(stage, params.root_prim_path + "/env_light");
174 pxr::UsdLuxDomeLight dome_light = pxr::UsdLuxDomeLight::Define(stage, env_light_path);
175 colorspace_apply_to_prim(dome_light.GetPrim());
176
177 if (res.image) {
178 /* Use existing image texture file. */
179 dome_light.CreateTextureFileAttr().Set(pxr::SdfAssetPath(image_filepath));
180
181 /* Set optional color multiplication. */
182 if (res.mult_found) {
183 pxr::GfVec3f color_val(res.color_mult[0], res.color_mult[1], res.color_mult[2]);
184 dome_light.CreateColorAttr().Set(color_val);
185 }
186
187 /* Set transform. */
188 pxr::GfVec3d angles = res.transform.DecomposeRotation(
189 pxr::GfVec3d::ZAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::XAxis());
190 pxr::GfVec3f rot_vec(angles[2], angles[1], angles[0]);
191 pxr::UsdGeomXformCommonAPI xform_api(dome_light);
192 xform_api.SetRotate(rot_vec, pxr::UsdGeomXformCommonAPI::RotationOrderXYZ);
193 }
194 else if (res.color_found) {
195 /* If no texture is found export a solid color texture as a stand-in so that Hydra
196 * renderers don't throw errors. */
197 dome_light.CreateIntensityAttr().Set(res.intensity);
198
199 std::string source_path = cache_image_color(res.color);
200 const std::string base_path = stage->GetRootLayer()->GetRealPath();
201
202 char file_name[FILE_MAX];
203 BLI_path_split_file_part(source_path.c_str(), file_name, FILE_MAX);
204 char dest_path[FILE_MAX];
205 BLI_path_split_dir_part(base_path.c_str(), dest_path, FILE_MAX);
206
207 BLI_path_append_dir(dest_path, FILE_MAX, "textures");
208 BLI_dir_create_recursive(dest_path);
209
210 BLI_path_append(dest_path, FILE_MAX, file_name);
211
212 if (BLI_copy(source_path.c_str(), dest_path) != 0) {
213 CLOG_WARN(&LOG, "USD Export: Couldn't write world color image to %s", dest_path);
214 }
215 else {
216 BLI_path_join(dest_path, FILE_MAX, ".", "textures", file_name);
217 BLI_string_replace_char(dest_path, '\\', '/');
218 dome_light.CreateTextureFileAttr().Set(pxr::SdfAssetPath(dest_path));
219 }
220 }
221}
222
223/* Import the dome light as a world material. */
224
226 Scene *scene,
227 Main *bmain,
228 const USDImportDomeLightData &dome_light_data,
229 const pxr::UsdPrim &prim,
230 const pxr::UsdTimeCode time)
231{
232 if (!(scene && scene->world && prim)) {
233 return;
234 }
235
236 bNodeTree *ntree = scene->world->nodetree;
237 BLI_assert(ntree != nullptr);
238 bNode *output = nullptr;
239 bNode *bgshader = nullptr;
240
241 /* We never delete existing nodes, but we might disconnect them
242 * and move them out of the way. */
243
244 /* Look for the output and background shader nodes, which we will reuse. */
245 for (bNode *node : ntree->all_nodes()) {
246 if (node->type_legacy == SH_NODE_OUTPUT_WORLD) {
247 output = node;
248 }
249 else if (node->type_legacy == SH_NODE_BACKGROUND) {
250 bgshader = node;
251 }
252 else {
253 /* Move existing node out of the way. */
254 node->location[1] += 300;
255 }
256 }
257
258 /* Create the output and background shader nodes, if they don't exist. */
259 if (!output) {
261 output->location[0] = 300.0f;
262 output->location[1] = 300.0f;
263 }
264
265 if (!bgshader) {
266 bgshader = append_node(output, SH_NODE_BACKGROUND, "Background", "Surface", ntree, 200);
267
268 /* Set the default background color. */
269 bNodeSocket *color_sock = bke::node_find_socket(*bgshader, SOCK_IN, "Color"_ustr);
270 copy_v3_v3(color_sock->default_value_typed<bNodeSocketValueRGBA>()->value,
271 &scene->world->horr);
272 }
273
274 /* Make sure the first input to the shader node is disconnected. */
275 bNodeSocket *shader_input = bke::node_find_socket(*bgshader, SOCK_IN, "Color"_ustr);
276
277 if (shader_input && shader_input->link) {
278 bke::node_remove_link(ntree, *shader_input->link);
279 }
280
281 /* Set the background shader intensity. */
282 float intensity = dome_light_data.intensity * params.light_intensity_scale;
283
284 bNodeSocket *strength_sock = bke::node_find_socket(*bgshader, SOCK_IN, "Strength"_ustr);
285 strength_sock->default_value_typed<bNodeSocketValueFloat>()->value = intensity;
286
287 if (!dome_light_data.has_tex) {
288 /* No texture file is authored on the dome light. Set the color, if it was authored,
289 * and return early. */
290 if (dome_light_data.has_color) {
291 bNodeSocket *color_sock = bke::node_find_socket(*bgshader, SOCK_IN, "Color"_ustr);
292 copy_v3_v3(color_sock->default_value_typed<bNodeSocketValueRGBA>()->value,
293 dome_light_data.color.data());
294 }
295
298
299 return;
300 }
301
302 /* If the light has authored color, create a color multiply node for the environment
303 * texture output. */
304 bNode *mult = nullptr;
305
306 if (dome_light_data.has_color) {
307 mult = append_node(bgshader, SH_NODE_VECTOR_MATH, "Vector", "Color", ntree, 200);
309
310 /* Set the color in the vector math node's second socket. */
311 bNodeSocket *vec_sock = bke::node_find_socket(*mult, SOCK_IN, "Vector"_ustr);
312 if (vec_sock) {
313 vec_sock = vec_sock->next;
314 }
315
316 if (vec_sock) {
317 copy_v3_v3(vec_sock->default_value_typed<bNodeSocketValueVector>()->value,
318 dome_light_data.color.data());
319 }
320 else {
321 CLOG_WARN(&LOG, "Couldn't find vector multiply second vector socket");
322 }
323 }
324
325 bNode *tex = nullptr;
326
327 /* Append an environment texture node to the mult node, if it was created, or directly to
328 * the background shader. */
329 if (mult) {
330 tex = append_node(mult, SH_NODE_TEX_ENVIRONMENT, "Color", "Vector", ntree, 400);
331 }
332 else {
333 tex = append_node(bgshader, SH_NODE_TEX_ENVIRONMENT, "Color", "Color", ntree, 400);
334 }
335
336 bNode *mapping = append_node(tex, SH_NODE_MAPPING, "Vector", "Vector", ntree, 200);
337
338 append_node(mapping, SH_NODE_TEX_COORD, "Generated", "Vector", ntree, 200);
339
340 /* Load the texture image. */
341 const std::string &resolved_path = dome_light_data.tex_path.GetResolvedPath();
342 if (resolved_path.empty()) {
343 CLOG_WARN(&LOG,
344 "Couldn't get resolved path for asset %s",
345 dome_light_data.tex_path.GetAssetPath().c_str());
346 return;
347 }
348
349 Image *image = load_image(resolved_path, bmain, params);
350 if (!image) {
351 CLOG_WARN(&LOG, "Couldn't load image file %s", resolved_path.c_str());
352 return;
353 }
354
355 tex->id = &image->id;
356
357 /* Set the transform. */
358 pxr::UsdGeomXformCache xf_cache(time);
359 pxr::GfMatrix4d xf = xf_cache.GetLocalToWorldTransform(prim);
360
361 pxr::UsdStageRefPtr stage = prim.GetStage();
362
363 if (!stage) {
364 CLOG_WARN(&LOG, "Couldn't get stage for dome light %s", prim.GetPath().GetText());
365 return;
366 }
367
368 /* Note: This logic tries to produce identical results to `usdview` as of USD 25.05.
369 * However, `usdview` seems to handle Y-Up stages differently; some scenes match while others
370 * do not unless we keep the second conditional below (+90 on x-axis). */
371 const pxr::TfToken stage_up = pxr::UsdGeomGetStageUpAxis(stage);
372 const bool needs_stage_z_adjust = stage_up == pxr::UsdGeomTokens->z &&
373 ELEM(dome_light_data.pole_axis,
374 pxr::UsdLuxTokens->Z,
375 pxr::UsdLuxTokens->scene);
376 const bool needs_stage_y_adjust = stage_up == pxr::UsdGeomTokens->y &&
377 ELEM(dome_light_data.pole_axis, pxr::UsdLuxTokens->Z);
378 if (needs_stage_z_adjust || needs_stage_y_adjust) {
379 xf *= pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(0.0, 1.0, 0.0), 90.0));
380 }
381 else if (stage_up == pxr::UsdGeomTokens->y) {
382 /* Convert from Y-up to Z-up with a 90 degree rotation about the X-axis. */
383 xf *= pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(1.0, 0.0, 0.0), 90.0));
384 }
385
386 /* Rotate into Blender's frame of reference. */
387 xf = pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(0.0, 0.0, 1.0), -90.0)) *
388 pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(1.0, 0.0, 0.0), -90.0)) * xf;
389
390 pxr::GfVec3d angles = xf.DecomposeRotation(
391 pxr::GfVec3d::XAxis(), pxr::GfVec3d::YAxis(), pxr::GfVec3d::ZAxis());
392 pxr::GfVec3f rot_vec(-angles[0], -angles[1], -angles[2]);
393
394 /* Convert degrees to radians. */
395 rot_vec *= M_PI / 180.0f;
396
397 if (bNodeSocket *socket = bke::node_find_socket(*mapping, SOCK_IN, "Rotation"_ustr)) {
398 bNodeSocketValueVector *rot_value = static_cast<bNodeSocketValueVector *>(
399 socket->default_value);
400 copy_v3_v3(rot_value->value, rot_vec.data());
401 }
402
406}
407
408static bool node_search(bNode *fromnode, bNode * /*tonode*/, void *userdata, bool /*reversed*/)
409{
410 if (!(userdata && fromnode)) {
411 return true;
412 }
413
414 WorldToDomeLight &res = *static_cast<WorldToDomeLight *>(userdata);
415
416 if (!res.color_found && fromnode->type_legacy == SH_NODE_BACKGROUND) {
417 /* Get light color and intensity */
419 *fromnode, SOCK_IN, "Color"_ustr)
420 ->default_value_typed<bNodeSocketValueRGBA>();
421 const bNodeSocketValueFloat *strength_data =
422 bke::node_find_socket(*fromnode, SOCK_IN, "Strength"_ustr)
423 ->default_value_typed<bNodeSocketValueFloat>();
424
425 res.color_found = true;
426 res.intensity = strength_data->value;
427 res.color[0] = color_data->value[0];
428 res.color[1] = color_data->value[1];
429 res.color[2] = color_data->value[2];
430 res.color[3] = 1.0f;
431 }
432 else if (!res.image && fromnode->type_legacy == SH_NODE_TEX_ENVIRONMENT) {
433 NodeTexImage *tex = static_cast<NodeTexImage *>(fromnode->storage);
434 res.image = reinterpret_cast<Image *>(fromnode->id);
435 res.iuser = &tex->iuser;
436
437 /* Always adjust for rotational differences between Blender and USD. */
438 res.transform =
439 pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(1.0, 0.0, 0.0), 90.0)) *
440 pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(0.0, 0.0, 1.0), 90.0));
441 }
442 else if (!res.image && !res.mult_found && fromnode->type_legacy == SH_NODE_VECTOR_MATH) {
443 if (fromnode->custom1 == NODE_VECTOR_MATH_MULTIPLY) {
444 res.mult_found = true;
445
446 bNodeSocket *vec_sock = bke::node_find_socket(*fromnode, SOCK_IN, "Vector"_ustr);
447 if (vec_sock) {
448 vec_sock = vec_sock->next;
449 }
450
451 if (vec_sock) {
452 copy_v3_v3(res.color_mult, vec_sock->default_value_typed<bNodeSocketValueVector>()->value);
453 }
454 }
455 }
456 else if (res.image && fromnode->type_legacy == SH_NODE_MAPPING) {
457 if (bNodeSocket *socket = bke::node_find_socket(*fromnode, SOCK_IN, "Rotation"_ustr)) {
458 const bNodeSocketValueVector *rot_value =
459 socket->default_value_typed<bNodeSocketValueVector>();
460 /* Convert radians to degrees. */
461 pxr::GfVec3f rot(rot_value->value);
462 rot *= 180.0f / M_PI;
463
464 res.transform *=
465 pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(0.0, 0.0, 1.0), -rot[2])) *
466 pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(0.0, 1.0, 0.0), -rot[1])) *
467 pxr::GfMatrix4d().SetRotate(pxr::GfRotation(pxr::GfVec3d(1.0, 0.0, 0.0), -rot[0]));
468 }
469 }
470 return true;
471}
472
474{
475 /* Find the world output. */
476 scene->world->nodetree->ensure_topology_cache();
477 const Span<const bNode *> bsdf_nodes = scene->world->nodetree->nodes_by_type(
478 "ShaderNodeOutputWorld"_ustr);
479
480 for (const bNode *node : bsdf_nodes) {
481 if (node->flag & NODE_DO_OUTPUT) {
482 bke::node_chain_iterator(scene->world->nodetree, node, node_search, &res, true);
483 break;
484 }
485 }
486}
487
488} // namespace io::usd
489} // namespace blender
#define SH_NODE_OUTPUT_WORLD
#define SH_NODE_TEX_COORD
#define SH_NODE_VECTOR_MATH
#define SH_NODE_TEX_ENVIRONMENT
#define SH_NODE_BACKGROUND
#define SH_NODE_MAPPING
File and directory operations.
#define M_PI
#define FILE_MAX
#define BLI_path_join(...)
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define ID_BLEND_PATH(_bmain, _id)
Definition DNA_ID.h:688
#define ELEM(...)
#define output
SIMD_FORCE_INLINE void mult(const btTransform &t1, const btTransform &t2)
Set the current transform as the value of the product of two transforms.
Definition btTransform.h:76
UString()=default
#define rot(x, k)
void node_remove_link(bNodeTree *ntree, bNodeLink &link)
Definition node.cc:4676
void node_chain_iterator(const bNodeTree *ntree, const bNode *node_start, bool(*callback)(bNode *, bNode *, void *, const bool), void *userdata, bool reversed)
Definition node.cc:4125
bNode * node_add_static_node(const bContext *C, bNodeTree &ntree, int type)
Definition node.cc:4283
bNodeLink & node_add_link(bNodeTree &ntree, bNode &fromnode, bNodeSocket &fromsock, bNode &tonode, bNodeSocket &tosock)
Definition node.cc:4638
bNodeSocket * node_find_socket(bNode &node, eNodeSocketInOut in_out, UString identifier)
Definition node.cc:3036
void node_set_active(bNodeTree &ntree, bNode &node)
Definition node.cc:5484
void world_material_to_dome_light(const USDExportParams &params, const Scene *scene, pxr::UsdStageRefPtr stage)
const char * temp_textures_dir()
bool should_import_asset(const std::string &path)
static Image * load_image(std::string tex_path, Main *bmain, const USDImportParams &params)
pxr::SdfPath get_unique_path(pxr::UsdStageRefPtr stage, const std::string &path)
Definition usd_utils.cc:109
void dome_light_to_world_material(const USDImportParams &params, Scene *scene, Main *bmain, const USDImportDomeLightData &dome_light_data, const pxr::UsdPrim &prim, const pxr::UsdTimeCode time)
std::string cache_image_color(const float color[4])
static bool node_search(bNode *fromnode, bNode *, void *userdata, bool)
void export_texture(Image *ima, const pxr::UsdStageRefPtr stage, const bool allow_overwrite, ReportList *reports)
std::string get_tex_image_asset_filepath(Image *ima, const pxr::UsdStageRefPtr stage, const USDExportParams &export_params)
std::string import_asset(const std::string &src, const char *import_dir, TexNameCollisionMode name_collision_mode, ReportList *reports)
void colorspace_apply_to_prim(const pxr::UsdPrim &prim)
void ensure_usd_source_path_prop(const std::string &path, ID *id)
static bNode * append_node(bNode *dst_node, int new_node_type, const StringRef out_sock, const StringRef in_sock, bNodeTree *ntree, float offset)
static const pxr::TfToken pole_axis_z("Z", pxr::TfToken::Immortal)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
MINLINE void copy_v3_v3(float r[3], const float a[3])
bool BLI_dir_create_recursive(const char *dirname) ATTR_NONNULL()
Definition fileops_c.cc:416
void BLI_string_replace_char(char *str, char src, char dst) ATTR_NONNULL(1)
size_t size_t BLI_path_append_dir(char *__restrict dst, size_t dst_maxncpy, const char *__restrict dir) ATTR_NONNULL(1
size_t BLI_path_append(char *__restrict dst, size_t dst_maxncpy, const char *__restrict file) ATTR_NONNULL(1
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
Image * BKE_image_load_exists(Main *bmain, const char *filepath, bool check_open=true, bool *r_exists=nullptr)
void DEG_id_tag_update(ID *id, unsigned int flags)
int BLI_delete(const char *path, bool dir, bool recursive) ATTR_NONNULL()
void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
void BKE_ntree_update_after_single_tree_change(Main &bmain, bNodeTree &modified_tree, const NodeTreeUpdateExtraParams &params={})
bool BLI_is_dir(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:457
int BLI_copy(const char *path_src, const char *path_dst) ATTR_NONNULL()
void void void BLI_path_split_file_part(const char *filepath, char *file, size_t file_maxncpy) ATTR_NONNULL(1
@ ID_RECALC_NTREE_OUTPUT
Definition DNA_ID.h:1155
static CLG_LogRef LOG
Definition logging.cpp:12
@ NODE_VECTOR_MATH_MULTIPLY
bool BKE_image_has_packedfile(const Image *image)
struct World * world
struct bNodeLink * link
struct bNodeSocket * next
TexImportMode import_textures_mode
Definition usd.hh:231
TexNameCollisionMode tex_name_collision_mode
Definition usd.hh:235