Blender V5.3
io/usd/hydra/material.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2022 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "material.hh"
6
7#include <pxr/base/tf/stringUtils.h>
8#include <pxr/imaging/hd/material.h>
9#include <pxr/imaging/hd/materialBindingSchema.h>
10#include <pxr/imaging/hd/materialBindingsSchema.h>
11#include <pxr/imaging/hd/materialConnectionSchema.h>
12#include <pxr/imaging/hd/materialNetworkSchema.h>
13#include <pxr/imaging/hd/materialNodeParameterSchema.h>
14#include <pxr/imaging/hd/materialNodeSchema.h>
15#include <pxr/imaging/hd/materialSchema.h>
16#include <pxr/imaging/hd/retainedDataSource.h>
17#include <pxr/imaging/hd/tokens.h>
18#include <pxr/usd/usdShade/material.h>
19#include <pxr/usdImaging/usdImaging/materialParamUtils.h>
20
21#ifdef WITH_MATERIALX
22# include <pxr/usd/usdMtlx/reader.h>
23#endif
24
26
27#include "DNA_material_types.h"
28
29#include "CLG_log.h"
30
31#include "image.hh"
32#include "scene_index.hh"
33
36#include "usd_private.hh"
37
38#ifdef WITH_MATERIALX
40#endif
41
42namespace blender::io::hydra {
43
44static pxr::HdContainerDataSourceHandle build_material_node_data_source(
45 const pxr::HdMaterialNode2 &node)
46{
47 /* Parameters. */
48 HdContainerBuilder params;
49 params.reserve(node.parameters.size());
50 for (const auto &param : node.parameters) {
51 params.add(param.first,
52 pxr::HdMaterialNodeParameterSchema::Builder()
53 .SetValue(pxr::HdRetainedSampledDataSource::New(param.second))
54 .Build());
55 }
56
57 /* Input connections. */
58 HdContainerBuilder inputs;
59 inputs.reserve(node.inputConnections.size());
60 for (const auto &input : node.inputConnections) {
62 conn_values.reserve(input.second.size());
63 for (const pxr::HdMaterialConnection2 &conn : input.second) {
64 conn_values.append(
65 pxr::HdMaterialConnectionSchema::Builder()
66 .SetUpstreamNodePath(pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(
67 conn.upstreamNode.GetToken()))
68 .SetUpstreamNodeOutputName(pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(
69 conn.upstreamOutputName))
70 .Build());
71 }
72 inputs.add(input.first,
73 pxr::HdRetainedSmallVectorDataSource::New(conn_values.size(), conn_values.data()));
74 }
75
76 return pxr::HdMaterialNodeSchema::Builder()
77 .SetParameters(params.build())
78 .SetInputConnections(inputs.build())
79 .SetNodeIdentifier(pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(node.nodeTypeId))
80 .Build();
81}
82
83static pxr::HdContainerDataSourceHandle build_material_network_data_source(
84 const pxr::HdMaterialNetworkMap &network_map)
85{
86 const pxr::HdMaterialNetwork2 net2 = pxr::HdConvertToHdMaterialNetwork2(network_map);
87
88 /* Nodes. */
90 nodes.reserve(net2.nodes.size());
91 for (const auto &entry : net2.nodes) {
92 nodes.add(entry.first.GetToken(), build_material_node_data_source(entry.second));
93 }
94
95 /* Terminals. */
96 HdContainerBuilder terminals;
97 terminals.reserve(net2.terminals.size());
98 for (const auto &entry : net2.terminals) {
99 terminals.add(
100 entry.first,
101 pxr::HdMaterialConnectionSchema::Builder()
102 .SetUpstreamNodePath(pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(
103 entry.second.upstreamNode.GetToken()))
104 .SetUpstreamNodeOutputName(pxr::HdRetainedTypedSampledDataSource<pxr::TfToken>::New(
105 entry.second.upstreamOutputName))
106 .Build());
107 }
108
109 return pxr::HdMaterialNetworkSchema::Builder()
110 .SetNodes(nodes.build())
111 .SetTerminals(terminals.build())
112 .Build();
113}
114
116{
117 /* Create temporary in memory stage to avoid collisions with other materials. */
118 pxr::UsdStageRefPtr stage = pxr::UsdStage::CreateInMemory();
119
120 const pxr::SdfPath material_library_path("/_materials");
121 const pxr::SdfPath path = ctx.material_prim_id(material);
122 const pxr::SdfPath usd_material_path = material_library_path.AppendChild(
123 pxr::TfToken(path.GetElementString()));
124
125 /* Create USD export content to reuse USD file export code. */
126 io::usd::USDExportParams export_params;
127 export_params.relative_paths = false;
128 export_params.export_textures = false; /* Don't copy all textures, is slow. */
129 export_params.evaluation_mode = DEG_get_mode(ctx.depsgraph);
130
131 const pxr::UsdTimeCode time = pxr::UsdTimeCode::Default();
132 auto get_time_code = [time]() { return time; };
133
134 io::usd::USDExporterContext export_context{ctx.bmain,
135 ctx.depsgraph,
136 stage,
137 material_library_path,
138 get_time_code,
139 export_params,
142 /* Create USD material. */
143 pxr::UsdShadeMaterial usd_material;
144#ifdef WITH_MATERIALX
145 if (ctx.use_materialx) {
146 const std::string material_name = pxr::TfMakeValidIdentifier(material->id.name);
147 nodes::materialx::ExportParams materialx_export_params{
148 material_name, cache_or_get_image_file, "st", "UVMap"};
149 MaterialX::DocumentPtr doc = nodes::materialx::export_to_materialx(
150 ctx.depsgraph, material, materialx_export_params);
151 pxr::UsdMtlxRead(doc, stage);
152
153 if (pxr::UsdPrim materials = stage->GetPrimAtPath(pxr::SdfPath("/MaterialX/Materials"))) {
154 pxr::UsdPrimSiblingRange children = materials.GetChildren();
155 if (!children.empty()) {
156 usd_material = pxr::UsdShadeMaterial(*children.begin());
157 }
158 }
159 if (!usd_material) {
160 CLOG_WARN(LOG_HYDRA_SCENE_INDEX, "MaterialX export failed for '%s'", material->id.name + 2);
161 }
162 else {
163 /* Fall back to UsdPreviewSurface if MaterialX did not have a valid surface,
164 * matching USD export behavior. */
165 const pxr::UsdShadeOutput surface = usd_material.GetSurfaceOutput();
166 if (!surface || !surface.HasConnectedSource()) {
167 io::usd::create_usd_viewport_material(export_context, material, usd_material);
168 }
169 }
170 }
171 else
172#endif
173 {
174 usd_material = io::usd::create_usd_material(
175 export_context, usd_material_path, material, "st", nullptr);
176 }
177
178 EmittedMaterial entry;
179 entry.path = path;
180 /* Double side is a geometry level parameter in USD. */
181 entry.double_sided = (material->blend_flag & MA_BL_CULL_BACKFACE) == 0;
182
183 if (!usd_material) {
184 return entry;
185 }
186
187 /* Build the material network from the surface, volume and displacement terminals. */
188 const std::vector<pxr::TfToken> render_contexts(ctx.material_render_contexts.begin(),
189 ctx.material_render_contexts.end());
190 const std::vector<pxr::TfToken> source_types(ctx.shader_source_types.begin(),
191 ctx.shader_source_types.end());
192 pxr::HdMaterialNetworkMap network_map;
193 if (pxr::UsdShadeShader surface = usd_material.ComputeSurfaceSource(render_contexts)) {
194 pxr::UsdImagingBuildHdMaterialNetworkFromTerminal(surface.GetPrim(),
195 pxr::HdMaterialTerminalTokens->surface,
196 source_types,
197 render_contexts,
198 &network_map,
199 time);
200 }
201 if (pxr::UsdShadeShader volume = usd_material.ComputeVolumeSource(render_contexts)) {
202 pxr::UsdImagingBuildHdMaterialNetworkFromTerminal(volume.GetPrim(),
203 pxr::HdMaterialTerminalTokens->volume,
204 source_types,
205 render_contexts,
206 &network_map,
207 time);
208 }
209 if (pxr::UsdShadeShader displacement = usd_material.ComputeDisplacementSource(render_contexts)) {
210 pxr::UsdImagingBuildHdMaterialNetworkFromTerminal(displacement.GetPrim(),
211 pxr::HdMaterialTerminalTokens->displacement,
212 source_types,
213 render_contexts,
214 &network_map,
215 time);
216 }
217
218 if (network_map.terminals.empty()) {
219 return entry;
220 }
221
222 /* Publish the network under every render context plus the universal fallback.
223 * Blender does have solid viewport material parameters but Hydra is only used for
224 * the rendered display mode. */
225 pxr::HdContainerDataSourceHandle network_ds = build_material_network_data_source(network_map);
227 b.reserve(render_contexts.size() + 1);
228 for (const pxr::TfToken &c : render_contexts) {
229 b.add(c, network_ds);
230 }
231 b.add(pxr::HdMaterialSchemaTokens->universalRenderContext, network_ds);
232 entry.data_source = pxr::HdRetainedContainerDataSource::New(
233 pxr::HdMaterialSchema::GetSchemaToken(), b.build());
234 return entry;
235}
236
237} // namespace blender::io::hydra
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
int64_t size() const
void append(const T &value)
void reserve(const int64_t min_capacity)
static pxr::HdContainerDataSourceHandle build_material_network_data_source(const pxr::HdMaterialNetworkMap &network_map)
static pxr::HdContainerDataSourceHandle build_material_node_data_source(const pxr::HdMaterialNode2 &node)
CLG_LogRef * LOG_HYDRA_SCENE_INDEX
std::string cache_or_get_image_file(Main *bmain, Scene *scene, Image *image, ImageUser *iuser)
EmittedMaterial build_emitted_material(const PopulateContext &ctx, const Material *material)
std::string image_cache_file_path()
void create_usd_viewport_material(const USDExporterContext &usd_export_context, const Material *material, const pxr::UsdShadeMaterial &usd_material)
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)
MaterialX::DocumentPtr export_to_materialx(const Depsgraph *depsgraph, const Material *material, const ExportParams &export_params)
eEvaluationMode DEG_get_mode(const Depsgraph *graph)
pxr::HdContainerDataSourceHandle data_source
void add(const pxr::TfToken &name, const T &value)
Definition util.hh:51
pxr::HdContainerDataSourceHandle build() const
Definition util.hh:63
pxr::SdfPath material_prim_id(const Material *material) const
Span< pxr::TfToken > material_render_contexts
enum eEvaluationMode evaluation_mode
Definition usd.hh:149