Blender V5.3
usd_writer_material.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#include "usd_asset_utils.hh"
9#include "usd_hook.hh"
10#include "usd_utils.hh"
11
12#include "BKE_image.hh"
13#include "BKE_image_format.hh"
14#include "BKE_library.hh"
15#include "BKE_main.hh"
16#include "BKE_node.hh"
18#include "BKE_node_runtime.hh"
19#include "BKE_report.hh"
20
22#include "IMB_imbuf.hh"
23
24#include "BLI_fileops.hh"
26#include "BLI_map.hh"
27#include "BLI_path_utils.hh"
28#include "BLI_set.hh"
29#include "BLI_string.hh"
30#include "BLI_string_ref.hh"
31#include "BLI_string_utils.hh"
32
33#include "DNA_material_types.h"
34#include "DNA_node_types.h"
36
37#include "MEM_guardedalloc.h"
38
39#include "WM_types.hh"
40
41#include <pxr/base/tf/stringUtils.h>
42
43#ifdef WITH_MATERIALX
45# include <pxr/usd/sdf/copyUtils.h>
46# include <pxr/usd/usdMtlx/materialXConfigAPI.h>
47# include <pxr/usd/usdMtlx/reader.h>
48#endif
49
50#include "CLG_log.h"
51
52namespace blender {
53
54static CLG_LogRef LOG = {"io.usd"};
55
56/* `TfToken` objects are not cheap to construct, so we do it once. */
57namespace usdtokens {
58/* Materials. */
59static const pxr::TfToken clearcoat("clearcoat", pxr::TfToken::Immortal);
60static const pxr::TfToken clearcoatRoughness("clearcoatRoughness", pxr::TfToken::Immortal);
61static const pxr::TfToken diffuse_color("diffuseColor", pxr::TfToken::Immortal);
62static const pxr::TfToken emissive_color("emissiveColor", pxr::TfToken::Immortal);
63static const pxr::TfToken metallic("metallic", pxr::TfToken::Immortal);
64static const pxr::TfToken preview_shader("previewShader", pxr::TfToken::Immortal);
65static const pxr::TfToken preview_surface("UsdPreviewSurface", pxr::TfToken::Immortal);
66static const pxr::TfToken UsdTransform2d("UsdTransform2d", pxr::TfToken::Immortal);
67static const pxr::TfToken uv_texture("UsdUVTexture", pxr::TfToken::Immortal);
68static const pxr::TfToken primvar_float("UsdPrimvarReader_float", pxr::TfToken::Immortal);
69static const pxr::TfToken primvar_float2("UsdPrimvarReader_float2", pxr::TfToken::Immortal);
70static const pxr::TfToken primvar_float3("UsdPrimvarReader_float3", pxr::TfToken::Immortal);
71static const pxr::TfToken primvar_vector("UsdPrimvarReader_vector", pxr::TfToken::Immortal);
72static const pxr::TfToken roughness("roughness", pxr::TfToken::Immortal);
73static const pxr::TfToken specular("specular", pxr::TfToken::Immortal);
74static const pxr::TfToken opacity("opacity", pxr::TfToken::Immortal);
75static const pxr::TfToken opacityThreshold("opacityThreshold", pxr::TfToken::Immortal);
76static const pxr::TfToken surface("surface", pxr::TfToken::Immortal);
77static const pxr::TfToken displacement("displacement", pxr::TfToken::Immortal);
78static const pxr::TfToken rgb("rgb", pxr::TfToken::Immortal);
79static const pxr::TfToken r("r", pxr::TfToken::Immortal);
80static const pxr::TfToken g("g", pxr::TfToken::Immortal);
81static const pxr::TfToken b("b", pxr::TfToken::Immortal);
82static const pxr::TfToken a("a", pxr::TfToken::Immortal);
83static const pxr::TfToken st("st", pxr::TfToken::Immortal);
84static const pxr::TfToken result("result", pxr::TfToken::Immortal);
85static const pxr::TfToken varname("varname", pxr::TfToken::Immortal);
86static const pxr::TfToken out("out", pxr::TfToken::Immortal);
87static const pxr::TfToken normal("normal", pxr::TfToken::Immortal);
88static const pxr::TfToken ior("ior", pxr::TfToken::Immortal);
89static const pxr::TfToken file("file", pxr::TfToken::Immortal);
90static const pxr::TfToken raw("raw", pxr::TfToken::Immortal);
91static const pxr::TfToken scale("scale", pxr::TfToken::Immortal);
92static const pxr::TfToken bias("bias", pxr::TfToken::Immortal);
93static const pxr::TfToken sRGB("sRGB", pxr::TfToken::Immortal);
94static const pxr::TfToken sourceColorSpace("sourceColorSpace", pxr::TfToken::Immortal);
95static const pxr::TfToken black("black", pxr::TfToken::Immortal);
96static const pxr::TfToken clamp("clamp", pxr::TfToken::Immortal);
97static const pxr::TfToken repeat("repeat", pxr::TfToken::Immortal);
98static const pxr::TfToken mirror("mirror", pxr::TfToken::Immortal);
99static const pxr::TfToken wrapS("wrapS", pxr::TfToken::Immortal);
100static const pxr::TfToken wrapT("wrapT", pxr::TfToken::Immortal);
101static const pxr::TfToken in("in", pxr::TfToken::Immortal);
102static const pxr::TfToken translation("translation", pxr::TfToken::Immortal);
103static const pxr::TfToken rotation("rotation", pxr::TfToken::Immortal);
104} // namespace usdtokens
105
106namespace io::usd {
107
108/* Preview surface input specification. */
109struct InputSpec {
110 pxr::TfToken input_name;
111 pxr::SdfValueTypeName input_type;
112 /* Whether a default value should be set
113 * if the node socket has not input. Usually
114 * false for the Normal input. */
116};
117
118/* Map Blender socket names to USD Preview Surface InputSpec structs. */
120
121/* Static function forward declarations. */
122static pxr::UsdShadeShader create_usd_preview_shader(const USDExporterContext &usd_export_context,
123 const pxr::UsdShadeMaterial &material,
124 const StringRef name,
125 int type);
126static pxr::UsdShadeShader create_usd_preview_shader(const USDExporterContext &usd_export_context,
127 const pxr::UsdShadeMaterial &material,
128 const bNode *node);
129static pxr::UsdShadeShader create_primvar_reader_shader(
130 const USDExporterContext &usd_export_context,
131 const pxr::UsdShadeMaterial &material,
132 const pxr::TfToken &primvar_type,
133 const bNode *node);
134static void create_uv_input(const USDExporterContext &usd_export_context,
135 const bNodeSocket *input_socket,
136 pxr::UsdShadeMaterial &usd_material,
137 pxr::UsdShadeInput &usd_input,
138 const std::string &active_uvmap_name,
139 ReportList *reports);
140static void export_texture(const USDExporterContext &usd_export_context, bNode *node);
141static bNode *find_bsdf_node(const Material *material);
142static bNode *find_displacement_node(const Material *material);
143static void get_absolute_path(const Image *ima, char *r_path);
144static std::string get_tex_image_asset_filepath(const USDExporterContext &usd_export_context,
145 const bNode *node);
147static const bNodeLink *traverse_channel(const bNodeSocket *input, short target_type);
148
149void set_transmission_opacity_range(pxr::UsdShadeShader &usd_shader,
150 const InputSpec &input_spec,
151 const pxr::TfToken &source_name);
152void set_normal_texture_range(pxr::UsdShadeShader &usd_shader, const InputSpec &input_spec);
153
154/* Create an input on the given shader with name and type
155 * provided by the InputSpec and assign the given value to the
156 * input. Parameters T1 and T2 indicate the Blender and USD
157 * value types, respectively. */
158template<typename T>
159void create_input(pxr::UsdShadeShader &shader, const InputSpec &spec, const T &value, float scale)
160{
161 shader.CreateInput(spec.input_name, spec.input_type).Set(scale * value);
162}
163
164static void set_scale_bias(pxr::UsdShadeShader &usd_shader,
165 const pxr::GfVec4f scale,
166 const pxr::GfVec4f bias)
167{
168 pxr::UsdShadeInput scale_attr = usd_shader.GetInput(usdtokens::scale);
169 if (!scale_attr) {
170 scale_attr = usd_shader.CreateInput(usdtokens::scale, pxr::SdfValueTypeNames->Float4);
171 }
172 scale_attr.Set(scale);
173
174 pxr::UsdShadeInput bias_attr = usd_shader.GetInput(usdtokens::bias);
175 if (!bias_attr) {
176 bias_attr = usd_shader.CreateInput(usdtokens::bias, pxr::SdfValueTypeNames->Float4);
177 }
178 bias_attr.Set(bias);
179}
180
181static void process_inputs(const USDExporterContext &usd_export_context,
182 pxr::UsdShadeMaterial &usd_material,
183 pxr::UsdShadeShader &shader,
184 const bNode *node,
185 const std::string &active_uvmap_name,
186 ReportList *reports)
187{
188 const InputSpecMap &input_map = preview_surface_input_map();
189
190 for (bNodeSocket &sock : node->inputs) {
191 /* Check if this socket is mapped to a USD preview shader input. */
192 const InputSpec *spec = input_map.lookup_ptr(sock.name);
193 if (spec == nullptr) {
194 continue;
195 }
196
197 const InputSpec &input_spec = *spec;
198
199 /* Allow scaling inputs. */
200 float input_scale = 1.0;
201
202 /* Don't export emission color if strength is zero. */
203 if (input_spec.input_name == usdtokens::emissive_color) {
204 const bNodeSocket *emission_strength_sock = bke::node_find_socket(
205 *node, SOCK_IN, "Emission Strength"_ustr);
206 if (!emission_strength_sock) {
207 continue;
208 }
209
210 input_scale = emission_strength_sock->default_value_typed<bNodeSocketValueFloat>()->value;
211 if (input_scale == 0.0f) {
212 continue;
213 }
214 }
215
216 bool processed = false;
217
218 /* Check for an upstream Image node. */
219 const bNodeLink *input_link = traverse_channel(&sock, SH_NODE_TEX_IMAGE);
220 if (input_link) {
221 /* Convert the texture image node connected to this input. */
222 bNode *input_node = input_link->fromnode;
223 pxr::UsdShadeShader usd_shader = create_usd_preview_shader(
224 usd_export_context, usd_material, input_node);
225
226 /* Create the UsdUVTexture node output attribute that should be connected to this input. */
227 pxr::TfToken source_name;
228 if (input_spec.input_type == pxr::SdfValueTypeNames->Float) {
229 /* If the input is a float, we check if there is also a Separate Color node in between, if
230 * there is use the output channel from that, otherwise connect either the texture alpha or
231 * red channels. */
232 const bNodeLink *input_link_sep_color = traverse_channel(&sock, SH_NODE_SEPARATE_COLOR);
233 if (input_link_sep_color) {
234 if (STREQ(input_link_sep_color->fromsock->identifier, "Red")) {
235 source_name = usdtokens::r;
236 }
237 if (STREQ(input_link_sep_color->fromsock->identifier, "Green")) {
238 source_name = usdtokens::g;
239 }
240 if (STREQ(input_link_sep_color->fromsock->identifier, "Blue")) {
241 source_name = usdtokens::b;
242 }
243 }
244 else {
245 source_name = STREQ(input_link->fromsock->identifier, "Alpha") ? usdtokens::a :
247 }
248 usd_shader.CreateOutput(source_name, pxr::SdfValueTypeNames->Float);
249 }
250 else {
251 source_name = usdtokens::rgb;
252 usd_shader.CreateOutput(usdtokens::rgb, pxr::SdfValueTypeNames->Float3);
253 }
254
255 /* Create the preview surface input and connect it to the shader. */
256 pxr::UsdShadeConnectionSourceInfo source_info(
257 usd_shader.ConnectableAPI(), source_name, pxr::UsdShadeAttributeType::Output);
258 shader.CreateInput(input_spec.input_name, input_spec.input_type)
259 .ConnectToSource(source_info);
260
261 if (STREQ(sock.name, "Transmission Weight")) {
262 set_transmission_opacity_range(usd_shader, input_spec, source_name);
263 }
264
265 set_normal_texture_range(usd_shader, input_spec);
266
267 /* Export the texture, if necessary. */
268 if (usd_export_context.export_params.export_textures) {
269 export_texture(usd_export_context, input_node);
270 }
271
272 /* Scale-Bias processing.
273 * Ordinary: If a Vector Math node was detected ahead of the texture node, and it has
274 * the correct type, NODE_VECTOR_MATH_MULTIPLY_ADD, assume it's meant to be
275 * used for scale-bias.
276 * Displacement: The scale-bias values come from the Midlevel and Scale sockets.
277 */
278 if (input_spec.input_name != usdtokens::displacement) {
279 const bNodeLink *scale_link = traverse_channel(&sock, SH_NODE_VECTOR_MATH);
280 if (scale_link) {
281 bNode *vector_math_node = scale_link->fromnode;
282 if (vector_math_node->custom1 == NODE_VECTOR_MATH_MULTIPLY_ADD) {
283 /* Attempt one more traversal in case the current node is not the
284 * correct NODE_VECTOR_MATH_MULTIPLY_ADD (see code in usd_reader_material). */
285 const bNodeSocket *sock_current = bke::node_find_socket(
286 *vector_math_node, SOCK_IN, "Vector"_ustr);
287 const bNodeLink *temp_link = traverse_channel(sock_current, SH_NODE_VECTOR_MATH);
288 if (temp_link && temp_link->fromnode->custom1 == NODE_VECTOR_MATH_MULTIPLY_ADD) {
289 vector_math_node = temp_link->fromnode;
290 }
291
292 const bNodeSocket *sock_scale = bke::node_find_socket(
293 *vector_math_node, SOCK_IN, "Vector_001"_ustr);
294 const bNodeSocket *sock_bias = bke::node_find_socket(
295 *vector_math_node, SOCK_IN, "Vector_002"_ustr);
296 const float *scale_value =
297 sock_scale->default_value_typed<bNodeSocketValueVector>()->value;
298 const float *bias_value =
299 sock_bias->default_value_typed<bNodeSocketValueVector>()->value;
300
301 const pxr::GfVec4f scale(scale_value[0], scale_value[1], scale_value[2], 1.0f);
302 const pxr::GfVec4f bias(bias_value[0], bias_value[1], bias_value[2], 0.0f);
303 set_scale_bias(usd_shader, scale, bias);
304 }
305 }
306 }
307 else {
308 const bNodeSocket *sock_midlevel = bke::node_find_socket(*node, SOCK_IN, "Midlevel"_ustr);
309 const bNodeSocket *sock_scale = bke::node_find_socket(*node, SOCK_IN, "Scale"_ustr);
310 const float midlevel_value =
311 sock_midlevel->default_value_typed<bNodeSocketValueFloat>()->value;
312 const float scale_value = sock_scale->default_value_typed<bNodeSocketValueFloat>()->value;
313
314 const float adjusted_bias = -midlevel_value * scale_value;
315 const pxr::GfVec4f scale(scale_value, scale_value, scale_value, 1.0f);
316 const pxr::GfVec4f bias(adjusted_bias, adjusted_bias, adjusted_bias, 0.0f);
317 set_scale_bias(usd_shader, scale, bias);
318 }
319
320 /* Look for a connected uvmap node. */
321 if (bNodeSocket *socket = bke::node_find_socket(*input_node, SOCK_IN, "Vector"_ustr)) {
322 if (pxr::UsdShadeInput st_input = usd_shader.CreateInput(usdtokens::st,
323 pxr::SdfValueTypeNames->Float2))
324 {
326 usd_export_context, socket, usd_material, st_input, active_uvmap_name, reports);
327 }
328 }
329
330 /* Set opacityThreshold if an alpha cutout is used. */
331 if (input_spec.input_name == usdtokens::opacity) {
332 float threshold = 0.0f;
333
334 /* The immediate upstream node should either be a Math Round or a Math 1-minus. */
335 const bNodeLink *math_link = traverse_channel(&sock, SH_NODE_MATH);
336 if (math_link && math_link->fromnode) {
337 bNode *math_node = math_link->fromnode;
338
339 if (math_node->custom1 == NODE_MATH_ROUND) {
340 threshold = 0.5f;
341 }
342 else if (math_node->custom1 == NODE_MATH_SUBTRACT) {
343 /* If this is the 1-minus node, we need to search upstream to find the less-than. */
344 bNodeSocket *math_sock = bke::node_find_socket(*math_node, SOCK_IN, "Value"_ustr);
345 if (math_sock->default_value_typed<bNodeSocketValueFloat>()->value == 1.0f) {
346 math_sock = bke::node_find_socket(*math_node, SOCK_IN, "Value_001"_ustr);
347 math_link = traverse_channel(math_sock, SH_NODE_MATH);
348 if (math_link && math_link->fromnode) {
349 math_node = math_link->fromnode;
350
351 if (math_node->custom1 == NODE_MATH_LESS_THAN) {
352 /* We found the upstream less-than with the threshold value. */
353 bNodeSocket *threshold_sock = bke::node_find_socket(
354 *math_node, SOCK_IN, "Value_001"_ustr);
355 threshold = threshold_sock->default_value_typed<bNodeSocketValueFloat>()->value;
356 }
357 }
358 }
359 }
360 }
361
362 if (threshold > 0.0f) {
363 pxr::UsdShadeInput opacity_threshold_input = shader.CreateInput(
364 usdtokens::opacityThreshold, pxr::SdfValueTypeNames->Float);
365 opacity_threshold_input.GetAttr().Set(pxr::VtValue(threshold));
366 }
367 }
368
369 processed = true;
370 }
371
372 if (processed) {
373 continue;
374 }
375
376 /* No upstream Image was found. Check for an Attribute node instead */
377 input_link = traverse_channel(&sock, SH_NODE_ATTRIBUTE);
378 if (input_link) {
379 const bNode *attr_node = input_link->fromnode;
381
382 if (storage->type == SHD_ATTRIBUTE_GEOMETRY) {
383 pxr::SdfValueTypeName output_type;
384 pxr::UsdShadeShader usd_shader;
385 if (STREQ(input_link->fromsock->identifier, "Color")) {
386 output_type = pxr::SdfValueTypeNames->Float3;
387 usd_shader = create_primvar_reader_shader(
388 usd_export_context, usd_material, usdtokens::primvar_float3, attr_node);
389 }
390 else if (STREQ(input_link->fromsock->identifier, "Vector")) {
391 output_type = pxr::SdfValueTypeNames->Float3;
392 usd_shader = create_primvar_reader_shader(
393 usd_export_context, usd_material, usdtokens::primvar_vector, attr_node);
394 }
395 else if (STREQ(input_link->fromsock->identifier, "Fac")) {
396 output_type = pxr::SdfValueTypeNames->Float;
397 usd_shader = create_primvar_reader_shader(
398 usd_export_context, usd_material, usdtokens::primvar_float, attr_node);
399 }
400
401 std::string attr_name = make_safe_primvar_name(
402 storage->name, usd_export_context.export_params.allow_unicode);
403 usd_shader.CreateInput(usdtokens::varname, pxr::SdfValueTypeNames->String).Set(attr_name);
404
405 pxr::UsdShadeConnectionSourceInfo source_info(usd_shader.ConnectableAPI(),
407 pxr::UsdShadeAttributeType::Output,
408 output_type);
409 shader.CreateInput(input_spec.input_name, input_spec.input_type)
410 .ConnectToSource(source_info);
411
412 processed = true;
413 }
414 }
415
416 if (processed) {
417 continue;
418 }
419
420 /* No upstream nodes, just set a default constant. */
421 if (input_spec.set_default_value) {
422 switch (sock.type) {
423 case SOCK_FLOAT: {
424 const bool is_inverted = input_spec.input_name == usdtokens::opacity;
425 const float val = sock.default_value_typed<bNodeSocketValueFloat>()->value;
426 create_input(shader, input_spec, is_inverted ? (1.0f - val) : val, input_scale);
427 } break;
428 case SOCK_VECTOR: {
429 const float *val = sock.default_value_typed<bNodeSocketValueVector>()->value;
430 create_input(shader, input_spec, pxr::GfVec3f(val), input_scale);
431 } break;
432 case SOCK_RGBA: {
433 const float *val = sock.default_value_typed<bNodeSocketValueRGBA>()->value;
434 create_input(shader, input_spec, pxr::GfVec3f(val), input_scale);
435 } break;
436 default:
437 break;
438 }
439 }
440 }
441}
442
443static void create_usd_preview_surface_material(const USDExporterContext &usd_export_context,
444 const Material *material,
445 pxr::UsdShadeMaterial &usd_material,
446 const std::string &active_uvmap_name,
447 ReportList *reports)
448{
449 if (!material) {
450 return;
451 }
452
453 /* We only handle the first instance of either principled or
454 * diffuse bsdf nodes in the material's node tree, because
455 * USD Preview Surface has no concept of layering materials. */
456 bNode *surface_node = find_bsdf_node(material);
457 if (!surface_node) {
458 return;
459 }
460
461 pxr::UsdShadeShader preview_surface = create_usd_preview_shader(
462 usd_export_context, usd_material, surface_node);
463
464 /* Handle the primary "surface" output. */
466 usd_export_context, usd_material, preview_surface, surface_node, active_uvmap_name, reports);
467
468 /* Handle the "displacement" output if it meets our requirements. */
469 if (bNode *displacement_node = find_displacement_node(material)) {
470 if (displacement_node->custom1 != SHD_SPACE_OBJECT) {
471 CLOG_WARN(&LOG,
472 "Skipping displacement. Only Object Space displacement is supported by the "
473 "UsdPreviewSurface.");
474 return;
475 }
476
477 bNodeSocket *sock_mid = bke::node_find_socket(*displacement_node, SOCK_IN, "Midlevel"_ustr);
478 bNodeSocket *sock_scale = bke::node_find_socket(*displacement_node, SOCK_IN, "Scale"_ustr);
479 if (sock_mid->link || sock_scale->link) {
480 CLOG_WARN(&LOG, "Skipping displacement. Midlevel and Scale must be constants.");
481 return;
482 }
483
484 usd_material.CreateDisplacementOutput().ConnectToSource(preview_surface.ConnectableAPI(),
486
487 bNodeSocket *sock_height = bke::node_find_socket(*displacement_node, SOCK_IN, "Height"_ustr);
488 if (sock_height->link) {
489 process_inputs(usd_export_context,
490 usd_material,
491 preview_surface,
492 displacement_node,
493 active_uvmap_name,
494 reports);
495 }
496 else {
497 /* The Height itself was also a constant. Odd but still valid. As there's only 1 value that
498 * can be written to USD, this will be a lossy conversion upon reading back in. The reader
499 * will calculate the node's parameters assuming default values for Midlevel and Scale. */
500 const float mid_value = sock_mid->default_value_typed<bNodeSocketValueFloat>()->value;
501 const float scale_value = sock_scale->default_value_typed<bNodeSocketValueFloat>()->value;
502 const float height_value = sock_height->default_value_typed<bNodeSocketValueFloat>()->value;
503 const float displacement_value = (height_value - mid_value) * scale_value;
504 const InputSpec &spec = preview_surface_input_map().lookup("Height");
505 preview_surface.CreateInput(spec.input_name, spec.input_type).Set(displacement_value);
506 }
507 }
508}
509
510void set_transmission_opacity_range(pxr::UsdShadeShader &usd_shader,
511 const InputSpec &input_spec,
512 const pxr::TfToken &source_name)
513{
514 /* Only run if this input_spec is for a opacity. */
515 if (input_spec.input_name != usdtokens::opacity) {
516 return;
517 }
518
519 /* Make sure this is a texture shader prim. */
520 pxr::TfToken shader_id;
521 if (!usd_shader.GetIdAttr().Get(&shader_id) || shader_id != usdtokens::uv_texture) {
522 return;
523 }
524
525 /* Get or Create the scale attribute. */
526 auto scale_attr = usd_shader.GetInput(usdtokens::scale);
527 if (!scale_attr) {
528 scale_attr = usd_shader.CreateInput(usdtokens::scale, pxr::SdfValueTypeNames->Float4);
529 }
530
531 /* Get or Create the bias attribute. */
532 auto bias_attr = usd_shader.GetInput(usdtokens::bias);
533 if (!bias_attr) {
534 bias_attr = usd_shader.CreateInput(usdtokens::bias, pxr::SdfValueTypeNames->Float4);
535 }
536
537 /* Minimally set the scale-bias adjustment based only on the channel used. */
538 if (source_name == usdtokens::r) {
539 scale_attr.Set(pxr::GfVec4f(-1.0f, 1.0f, 1.0f, 1.0f));
540 bias_attr.Set(pxr::GfVec4f(1.0f, 0.0f, 0.0f, 0.0f));
541 }
542 else if (source_name == usdtokens::g) {
543 scale_attr.Set(pxr::GfVec4f(1.0f, -1.0f, 1.0f, 1.0f));
544 bias_attr.Set(pxr::GfVec4f(0.0f, 1.0f, 0.0f, 0.0f));
545 }
546 else if (source_name == usdtokens::b) {
547 scale_attr.Set(pxr::GfVec4f(1.0f, 1.0f, -1.0f, 1.0f));
548 bias_attr.Set(pxr::GfVec4f(0.0f, 0.0f, 1.0f, 0.0f));
549 }
550 else {
551 scale_attr.Set(pxr::GfVec4f(-1.0f, -1.0f, -1.0f, 1.0f));
552 bias_attr.Set(pxr::GfVec4f(1.0f, 1.0f, 1.0f, 0.0f));
553 }
554}
555
556void set_normal_texture_range(pxr::UsdShadeShader &usd_shader, const InputSpec &input_spec)
557{
558 /* Set the scale and bias for normal map textures
559 * The USD spec requires them to be within the -1 to 1 space. */
560
561 /* Only run if this input_spec is for a normal. */
562 if (input_spec.input_name != usdtokens::normal) {
563 return;
564 }
565
566 /* Make sure this is a texture shader prim. */
567 pxr::TfToken shader_id;
568 if (!usd_shader.GetIdAttr().Get(&shader_id) || shader_id != usdtokens::uv_texture) {
569 return;
570 }
571
572 /* We should only be setting this if the colorspace is raw. sRGB will not map the same. */
573 pxr::TfToken colorspace;
574 auto colorspace_attr = usd_shader.GetInput(usdtokens::sourceColorSpace);
575 if (!colorspace_attr || !colorspace_attr.Get(&colorspace) || colorspace != usdtokens::raw) {
576 return;
577 }
578
579 /* Get or Create the scale attribute and set it. */
580 auto scale_attr = usd_shader.GetInput(usdtokens::scale);
581 if (!scale_attr) {
582 scale_attr = usd_shader.CreateInput(usdtokens::scale, pxr::SdfValueTypeNames->Float4);
583 }
584 scale_attr.Set(pxr::GfVec4f(2.0f, 2.0f, 2.0f, 2.0f));
585
586 /* Get or Create the bias attribute and set it. */
587 auto bias_attr = usd_shader.GetInput(usdtokens::bias);
588 if (!bias_attr) {
589 bias_attr = usd_shader.CreateInput(usdtokens::bias, pxr::SdfValueTypeNames->Float4);
590 }
591 bias_attr.Set(pxr::GfVec4f(-1.0f, -1.0f, -1.0f, -1.0f));
592}
593
594/* Create USD Shade Material network from Blender viewport display settings. */
596 const Material *material,
597 const pxr::UsdShadeMaterial &usd_material)
598{
599 /* Construct the shader. */
600 pxr::SdfPath shader_path = usd_material.GetPath().AppendChild(usdtokens::preview_shader);
601 pxr::UsdShadeShader shader = pxr::UsdShadeShader::Define(usd_export_context.stage, shader_path);
602
603 shader.CreateIdAttr(pxr::VtValue(usdtokens::preview_surface));
604 shader.CreateInput(usdtokens::diffuse_color, pxr::SdfValueTypeNames->Color3f)
605 .Set(pxr::GfVec3f(material->r, material->g, material->b));
606 shader.CreateInput(usdtokens::roughness, pxr::SdfValueTypeNames->Float).Set(material->roughness);
607 shader.CreateInput(usdtokens::metallic, pxr::SdfValueTypeNames->Float).Set(material->metallic);
608
609 /* Connect the shader and the material together. */
610 usd_material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), usdtokens::surface);
611}
612
613/* Return USD Preview Surface input map singleton. */
615{
616 static const InputSpecMap input_map = []() {
617 InputSpecMap map;
618 map.add_new("Base Color", {usdtokens::diffuse_color, pxr::SdfValueTypeNames->Color3f, true});
619 map.add_new("Emission Color",
620 {usdtokens::emissive_color, pxr::SdfValueTypeNames->Color3f, true});
621 map.add_new("Color", {usdtokens::diffuse_color, pxr::SdfValueTypeNames->Color3f, true});
622 map.add_new("Roughness", {usdtokens::roughness, pxr::SdfValueTypeNames->Float, true});
623 map.add_new("Metallic", {usdtokens::metallic, pxr::SdfValueTypeNames->Float, true});
624 map.add_new("Specular IOR Level", {usdtokens::specular, pxr::SdfValueTypeNames->Float, true});
625 map.add_new("Alpha", {usdtokens::opacity, pxr::SdfValueTypeNames->Float, true});
626 map.add_new("Transmission Weight", {usdtokens::opacity, pxr::SdfValueTypeNames->Float, true});
627 map.add_new("IOR", {usdtokens::ior, pxr::SdfValueTypeNames->Float, true});
628
629 /* Note that for the Normal input set_default_value is false. */
630 map.add_new("Normal", {usdtokens::normal, pxr::SdfValueTypeNames->Normal3f, false});
631 map.add_new("Coat Weight", {usdtokens::clearcoat, pxr::SdfValueTypeNames->Float, true});
632 map.add_new("Coat Roughness",
633 {usdtokens::clearcoatRoughness, pxr::SdfValueTypeNames->Float, true});
634 map.add_new("Height", {usdtokens::displacement, pxr::SdfValueTypeNames->Float, false});
635 return map;
636 }();
637
638 return input_map;
639}
640
641/* Find the UVMAP node input to the given texture image node and convert it
642 * to a USD primvar reader shader. If no UVMAP node is found, create a primvar
643 * reader for the given default uv set. The primvar reader will be attached to
644 * the 'st' input of the given USD texture shader. */
645static void create_uvmap_shader(const USDExporterContext &usd_export_context,
646 const bNodeLink *uvmap_link,
647 const pxr::UsdShadeMaterial &usd_material,
648 const pxr::UsdShadeInput &usd_input,
649 const std::string &active_uvmap_name,
650 ReportList *reports)
651
652{
653 const bNode *uv_node = (uvmap_link && uvmap_link->fromnode ? uvmap_link->fromnode : nullptr);
654
655 BLI_assert(!uv_node || uv_node->type_legacy == SH_NODE_UVMAP);
656
657 const StringRef shader_name = uv_node ? uv_node->name : "uvmap";
658
659 pxr::UsdShadeShader uv_shader = create_usd_preview_shader(
660 usd_export_context, usd_material, shader_name, SH_NODE_UVMAP);
661
662 if (!uv_shader) {
663 BKE_reportf(reports, RPT_WARNING, "%s: Couldn't create USD shader for UV map", __func__);
664 return;
665 }
666
667 std::string uv_name = active_uvmap_name;
668 if (uv_node && uv_node->storage) {
669 const NodeShaderUVMap *shader_uv_map = static_cast<const NodeShaderUVMap *>(uv_node->storage);
670 uv_name = shader_uv_map->uv_map;
671 }
672 if (usd_export_context.export_params.rename_uvmaps && uv_name == active_uvmap_name) {
673 uv_name = usdtokens::st;
674 }
675 /* We need to make valid, same as was done when exporting UV primvar. */
676 uv_name = make_safe_primvar_name(uv_name, usd_export_context.export_params.allow_unicode);
677
678 uv_shader.CreateInput(usdtokens::varname, pxr::SdfValueTypeNames->String).Set(uv_name);
679 usd_input.ConnectToSource(uv_shader.ConnectableAPI(), usdtokens::result);
680}
681
682static void create_transform2d_shader(const USDExporterContext &usd_export_context,
683 const bNodeLink *mapping_link,
684 pxr::UsdShadeMaterial &usd_material,
685 pxr::UsdShadeInput &usd_input,
686 const std::string &uvmap_name,
687 ReportList *reports)
688
689{
690 const bNode *mapping_node = (mapping_link && mapping_link->fromnode ? mapping_link->fromnode :
691 nullptr);
692
693 BLI_assert(mapping_node && mapping_node->type_legacy == SH_NODE_MAPPING);
694
695 if (!mapping_node) {
696 return;
697 }
698
699 if (mapping_node->custom1 != TEXMAP_TYPE_POINT) {
700 if (const bNodeSocket *socket = bke::node_find_socket(*mapping_node, SOCK_IN, "Vector"_ustr)) {
701 create_uv_input(usd_export_context, socket, usd_material, usd_input, uvmap_name, reports);
702 }
703 return;
704 }
705
706 pxr::UsdShadeShader transform2d_shader = create_usd_preview_shader(
707 usd_export_context, usd_material, mapping_node);
708
709 if (!transform2d_shader) {
710 BKE_reportf(reports, RPT_WARNING, "%s: Couldn't create USD shader for mapping node", __func__);
711 return;
712 }
713
714 usd_input.ConnectToSource(transform2d_shader.ConnectableAPI(), usdtokens::result);
715
716 float scale[3] = {1.0f, 1.0f, 1.0f};
717 float loc[3] = {0.0f, 0.0f, 0.0f};
718 float rot[3] = {0.0f, 0.0f, 0.0f};
719
720 if (const bNodeSocket *scale_socket = bke::node_find_socket(
721 *mapping_node, SOCK_IN, "Scale"_ustr))
722 {
723 copy_v3_v3(scale, scale_socket->default_value_typed<bNodeSocketValueVector>()->value);
724 /* Ignore the Z scale. */
725 scale[2] = 1.0f;
726 }
727
728 if (const bNodeSocket *loc_socket = bke::node_find_socket(
729 *mapping_node, SOCK_IN, "Location"_ustr))
730 {
731 copy_v3_v3(loc, loc_socket->default_value_typed<bNodeSocketValueVector>()->value);
732 /* Ignore the Z translation. */
733 loc[2] = 0.0f;
734 }
735
736 if (const bNodeSocket *rot_socket = bke::node_find_socket(
737 *mapping_node, SOCK_IN, "Rotation"_ustr))
738 {
739 copy_v3_v3(rot, rot_socket->default_value_typed<bNodeSocketValueVector>()->value);
740 /* Ignore the X and Y rotations. */
741 rot[0] = 0.0f;
742 rot[1] = 0.0f;
743 }
744
745 if (pxr::UsdShadeInput scale_input = transform2d_shader.CreateInput(
746 usdtokens::scale, pxr::SdfValueTypeNames->Float2))
747 {
748 pxr::GfVec2f scale_val(scale[0], scale[1]);
749 scale_input.Set(scale_val);
750 }
751
752 if (pxr::UsdShadeInput trans_input = transform2d_shader.CreateInput(
753 usdtokens::translation, pxr::SdfValueTypeNames->Float2))
754 {
755 pxr::GfVec2f trans_val(loc[0], loc[1]);
756 trans_input.Set(trans_val);
757 }
758
759 if (pxr::UsdShadeInput rot_input = transform2d_shader.CreateInput(usdtokens::rotation,
760 pxr::SdfValueTypeNames->Float))
761 {
762 /* Convert to degrees. */
763 float rot_val = rot[2] * 180.0f / M_PI;
764 rot_input.Set(rot_val);
765 }
766
767 if (const bNodeSocket *socket = bke::node_find_socket(*mapping_node, SOCK_IN, "Vector"_ustr)) {
768 if (pxr::UsdShadeInput in_input = transform2d_shader.CreateInput(
769 usdtokens::in, pxr::SdfValueTypeNames->Float2))
770 {
771 create_uv_input(usd_export_context, socket, usd_material, in_input, uvmap_name, reports);
772 }
773 }
774}
775
776static void create_uv_input(const USDExporterContext &usd_export_context,
777 const bNodeSocket *input_socket,
778 pxr::UsdShadeMaterial &usd_material,
779 pxr::UsdShadeInput &usd_input,
780 const std::string &active_uvmap_name,
781 ReportList *reports)
782{
783 if (!(usd_material && usd_input)) {
784 return;
785 }
786
787 if (const bNodeLink *mapping_link = traverse_channel(input_socket, SH_NODE_MAPPING)) {
788 /* Use either "st" or active UV map name from mesh, depending if it was renamed. */
789 std::string uvmap_name = (usd_export_context.export_params.rename_uvmaps) ? usdtokens::st :
790 active_uvmap_name;
792 usd_export_context, mapping_link, usd_material, usd_input, uvmap_name, reports);
793 return;
794 }
795
796 const bNodeLink *uvmap_link = traverse_channel(input_socket, SH_NODE_UVMAP);
797
798 /* Note that uvmap_link might be null, but create_uv_shader() can handle this case. */
800 usd_export_context, uvmap_link, usd_material, usd_input, active_uvmap_name, reports);
801}
802
803static bool has_generated_tiles(const Image *ima)
804{
805 bool any_generated = false;
806 for (const ImageTile &tile : ima->tiles) {
807 if ((tile.gen_flag & IMA_GEN_TILE) != 0) {
808 any_generated = true;
809 break;
810 }
811 }
812 return any_generated;
813}
814
816{
817 return has_generated_tiles(ima) || BKE_image_is_dirty(ima);
818}
819
820static bool is_packed_texture(const Image *ima)
821{
822 return BKE_image_has_packedfile(ima);
823}
824
825/* Generate a file name for an in-memory image that doesn't have a
826 * filepath already defined. */
827static std::string get_in_memory_texture_filename(Image *ima)
828{
829 bool is_dirty = BKE_image_is_dirty(ima);
830 bool is_generated = has_generated_tiles(ima);
831 bool is_packed = BKE_image_has_packedfile(ima);
832 bool is_tiled = ima->source == IMA_SRC_TILED;
833 if (!(is_generated || is_dirty || is_packed)) {
834 return "";
835 }
836
837 /* Determine the correct file extension from the image format. */
838 ImBuf *imbuf = BKE_image_acquire_ibuf(ima, nullptr, nullptr);
839 if (!imbuf) {
840 return "";
841 }
842
843 ImageFormatData imageFormat;
844 BKE_image_format_from_imbuf(&imageFormat, imbuf);
845 BKE_image_release_ibuf(ima, imbuf, nullptr);
846
847 char file_name[FILE_MAX];
848
849 /* NOTE: Any changes in packed filepath handling here should be considered alongside potential
850 * changes in `export_packed_texture`. The file name returned needs to match. */
851 if (is_packed && ima->filepath[0] != '\0') {
852 BLI_path_split_file_part(ima->filepath, file_name, FILE_MAX);
853 return file_name;
854 }
855
856 /* Use the image name for the file name. */
857 STRNCPY(file_name, ima->id.name + 2);
858
859 BKE_image_path_ext_from_imformat_ensure(file_name, sizeof(file_name), &imageFormat);
860
861 if (is_tiled && !BKE_image_is_filename_tokenized(file_name)) {
862 /* Ensure that the UDIM tag is in. */
863 char file_body[FILE_MAX];
864 char file_ext[FILE_MAX];
865 BLI_string_split_suffix(file_name, FILE_MAX, file_body, file_ext);
866 SNPRINTF(file_name, "%s.<UDIM>%s", file_body, file_ext);
867 }
868
869 return file_name;
870}
871
873 const std::string &export_dir,
874 const char image_abs_path[FILE_MAX],
875 const char file_name[FILE_MAX],
876 const bool allow_overwrite,
877 ReportList *reports)
878{
879 ImageFormatData imageFormat;
880 BKE_image_format_from_imbuf(&imageFormat, imbuf);
881
882 char export_path[FILE_MAX];
883 BLI_path_join(export_path, FILE_MAX, export_dir.c_str(), file_name);
884
885 if (!allow_overwrite && BLI_exists(export_path)) {
886 return;
887 }
888
889 if ((BLI_path_cmp_normalized(export_path, image_abs_path) == 0) && BLI_exists(image_abs_path)) {
890 /* As a precaution, don't overwrite the original path. */
891 return;
892 }
893
894 CLOG_DEBUG(&LOG, "Exporting in-memory texture to '%s'", export_path);
895
896 if (BKE_imbuf_write_as(imbuf, export_path, &imageFormat, true) == false) {
898 reports, RPT_WARNING, "USD export: couldn't export in-memory texture to %s", export_path);
899 }
900}
901
903 const std::string &export_dir,
904 const bool allow_overwrite,
905 ReportList *reports)
906{
907 char image_abs_path[FILE_MAX] = {};
908
909 char file_name[FILE_MAX];
910 if (ima->filepath[0]) {
911 get_absolute_path(ima, image_abs_path);
912 BLI_path_split_file_part(image_abs_path, file_name, FILE_MAX);
913 }
914 else {
915 /* Use the image name for the file name. */
916 std::string file = get_in_memory_texture_filename(ima);
917 STRNCPY(file_name, file.c_str());
918 }
919
920 /* This image in its current state only exists in Blender memory.
921 * So we have to export it. The export will keep the image state intact,
922 * so the exported file will not be associated with the image. */
923 if (ima->source != IMA_SRC_TILED) {
924 ImBuf *imbuf = BKE_image_acquire_ibuf(ima, nullptr, nullptr);
925 if (!imbuf) {
926 return;
927 }
928
929 export_in_memory_imbuf(imbuf, export_dir, image_abs_path, file_name, allow_overwrite, reports);
930 BKE_image_release_ibuf(ima, imbuf, nullptr);
931 }
932 else {
933 eUDIM_TILE_FORMAT tile_format;
934 const char *udim_pattern = nullptr;
935 udim_pattern = BKE_image_get_tile_strformat(file_name, &tile_format);
936 if (tile_format == UDIM_TILE_FORMAT_NONE) {
937 return;
938 }
939
940 /* Save all the tiles. */
941 ImageUser iuser{};
942 for (const ImageTile &tile : ima->tiles) {
943 char tile_filepath[FILE_MAX];
945 tile_filepath, udim_pattern, tile_format, tile.tile_number);
946 iuser.tile = tile.tile_number;
947
948 ImBuf *imbuf = BKE_image_acquire_ibuf(ima, &iuser, nullptr);
949 if (!imbuf) {
950 continue;
951 }
952
954 imbuf, export_dir, image_abs_path, tile_filepath, allow_overwrite, reports);
955 BKE_image_release_ibuf(ima, imbuf, nullptr);
956 }
957 MEM_delete(udim_pattern);
958 }
959}
960
961static void export_packed_texture(const Image *ima,
962 const std::string &export_dir,
963 const bool allow_overwrite,
964 ReportList *reports)
965{
966 for (const ImagePackedFile &imapf : ima->packedfiles) {
967 if (!imapf.packedfile || !imapf.packedfile->data || !imapf.packedfile->size) {
968 continue;
969 }
970
971 const PackedFile *pf = imapf.packedfile;
972
973 char image_abs_path[FILE_MAX] = {};
974 char file_name[FILE_MAX];
975
976 if (imapf.filepath[0] != '\0') {
977 /* Get the file name from the original path. */
978 /* Make absolute source path. */
979 STRNCPY(image_abs_path, imapf.filepath);
981 image_abs_path, ID_BLEND_PATH_FROM_GLOBAL(&ima->id), false /* Not for import */);
982 BLI_path_split_file_part(image_abs_path, file_name, FILE_MAX);
983 }
984 else {
985 /* The following logic is taken from unpack_generate_paths() in packedFile.cc. */
986
987 /* NOTE: we generally do not have any real way to re-create extension out of data. */
988 const size_t len = STRNCPY_RLEN(file_name, ima->id.name + 2);
989
990 /* For images ensure that the temporary filename contains tile number information as well as
991 * a file extension based on the file magic. */
992
993 enum eImbFileType ftype = eImbFileType(
994 IMB_test_image_type_from_memory(static_cast<const uchar *>(pf->data), pf->size));
995 if (ima->source == IMA_SRC_TILED) {
996 char tile_number[6];
997 SNPRINTF(tile_number, ".%d", imapf.tile_number);
998 BLI_strncpy(file_name + len, tile_number, sizeof(file_name) - len);
999 }
1000 if (ftype != IMB_FTYPE_NONE) {
1001 const int imtype = BKE_ftype_to_imtype(ftype, nullptr);
1002 BKE_image_path_ext_from_imtype_ensure(file_name, sizeof(file_name), imtype);
1003 }
1004 }
1005
1006 char export_path_buf[FILE_MAX];
1007 BLI_path_join(export_path_buf, FILE_MAX, export_dir.c_str(), file_name);
1008 BLI_string_replace_char(export_path_buf, '\\', '/');
1009
1010 const std::string export_path(export_path_buf);
1011 if (!allow_overwrite && asset_exists(export_path)) {
1012 return;
1013 }
1014
1015 const std::string image_path(image_abs_path);
1016 if (paths_equal(export_path, image_path) && asset_exists(image_path)) {
1017 /* As a precaution, don't overwrite the original path. */
1018 return;
1019 }
1020
1021 CLOG_DEBUG(&LOG, "Exporting packed texture to '%s'", export_path.c_str());
1022
1023 write_to_path(pf->data, pf->size, export_path, reports);
1024 }
1025}
1026
1027/* Get the absolute filepath of the given image. Assumes
1028 * r_path result array is of length FILE_MAX. */
1029static void get_absolute_path(const Image *ima, char *r_path)
1030{
1031 /* Make absolute source path. */
1032 BLI_strncpy(r_path, ima->filepath, FILE_MAX);
1033 BLI_path_abs(r_path, ID_BLEND_PATH_FROM_GLOBAL(&ima->id));
1034 BLI_path_normalize(r_path);
1035}
1036
1037static pxr::TfToken get_node_tex_image_wrap(const bNode *node)
1038{
1039 if (node->type_legacy != SH_NODE_TEX_IMAGE) {
1040 return pxr::TfToken();
1041 }
1042
1043 if (node->storage == nullptr) {
1044 return pxr::TfToken();
1045 }
1046
1047 const NodeTexImage *tex_image = static_cast<const NodeTexImage *>(node->storage);
1048
1049 pxr::TfToken wrap;
1050
1051 switch (tex_image->extension) {
1054 break;
1057 break;
1060 break;
1063 break;
1064 }
1065
1066 return wrap;
1067}
1068
1069/* Search the upstream node links connected to the given socket and return the first occurrence
1070 * of the link connected to the node of the given type. Return null if no such link was found.
1071 * The 'fromnode' and 'fromsock' members of the returned link are guaranteed to be not null. */
1072static const bNodeLink *traverse_channel(const bNodeSocket *input, const short target_type)
1073{
1074 if (!(input->link && input->link->fromnode && input->link->fromsock)) {
1075 return nullptr;
1076 }
1077
1078 const bNode *linked_node = input->link->fromnode;
1079 if (linked_node->type_legacy == target_type) {
1080 /* Return match. */
1081 return input->link;
1082 }
1083
1084 /* Recursively traverse the linked node's sockets. */
1085 for (const bNodeSocket &sock : linked_node->inputs) {
1086 if (const bNodeLink *found_link = traverse_channel(&sock, target_type)) {
1087 return found_link;
1088 }
1089 }
1090
1091 return nullptr;
1092}
1093
1094/* Returns the first occurrence of a principled BSDF or a diffuse BSDF node found in the given
1095 * material's node tree. Returns null if no instance of either type was found. */
1096static bNode *find_bsdf_node(const Material *material)
1097{
1098 for (bNode *node : material->nodetree->all_nodes()) {
1100 return node;
1101 }
1102 }
1103
1104 return nullptr;
1105}
1106
1112static bNode *find_displacement_node(const Material *material)
1113{
1114 for (bNode *node : material->nodetree->all_nodes()) {
1115 if (node->type_legacy == SH_NODE_DISPLACEMENT) {
1116 return node;
1117 }
1118 }
1119
1120 return nullptr;
1121}
1122
1123/* Creates a USD Preview Surface shader based on the given cycles node name and type. */
1124static pxr::UsdShadeShader create_usd_preview_shader(const USDExporterContext &usd_export_context,
1125 const pxr::UsdShadeMaterial &material,
1126 const StringRef name,
1127 const int type)
1128{
1129 pxr::SdfPath shader_path = material.GetPath().AppendChild(
1130 pxr::TfToken(make_safe_name(name, usd_export_context.export_params.allow_unicode)));
1131 pxr::UsdShadeShader shader = pxr::UsdShadeShader::Define(usd_export_context.stage, shader_path);
1132
1133 switch (type) {
1134 case SH_NODE_TEX_IMAGE: {
1135 shader.CreateIdAttr(pxr::VtValue(usdtokens::uv_texture));
1136 break;
1137 }
1138 case SH_NODE_MAPPING: {
1139 shader.CreateIdAttr(pxr::VtValue(usdtokens::UsdTransform2d));
1140 break;
1141 }
1142 case SH_NODE_TEX_COORD:
1143 case SH_NODE_UVMAP: {
1144 shader.CreateIdAttr(pxr::VtValue(usdtokens::primvar_float2));
1145 break;
1146 }
1149 shader.CreateIdAttr(pxr::VtValue(usdtokens::preview_surface));
1150 material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), usdtokens::surface);
1151 break;
1152 }
1153
1154 default:
1155 break;
1156 }
1157
1158 return shader;
1159}
1160
1161/* Creates a USD Preview Surface shader based on the given cycles shading node.
1162 * Due to the limited nodes in the USD Preview Surface specification, only the following nodes
1163 * are supported:
1164 * - UVMap
1165 * - Texture Coordinate
1166 * - Image Texture
1167 * - Principled BSDF
1168 * More may be added in the future.
1169 */
1170static pxr::UsdShadeShader create_usd_preview_shader(const USDExporterContext &usd_export_context,
1171 const pxr::UsdShadeMaterial &material,
1172 const bNode *node)
1173{
1174 pxr::UsdShadeShader shader = create_usd_preview_shader(
1175 usd_export_context, material, node->name, node->type_legacy);
1176
1177 if (node->type_legacy != SH_NODE_TEX_IMAGE) {
1178 return shader;
1179 }
1180
1181 /* For texture image nodes we set the image path and color space. */
1182 std::string imagePath = get_tex_image_asset_filepath(usd_export_context, node);
1183 if (!imagePath.empty()) {
1184 shader.CreateInput(usdtokens::file, pxr::SdfValueTypeNames->Asset)
1185 .Set(pxr::SdfAssetPath(imagePath));
1186 }
1187
1188 io::usd::colorspace_from_image_texture(reinterpret_cast<const Image *>(node->id), shader);
1189
1190 pxr::TfToken wrap = get_node_tex_image_wrap(node);
1191 if (!wrap.IsEmpty()) {
1192 shader.CreateInput(usdtokens::wrapS, pxr::SdfValueTypeNames->Token).Set(wrap);
1193 shader.CreateInput(usdtokens::wrapT, pxr::SdfValueTypeNames->Token).Set(wrap);
1194 }
1195
1196 return shader;
1197}
1198
1199static pxr::UsdShadeShader create_primvar_reader_shader(
1200 const USDExporterContext &usd_export_context,
1201 const pxr::UsdShadeMaterial &material,
1202 const pxr::TfToken &primvar_type,
1203 const bNode *node)
1204{
1205 pxr::SdfPath shader_path = material.GetPath().AppendChild(
1206 pxr::TfToken(make_safe_name(node->name, usd_export_context.export_params.allow_unicode)));
1207 pxr::UsdShadeShader shader = pxr::UsdShadeShader::Define(usd_export_context.stage, shader_path);
1208
1209 shader.CreateIdAttr(pxr::VtValue(primvar_type));
1210 return shader;
1211}
1212
1213static std::string get_tex_image_asset_filepath(const Image *ima)
1214{
1215 char filepath[FILE_MAX];
1216 get_absolute_path(ima, filepath);
1217
1218 return std::string(filepath);
1219}
1220
1221static std::string get_tex_image_asset_filepath(const USDExporterContext &usd_export_context,
1222 const bNode *node)
1223{
1225 node, usd_export_context.stage, usd_export_context.export_params);
1226}
1227
1229 const pxr::UsdStageRefPtr stage,
1230 const USDExportParams &export_params)
1231{
1232 std::string stage_path = stage->GetRootLayer()->GetRealPath();
1233
1234 if (!ima) {
1235 return "";
1236 }
1237
1238 std::string path;
1239
1240 if (is_in_memory_texture(ima)) {
1242 }
1243 else {
1244 if (!export_params.export_textures && export_params.use_original_paths) {
1245 path = get_usd_source_path(&ima->id);
1246 }
1247
1248 if (is_packed_texture(ima)) {
1249 if (path.empty()) {
1250 char file_name[FILE_MAX];
1252 BLI_path_join(file_name, FILE_MAX, ".", "textures", path.c_str());
1253 path = file_name;
1254 }
1255 }
1256 else if (ima->filepath[0] != '\0') {
1257 /* Get absolute path. */
1258 path = get_tex_image_asset_filepath(ima);
1259 }
1260 }
1261
1262 return get_tex_image_asset_filepath(path, stage_path, export_params);
1263}
1264
1265std::string get_tex_image_asset_filepath(const std::string &path,
1266 const std::string &stage_path,
1267 const USDExportParams &export_params)
1268{
1269 if (path.empty()) {
1270 return path;
1271 }
1272
1273 if (export_params.export_textures) {
1274 /* The texture is exported to a 'textures' directory next to the
1275 * USD root layer. */
1276
1277 char exp_path[FILE_MAX];
1278 char file_path[FILE_MAX];
1279 BLI_path_split_file_part(path.c_str(), file_path, FILE_MAX);
1280
1281 if (export_params.relative_paths) {
1282 BLI_path_join(exp_path, FILE_MAX, ".", "textures", file_path);
1283 }
1284 else {
1285 /* Create absolute path in the textures directory. */
1286 if (stage_path.empty()) {
1287 return path;
1288 }
1289
1290 char dir_path[FILE_MAX];
1291 BLI_path_split_dir_part(stage_path.c_str(), dir_path, FILE_MAX);
1292 BLI_path_join(exp_path, FILE_MAX, dir_path, "textures", file_path);
1293 }
1294 BLI_string_replace_char(exp_path, '\\', '/');
1295 return exp_path;
1296 }
1297
1298 if (export_params.relative_paths) {
1299 /* Get the path relative to the USD. */
1300 if (stage_path.empty()) {
1301 return path;
1302 }
1303
1304 std::string rel_path = get_relative_path(path, stage_path);
1305 if (rel_path.empty()) {
1306 return path;
1307 }
1308 return rel_path;
1309 }
1310
1311 return path;
1312}
1313
1315 const pxr::UsdStageRefPtr stage,
1316 const USDExportParams &export_params)
1317{
1318 Image *ima = reinterpret_cast<Image *>(node->id);
1319 return get_tex_image_asset_filepath(ima, stage, export_params);
1320}
1321
1322/* If the given image is tiled, copy the image tiles to the given
1323 * destination directory. */
1324static void copy_tiled_textures(const Image *ima,
1325 const std::string &dest_dir,
1326 const bool allow_overwrite,
1327 ReportList *reports)
1328{
1329 char src_path[FILE_MAX];
1330 get_absolute_path(ima, src_path);
1331
1332 eUDIM_TILE_FORMAT tile_format;
1333 const char *udim_pattern = BKE_image_get_tile_strformat(src_path, &tile_format);
1334
1335 /* Only <UDIM> tile formats are supported by USD right now. */
1336 if (tile_format != UDIM_TILE_FORMAT_UDIM) {
1337 CLOG_WARN(&LOG, "Unsupported tile format for '%s'", src_path);
1338 MEM_SAFE_DELETE(udim_pattern);
1339 return;
1340 }
1341
1342 /* Copy all tiles. */
1343 for (const ImageTile &tile : ima->tiles) {
1344 char src_tile_path[FILE_MAX];
1346 src_tile_path, udim_pattern, tile_format, tile.tile_number);
1347
1348 char dest_filename[FILE_MAXFILE];
1349 BLI_path_split_file_part(src_tile_path, dest_filename, sizeof(dest_filename));
1350
1351 char dest_tile_path[FILE_MAX];
1352 BLI_path_join(dest_tile_path, FILE_MAX, dest_dir.c_str(), dest_filename);
1353
1354 if (!allow_overwrite && BLI_exists(dest_tile_path)) {
1355 continue;
1356 }
1357
1358 if (BLI_path_cmp_normalized(src_tile_path, dest_tile_path) == 0) {
1359 /* Source and destination paths are the same, don't copy. */
1360 continue;
1361 }
1362
1363 CLOG_DEBUG(&LOG, "Copying texture tile from '%s' to '%s'", src_tile_path, dest_tile_path);
1364
1365 /* Copy the file. */
1366 if (BLI_copy(src_tile_path, dest_tile_path) != 0) {
1367 BKE_reportf(reports,
1369 "USD export: could not copy texture tile from %s to %s",
1370 src_tile_path,
1371 dest_tile_path);
1372 }
1373 }
1374 MEM_SAFE_DELETE(udim_pattern);
1375}
1376
1377/* Copy the given image to the destination directory. */
1378static void copy_single_file(const Image *ima,
1379 const std::string &dest_dir,
1380 const bool allow_overwrite,
1381 ReportList *reports)
1382{
1383 char source_path[FILE_MAX];
1384 get_absolute_path(ima, source_path);
1385
1386 char file_name[FILE_MAX];
1387 BLI_path_split_file_part(source_path, file_name, FILE_MAX);
1388
1389 char dest_path[FILE_MAX];
1390 BLI_path_join(dest_path, FILE_MAX, dest_dir.c_str(), file_name);
1391
1392 if (!allow_overwrite && BLI_exists(dest_path)) {
1393 return;
1394 }
1395
1396 if (BLI_path_cmp_normalized(source_path, dest_path) == 0) {
1397 /* Source and destination paths are the same, don't copy. */
1398 return;
1399 }
1400
1401 CLOG_DEBUG(&LOG, "Copying texture from '%s' to '%s'", source_path, dest_path);
1402
1403 /* Copy the file. */
1404 if (BLI_copy(source_path, dest_path) != 0) {
1405 BKE_reportf(reports,
1407 "USD export: could not copy texture from %s to %s",
1408 source_path,
1409 dest_path);
1410 }
1411}
1412
1414 const pxr::UsdStageRefPtr stage,
1415 const bool allow_overwrite,
1416 ReportList *reports)
1417{
1418 std::string dest_dir = get_export_textures_dir(stage);
1419 if (dest_dir.empty()) {
1420 CLOG_ERROR(&LOG, "Couldn't determine textures directory path");
1421 return;
1422 }
1423
1424 if (is_packed_texture(ima)) {
1425 export_packed_texture(ima, dest_dir, allow_overwrite, reports);
1426 }
1427 else if (is_in_memory_texture(ima)) {
1428 export_in_memory_texture(ima, dest_dir, allow_overwrite, reports);
1429 }
1430 else if (ima->source == IMA_SRC_TILED) {
1431 copy_tiled_textures(ima, dest_dir, allow_overwrite, reports);
1432 }
1433 else {
1434 copy_single_file(ima, dest_dir, allow_overwrite, reports);
1435 }
1436}
1437
1438/* Export the given texture node's image to a 'textures' directory in the export path.
1439 * Based on ImagesExporter::export_UV_Image() */
1440static void export_texture(const USDExporterContext &usd_export_context, bNode *node)
1441{
1443 usd_export_context.stage,
1444 usd_export_context.export_params.overwrite_textures,
1445 usd_export_context.export_params.worker_status->reports);
1446}
1447
1448#ifdef WITH_MATERIALX
1449static void export_texture(const USDExporterContext &usd_export_context, Image *ima)
1450{
1451 export_texture(ima,
1452 usd_export_context.stage,
1453 usd_export_context.export_params.overwrite_textures,
1454 usd_export_context.export_params.worker_status->reports);
1455}
1456#endif
1457
1459 const pxr::UsdStageRefPtr stage,
1460 const bool allow_overwrite,
1461 ReportList *reports)
1462{
1463 if (!ELEM(node->type_legacy, SH_NODE_TEX_IMAGE, SH_NODE_TEX_ENVIRONMENT)) {
1464 return;
1465 }
1466
1467 Image *ima = reinterpret_cast<Image *>(node->id);
1468 if (!ima) {
1469 return;
1470 }
1471
1472 export_texture(ima, stage, allow_overwrite, reports);
1473}
1474
1475pxr::TfToken token_for_input(const StringRef input_name)
1476{
1477 const InputSpecMap &input_map = preview_surface_input_map();
1478 const InputSpec *spec = input_map.lookup_ptr(input_name);
1479
1480 if (spec == nullptr) {
1481 return {};
1482 }
1483
1484 return spec->input_name;
1485}
1486
1487#ifdef WITH_MATERIALX
1488/* A wrapper for the MaterialX code to re-use the standard Texture export code */
1489static std::string materialx_export_image(const USDExporterContext &usd_export_context,
1490 Main * /*main*/,
1491 Scene * /*scene*/,
1492 Image *ima,
1493 ImageUser * /*iuser*/)
1494{
1495 auto tex_path = get_tex_image_asset_filepath(
1496 ima, usd_export_context.stage, usd_export_context.export_params);
1497
1498 export_texture(usd_export_context, ima);
1499 return tex_path;
1500}
1501
1502/* Utility function to reflow connections and paths within the temporary document
1503 * to their final location in the USD document. */
1504static pxr::SdfPath reflow_materialx_paths(pxr::SdfPath input_path,
1505 pxr::SdfPath temp_path,
1506 const pxr::SdfPath &target_path,
1507 const Map<std::string, std::string> &rename_pairs)
1508{
1509
1510 const std::string &input_path_string = input_path.GetString();
1511 /* First we see if the path is in the rename_pairs,
1512 * otherwise we check if it starts with any items in the list plus a path separator (/ or .) .
1513 * Checking for the path separators, removes false positives from other prefixed elements. */
1514 const auto *value_lookup_ptr = rename_pairs.lookup_ptr(input_path_string);
1515 if (value_lookup_ptr) {
1516 input_path = pxr::SdfPath(*value_lookup_ptr);
1517 }
1518 else {
1519 for (const auto &pair : rename_pairs.items()) {
1520 if (input_path_string.length() > pair.key.length() &&
1521 pxr::TfStringStartsWith(input_path_string, pair.key) &&
1522 (input_path_string[pair.key.length()] == '/' ||
1523 input_path_string[pair.key.length()] == '.'))
1524 {
1525 input_path = input_path.ReplacePrefix(pxr::SdfPath(pair.key), pxr::SdfPath(pair.value));
1526 break;
1527 }
1528 }
1529 }
1530
1531 return input_path.ReplacePrefix(temp_path, target_path);
1532}
1533
1534/* Exports the material as a MaterialX node-graph within the USD layer. */
1535static void create_usd_materialx_material(const USDExporterContext &usd_export_context,
1536 pxr::SdfPath usd_path,
1537 const Material *material,
1538 const std::string &active_uvmap_name,
1539 const pxr::UsdShadeMaterial &usd_material)
1540{
1541 nodes::materialx::ExportParams export_params = {
1542 /* Output surface material node will have this name. */
1543 usd_path.GetElementString(),
1544 /* We want to re-use the same MaterialX document generation code as used by the renderer.
1545 * While the graph is traversed, we also want it to export the textures out. */
1546 (usd_export_context.export_image_fn) ?
1547 usd_export_context.export_image_fn :
1548 [usd_export_context](Main *main, Scene *scene, Image *ima, ImageUser *iuser) {
1549 return materialx_export_image(usd_export_context, main, scene, ima, iuser);
1550 },
1551 /* Active UV map name to use for default texture coordinates. */
1552 (usd_export_context.export_params.rename_uvmaps) ? "st" : active_uvmap_name,
1553 active_uvmap_name,
1554 };
1555
1556 MaterialX::DocumentPtr doc = nodes::materialx::export_to_materialx(
1557 usd_export_context.depsgraph, material, export_params);
1558
1559 /* We want to merge the MaterialX graph under the same Material as the USDPreviewSurface
1560 * This allows for the same material assignment to have two levels of complexity so other
1561 * applications and renderers can easily pick which one they want.
1562 * This does mean that we need to pre-process the resulting graph so that there are no
1563 * name conflicts.
1564 * So we first gather all the existing names in this namespace to avoid that. */
1565 Set<std::string> used_names;
1566 auto material_prim = usd_material.GetPrim();
1567 for (const auto &child : material_prim.GetChildren()) {
1568 used_names.add(child.GetName().GetString());
1569 }
1570
1571 /* usdMtlx assumes a workflow where the mtlx file is referenced in,
1572 * but the resulting structure is not ideal for when the file is inlined.
1573 * Some of the issues include turning every shader input into a separate constant, which
1574 * leads to very unwieldy shader graphs in other applications. There are also extra nodes
1575 * that are only needed when referencing in the file that make editing the graph harder.
1576 * Therefore, we opt to copy just what we need over.
1577 *
1578 * To do this, we first open a temporary stage to process the structure inside */
1579
1580 auto temp_stage = pxr::UsdStage::CreateInMemory();
1581 pxr::UsdMtlxRead(doc, temp_stage, pxr::SdfPath("/root"));
1582
1583 /* Next we need to find the Material that matches this materials name */
1584 auto temp_material_path = pxr::SdfPath("/root/Materials");
1585 temp_material_path = temp_material_path.AppendChild(material_prim.GetName());
1586 auto temp_material_prim = temp_stage->GetPrimAtPath(temp_material_path);
1587 if (!temp_material_prim) {
1588 return;
1589 }
1590
1591 pxr::UsdShadeMaterial temp_material{temp_material_prim};
1592 if (!temp_material) {
1593 return;
1594 }
1595
1596 /* Copy over the MaterialXConfigAPI schema and associated attribute. */
1597 pxr::UsdMtlxMaterialXConfigAPI temp_config_api{temp_material_prim};
1598 if (temp_config_api) {
1599 pxr::UsdMtlxMaterialXConfigAPI materialx_config_api = pxr::UsdMtlxMaterialXConfigAPI::Apply(
1600 material_prim);
1601 pxr::UsdAttribute temp_mtlx_version_attr = temp_config_api.GetConfigMtlxVersionAttr();
1602 pxr::VtValue mtlx_version;
1603 if (temp_mtlx_version_attr && temp_mtlx_version_attr.Get(&mtlx_version)) {
1604 materialx_config_api.CreateConfigMtlxVersionAttr(mtlx_version);
1605 }
1606 }
1607
1608 /* Once we have the material, we need to prepare for renaming any conflicts.
1609 * However, we must make sure any new names don't conflict with names in the temp stage either */
1610 Set<std::string> temp_used_names;
1611 for (const auto &child : temp_material_prim.GetChildren()) {
1612 temp_used_names.add(child.GetName().GetString());
1613 }
1614
1615 /* We loop through the top level children of the material, and make sure that the names are
1616 * unique across both the destination stage, and this temporary stage.
1617 * This is stored for later use so that we can reflow any connections */
1618 Map<std::string, std::string> rename_pairs;
1619 for (const auto &temp_material_child : temp_material_prim.GetChildren()) {
1620 uint32_t conflict_counter = 0;
1621 const std::string &name = temp_material_child.GetName().GetString();
1622 std::string target_name = name;
1623 while (used_names.contains(target_name)) {
1624 ++conflict_counter;
1625 target_name = name + "_mtlx" + std::to_string(conflict_counter);
1626
1627 while (temp_used_names.contains(target_name)) {
1628 ++conflict_counter;
1629 target_name = name + "_mtlx" + std::to_string(conflict_counter);
1630 }
1631 }
1632
1633 if (conflict_counter == 0) {
1634 continue;
1635 }
1636
1637 temp_used_names.add(target_name);
1638 const pxr::SdfPath &temp_material_child_path = temp_material_child.GetPath();
1639 const std::string &original_path = temp_material_child_path.GetString();
1640 const std::string new_path =
1641 temp_material_child.GetPath().ReplaceName(pxr::TfToken(target_name)).GetString();
1642
1643 rename_pairs.add_overwrite(original_path, new_path);
1644 }
1645
1646 /* We now need to find the connections from the material to the surface shader
1647 * and modify it to match the final target location */
1648 for (const auto &temp_material_output : temp_material.GetOutputs()) {
1649 pxr::SdfPathVector output_paths;
1650
1651 temp_material_output.GetAttr().GetConnections(&output_paths);
1652 if (output_paths.size() == 1) {
1653 output_paths[0] = reflow_materialx_paths(
1654 output_paths[0], temp_material_path, usd_path, rename_pairs);
1655
1656 auto target_material_output = usd_material.CreateOutput(temp_material_output.GetBaseName(),
1657 temp_material_output.GetTypeName());
1658 target_material_output.GetAttr().SetConnections(output_paths);
1659 }
1660 }
1661
1662 /* Next we need to iterate through every shader descendant recursively, to process them */
1663 for (const auto &temp_child : temp_material_prim.GetAllDescendants()) {
1664 /* We only care about shader children */
1665 auto temp_shader = pxr::UsdShadeShader(temp_child);
1666 if (!temp_shader) {
1667 continue;
1668 }
1669
1670 /* First, we process any inputs */
1671 for (const auto &shader_input : temp_shader.GetInputs()) {
1672 pxr::SdfPathVector connection_paths;
1673 shader_input.GetAttr().GetConnections(&connection_paths);
1674
1675 if (connection_paths.size() != 1) {
1676 continue;
1677 }
1678
1679 const pxr::SdfPath &connection_path = connection_paths[0];
1680
1681 auto connection_source = pxr::UsdShadeConnectionSourceInfo(temp_stage, connection_path);
1682 auto connection_source_prim = connection_source.source.GetPrim();
1683 if (connection_source_prim == temp_material_prim) {
1684 /* If it's connected to the material prim, we should just bake down the value.
1685 * usdMtlx connects them to constants because it wants to maximize separation between the
1686 * input mtlx file and the resulting graph, but this isn't the ideal structure when the
1687 * graph is inlined.
1688 * Baking the values down makes this much more usable. */
1689 auto connection_source_attr = temp_stage->GetAttributeAtPath(connection_path);
1690 if (connection_source_attr && shader_input.DisconnectSource()) {
1691 pxr::VtValue val;
1692 if (connection_source_attr.Get(&val) && !val.IsEmpty()) {
1693 shader_input.GetAttr().Set(val);
1694 }
1695 }
1696 }
1697 else {
1698 /* If it's connected to another prim, then we should fix the path to that prim
1699 * SdfCopySpec below will handle some cases, but only if the target path exists first
1700 * which is impossible to guarantee in a graph. */
1701
1702 connection_paths[0] = reflow_materialx_paths(
1703 connection_paths[0], temp_material_path, usd_path, rename_pairs);
1704 shader_input.GetAttr().SetConnections(connection_paths);
1705 }
1706 }
1707
1708 /* Next we iterate through the outputs */
1709 for (const auto &shader_output : temp_shader.GetOutputs()) {
1710 pxr::SdfPathVector connection_paths;
1711 shader_output.GetAttr().GetConnections(&connection_paths);
1712
1713 if (connection_paths.size() != 1) {
1714 continue;
1715 }
1716
1717 connection_paths[0] = reflow_materialx_paths(
1718 connection_paths[0], temp_material_path, usd_path, rename_pairs);
1719 shader_output.GetAttr().SetConnections(connection_paths);
1720 } /* Iterate through outputs */
1721
1722 } /* Iterate through material prim children */
1723
1724 auto temp_layer = temp_stage->Flatten();
1725
1726 /* Copy the primspecs from the temporary stage over to the target stage */
1727 auto target_root_layer = usd_export_context.stage->GetRootLayer();
1728 for (const auto &temp_material_child : temp_material_prim.GetChildren()) {
1729 auto target_path = reflow_materialx_paths(
1730 temp_material_child.GetPath(), temp_material_path, usd_path, rename_pairs);
1731 pxr::SdfCopySpec(temp_layer, temp_material_child.GetPath(), target_root_layer, target_path);
1732 }
1733}
1734#endif
1735
1736pxr::UsdShadeMaterial create_usd_material(const USDExporterContext &usd_export_context,
1737 pxr::SdfPath usd_path,
1738 const Material *material,
1739 const std::string &active_uvmap_name,
1740 ReportList *reports)
1741{
1742 pxr::UsdShadeMaterial usd_material = pxr::UsdShadeMaterial::Define(usd_export_context.stage,
1743 usd_path);
1744
1745 if (usd_export_context.export_params.generate_preview_surface) {
1747 usd_export_context, material, usd_material, active_uvmap_name, reports);
1748 }
1749 else {
1750 create_usd_viewport_material(usd_export_context, material, usd_material);
1751 }
1752
1753#ifdef WITH_MATERIALX
1754 if (usd_export_context.export_params.generate_materialx_network) {
1755 create_usd_materialx_material(
1756 usd_export_context, usd_path, material, active_uvmap_name, usd_material);
1757 }
1758#endif
1759
1761 usd_export_context.stage, material, usd_material, usd_export_context.export_params, reports);
1762
1763 return usd_material;
1764}
1765
1766} // namespace io::usd
1767} // namespace blender
#define SH_NODE_UVMAP
#define SH_NODE_TEX_IMAGE
#define SH_NODE_BSDF_PRINCIPLED
#define SH_NODE_SEPARATE_COLOR
#define SH_NODE_TEX_COORD
#define SH_NODE_VECTOR_MATH
#define SH_NODE_TEX_ENVIRONMENT
#define SH_NODE_MATH
#define SH_NODE_BSDF_DIFFUSE
#define SH_NODE_MAPPING
#define SH_NODE_DISPLACEMENT
#define SH_NODE_ATTRIBUTE
File and directory operations.
#define M_PI
#define FILE_MAXFILE
#define FILE_MAX
#define BLI_path_join(...)
#define STRNCPY_RLEN(dst, src)
#define SNPRINTF(dst, format,...)
#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 ID_BLEND_PATH_FROM_GLOBAL(_id)
Definition DNA_ID.h:691
Read Blender memory allocation and freeing.
#define ELEM(...)
#define STREQ(a, b)
const Value * lookup_ptr(const Key &key) const
Definition BLI_map.hh:508
const Value & lookup(const Key &key) const
Definition BLI_map.hh:545
void add_new(const Key &key, const Value &value)
Definition BLI_map.hh:265
ItemIterator items() const &
Definition BLI_map.hh:902
#define rot(x, k)
#define pf(_x, _i)
Prefetch 64.
Definition gim_memory.h:48
#define main()
#define storage(slot, qualifiers)
float3x3 scale(float3x3 mat, float2 scale)
const ccl_global KernelWorkTile * tile
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
#define T
bNodeSocket * node_find_socket(bNode &node, eNodeSocketInOut in_out, UString identifier)
Definition node.cc:3036
BLI_INLINE Texture * wrap(MTLTexture *texture)
static const pxr::TfToken raw("raw", pxr::TfToken::Immortal)
static const pxr::TfToken sourceColorSpace("sourceColorSpace", pxr::TfToken::Immortal)
void colorspace_from_image_texture(const Image *image, pxr::UsdShadeShader &shader)
static void get_absolute_path(const Image *ima, char *r_path)
static void create_transform2d_shader(const USDExporterContext &usd_export_context, const bNodeLink *mapping_link, pxr::UsdShadeMaterial &usd_material, pxr::UsdShadeInput &usd_input, const std::string &uvmap_name, ReportList *reports)
static void export_texture(const USDExporterContext &usd_export_context, bNode *node)
static void create_usd_preview_surface_material(const USDExporterContext &usd_export_context, const Material *material, pxr::UsdShadeMaterial &usd_material, const std::string &active_uvmap_name, ReportList *reports)
static const InputSpecMap & preview_surface_input_map()
bool asset_exists(const std::string &path)
Map< StringRef, InputSpec > InputSpecMap
static bNode * find_bsdf_node(const Material *material)
static void copy_tiled_textures(const Image *ima, const std::string &dest_dir, const bool allow_overwrite, ReportList *reports)
void set_transmission_opacity_range(pxr::UsdShadeShader &usd_shader, const InputSpec &input_spec, const pxr::TfToken &source_name)
static bool is_packed_texture(const Image *ima)
std::string get_relative_path(const std::string &path, const std::string &anchor)
bool write_to_path(const void *data, size_t size, const std::string &path, ReportList *reports)
static bool is_in_memory_texture(Image *ima)
bool paths_equal(const std::string &path1, const std::string &path2)
pxr::TfToken token_for_input(const StringRef input_name)
static pxr::UsdShadeShader create_usd_preview_shader(const USDExporterContext &usd_export_context, const pxr::UsdShadeMaterial &material, const StringRef name, int type)
static bool has_generated_tiles(const Image *ima)
static std::string get_in_memory_texture_filename(Image *ima)
static void export_in_memory_imbuf(ImBuf *imbuf, const std::string &export_dir, const char image_abs_path[FILE_MAX], const char file_name[FILE_MAX], const bool allow_overwrite, ReportList *reports)
void create_input(pxr::UsdShadeShader &shader, const InputSpec &spec, const T &value, float scale)
void create_usd_viewport_material(const USDExporterContext &usd_export_context, const Material *material, const pxr::UsdShadeMaterial &usd_material)
void export_texture(Image *ima, const pxr::UsdStageRefPtr stage, const bool allow_overwrite, ReportList *reports)
static bNode * find_displacement_node(const Material *material)
std::string get_tex_image_asset_filepath(Image *ima, const pxr::UsdStageRefPtr stage, const USDExportParams &export_params)
static const bNodeLink * traverse_channel(const bNodeSocket *input, short target_type)
void USD_path_abs(char *path, const char *basepath, bool for_import)
std::string make_safe_name(const StringRef name, bool allow_unicode)
Definition usd_utils.cc:83
std::string get_export_textures_dir(const pxr::UsdStageRefPtr stage)
static void export_packed_texture(const Image *ima, const std::string &export_dir, const bool allow_overwrite, ReportList *reports)
static void export_in_memory_texture(Image *ima, const std::string &export_dir, const bool allow_overwrite, ReportList *reports)
static void copy_single_file(const Image *ima, const std::string &dest_dir, const bool allow_overwrite, ReportList *reports)
static void process_inputs(const USDExporterContext &usd_export_context, pxr::UsdShadeMaterial &usd_material, pxr::UsdShadeShader &shader, const bNode *node, const std::string &active_uvmap_name, ReportList *reports)
static pxr::TfToken get_node_tex_image_wrap(const bNode *node)
void call_material_export_hooks(pxr::UsdStageRefPtr stage, const Material *material, const pxr::UsdShadeMaterial &usd_material, const USDExportParams &export_params, ReportList *reports)
Definition usd_hook.cc:604
static pxr::UsdShadeShader create_primvar_reader_shader(const USDExporterContext &usd_export_context, const pxr::UsdShadeMaterial &material, const pxr::TfToken &primvar_type, const bNode *node)
void set_normal_texture_range(pxr::UsdShadeShader &usd_shader, const InputSpec &input_spec)
std::string get_usd_source_path(ID *id)
static void create_uv_input(const USDExporterContext &usd_export_context, const bNodeSocket *input_socket, pxr::UsdShadeMaterial &usd_material, pxr::UsdShadeInput &usd_input, const std::string &active_uvmap_name, ReportList *reports)
pxr::UsdShadeMaterial create_usd_material(const USDExporterContext &usd_export_context, pxr::SdfPath usd_path, const Material *material, const std::string &active_uvmap_name, ReportList *reports)
static void set_scale_bias(pxr::UsdShadeShader &usd_shader, const pxr::GfVec4f scale, const pxr::GfVec4f bias)
std::string make_safe_primvar_name(const StringRef name, bool allow_unicode)
Definition usd_utils.cc:88
static std::string get_tex_image_asset_filepath(const USDExporterContext &usd_export_context, const bNode *node)
static void create_uvmap_shader(const USDExporterContext &usd_export_context, const bNodeLink *uvmap_link, const pxr::UsdShadeMaterial &usd_material, const pxr::UsdShadeInput &usd_input, const std::string &active_uvmap_name, ReportList *reports)
MaterialX::DocumentPtr export_to_materialx(const Depsgraph *depsgraph, const Material *material, const ExportParams &export_params)
static const pxr::TfToken surface("surface", pxr::TfToken::Immortal)
static const pxr::TfToken raw("raw", pxr::TfToken::Immortal)
static const pxr::TfToken varname("varname", pxr::TfToken::Immortal)
static const pxr::TfToken rotation("rotation", pxr::TfToken::Immortal)
static const pxr::TfToken mirror("mirror", pxr::TfToken::Immortal)
static const pxr::TfToken opacity("opacity", pxr::TfToken::Immortal)
static const pxr::TfToken rgb("rgb", pxr::TfToken::Immortal)
static const pxr::TfToken roughness("roughness", pxr::TfToken::Immortal)
static const pxr::TfToken specular("specular", pxr::TfToken::Immortal)
static const pxr::TfToken wrapS("wrapS", pxr::TfToken::Immortal)
static const pxr::TfToken clearcoatRoughness("clearcoatRoughness", pxr::TfToken::Immortal)
static const pxr::TfToken diffuse_color("diffuseColor", pxr::TfToken::Immortal)
static const pxr::TfToken opacityThreshold("opacityThreshold", pxr::TfToken::Immortal)
static const pxr::TfToken clamp("clamp", pxr::TfToken::Immortal)
static const pxr::TfToken preview_surface("UsdPreviewSurface", pxr::TfToken::Immortal)
static const pxr::TfToken out("out", pxr::TfToken::Immortal)
static const pxr::TfToken g("g", pxr::TfToken::Immortal)
static const pxr::TfToken clearcoat("clearcoat", pxr::TfToken::Immortal)
static const pxr::TfToken metallic("metallic", pxr::TfToken::Immortal)
static const pxr::TfToken bias("bias", pxr::TfToken::Immortal)
static const pxr::TfToken b("b", pxr::TfToken::Immortal)
static const pxr::TfToken black("black", pxr::TfToken::Immortal)
static const pxr::TfToken a("a", pxr::TfToken::Immortal)
static const pxr::TfToken file("file", pxr::TfToken::Immortal)
static const pxr::TfToken in("in", pxr::TfToken::Immortal)
static const pxr::TfToken scale("scale", pxr::TfToken::Immortal)
static const pxr::TfToken primvar_float3("UsdPrimvarReader_float3", pxr::TfToken::Immortal)
static const pxr::TfToken preview_shader("previewShader", pxr::TfToken::Immortal)
static const pxr::TfToken emissive_color("emissiveColor", pxr::TfToken::Immortal)
static const pxr::TfToken primvar_vector("UsdPrimvarReader_vector", pxr::TfToken::Immortal)
static const pxr::TfToken sourceColorSpace("sourceColorSpace", pxr::TfToken::Immortal)
static const pxr::TfToken sRGB("sRGB", pxr::TfToken::Immortal)
static const pxr::TfToken r("r", pxr::TfToken::Immortal)
static const pxr::TfToken UsdTransform2d("UsdTransform2d", pxr::TfToken::Immortal)
static const pxr::TfToken primvar_float2("UsdPrimvarReader_float2", pxr::TfToken::Immortal)
static const pxr::TfToken ior("ior", pxr::TfToken::Immortal)
static const pxr::TfToken displacement("displacement", pxr::TfToken::Immortal)
static const pxr::TfToken result("result", pxr::TfToken::Immortal)
static const pxr::TfToken st("st", pxr::TfToken::Immortal)
static const pxr::TfToken uv_texture("UsdUVTexture", pxr::TfToken::Immortal)
static const pxr::TfToken translation("translation", pxr::TfToken::Immortal)
static const pxr::TfToken normal("normal", pxr::TfToken::Immortal)
static const pxr::TfToken wrapT("wrapT", pxr::TfToken::Immortal)
static const pxr::TfToken primvar_float("UsdPrimvarReader_float", pxr::TfToken::Immortal)
static const pxr::TfToken repeat("repeat", pxr::TfToken::Immortal)
BMesh Iterators.
char * BKE_image_get_tile_strformat(const char *filepath, eUDIM_TILE_FORMAT *r_tile_format)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
char * STRNCPY(char(&dst)[N], const char *src)
@ RPT_WARNING
Definition BKE_report.hh:40
MINLINE void copy_v3_v3(float r[3], const float a[3])
bool BLI_path_abs(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1
@ SHD_IMAGE_EXTENSION_EXTEND
@ SHD_IMAGE_EXTENSION_CLIP
@ SHD_IMAGE_EXTENSION_MIRROR
@ SHD_IMAGE_EXTENSION_REPEAT
@ SHD_ATTRIBUTE_GEOMETRY
bool BLI_exists(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:404
void BLI_string_replace_char(char *str, char src, char dst) ATTR_NONNULL(1)
@ NODE_MATH_LESS_THAN
void BKE_image_format_from_imbuf(ImageFormatData *im_format, const ImBuf *imbuf)
unsigned int uint32_t
Definition BKE_text.h:81
void BKE_image_set_filepath_from_tile_number(char *filepath, const char *pattern, eUDIM_TILE_FORMAT tile_format, int tile_number)
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
unsigned char uchar
Definition BKE_text.h:58
int BLI_path_cmp_normalized(const char *p1, const char *p2) ATTR_NONNULL(1
int BKE_image_path_ext_from_imformat_ensure(char *filepath, size_t filepath_maxncpy, const ImageFormatData *im_format)
int BLI_path_normalize(char *path) ATTR_NONNULL(1)
ImBuf * BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
int BLI_copy(const char *path_src, const char *path_dst) ATTR_NONNULL()
char BKE_ftype_to_imtype(eImbFileType ftype, const ImbFormatOptions *options)
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
eImbFileType IMB_test_image_type_from_memory(const unsigned char *buf, size_t buf_size)
void BLI_string_split_suffix(const char *string, size_t string_maxlen, char *r_body, char *r_suf) ATTR_NONNULL(1
bool BKE_image_is_filename_tokenized(char *filepath)
static CLG_LogRef LOG
Definition logging.cpp:12
@ NODE_VECTOR_MATH_MULTIPLY_ADD
bool BKE_image_has_packedfile(const Image *image)
int BKE_image_path_ext_from_imtype_ensure(char *filepath, size_t filepath_maxncpy, char imtype)
eUDIM_TILE_FORMAT
Definition BKE_image.hh:505
@ UDIM_TILE_FORMAT_NONE
Definition BKE_image.hh:506
@ UDIM_TILE_FORMAT_UDIM
Definition BKE_image.hh:507
bool BKE_imbuf_write_as(ImBuf *ibuf, const char *filepath, const ImageFormatData *imf, bool save_copy)
void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
@ String
Definition types.hh:154
struct PackedFile * packedfile
eNodeSocketDatatype type
struct bNodeLink * link
ListBaseT< bNodeSocket > inputs
wmJobWorkerStatus * worker_status
Definition usd.hh:184