forked from Autodesk/maya-usd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaterial.cpp
3825 lines (3346 loc) · 149 KB
/
material.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright 2020 Autodesk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "material.h"
#include "debugCodes.h"
#include "pxr/usd/sdr/registry.h"
#include "pxr/usd/sdr/shaderNode.h"
#include "renderDelegate.h"
#include "tokens.h"
#include <mayaUsd/base/tokens.h>
#include <mayaUsd/render/vp2RenderDelegate/colorManagementPreferences.h>
#include <mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h>
#include <mayaUsd/render/vp2ShaderFragments/shaderFragments.h>
#include <mayaUsd/utils/hash.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/gf/matrix4f.h>
#include <pxr/base/gf/vec2f.h>
#include <pxr/base/gf/vec3f.h>
#include <pxr/base/gf/vec4f.h>
#include <pxr/base/tf/diagnostic.h>
#include <pxr/base/tf/getenv.h>
#include <pxr/base/tf/pathUtils.h>
#include <pxr/imaging/hd/sceneDelegate.h>
#ifdef WANT_MATERIALX_BUILD
#include <pxr/imaging/hdMtlx/hdMtlx.h>
#endif
#include <pxr/pxr.h>
#include <pxr/usd/ar/packageUtils.h>
#include <pxr/usd/sdf/assetPath.h>
#include <pxr/usd/sdr/registry.h>
#include <pxr/usd/usdHydra/tokens.h>
#include <pxr/usd/usdUtils/pipeline.h>
#include <pxr/usdImaging/usdImaging/textureUtils.h>
#include <pxr/usdImaging/usdImaging/tokens.h>
#include <maya/M3dView.h>
#include <maya/MEventMessage.h>
#include <maya/MFragmentManager.h>
#include <maya/MGlobal.h>
#include <maya/MProfiler.h>
#include <maya/MSceneMessage.h>
#include <maya/MShaderManager.h>
#include <maya/MStatus.h>
#include <maya/MString.h>
#include <maya/MStringArray.h>
#include <maya/MTextureManager.h>
#include <maya/MUintArray.h>
#include <maya/MViewport2Renderer.h>
#ifdef WANT_MATERIALX_BUILD
#include <mayaUsd/render/MaterialXGenOgsXml/CombinedMaterialXVersion.h>
#include <mayaUsd/render/MaterialXGenOgsXml/OgsFragment.h>
#include <mayaUsd/render/MaterialXGenOgsXml/OgsXmlGenerator.h>
#include <mayaUsd/render/MaterialXGenOgsXml/ShaderGenUtil.h>
#include <MaterialXCore/Document.h>
#include <MaterialXFormat/File.h>
#include <MaterialXFormat/Util.h>
#include <MaterialXGenGlsl/GlslShaderGenerator.h>
#include <MaterialXGenShader/HwShaderGenerator.h>
#include <MaterialXGenShader/ShaderStage.h>
#include <MaterialXGenShader/Util.h>
#include <MaterialXRender/ImageHandler.h>
#endif
#include <pxr/imaging/hdSt/udimTextureObject.h>
#include <pxr/imaging/hio/image.h>
#include <boost/functional/hash.hpp>
#include <ghc/filesystem.hpp>
#include <tbb/parallel_for.h>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
#ifdef WANT_MATERIALX_BUILD
namespace mx = MaterialX;
#endif
PXR_NAMESPACE_OPEN_SCOPE
static bool _IsDisabledAsyncTextureLoading()
{
static const MString kOptionVarName(MayaUsdOptionVars->DisableAsyncTextureLoading.GetText());
if (MGlobal::optionVarExists(kOptionVarName)) {
return MGlobal::optionVarIntValue(kOptionVarName);
}
return true;
}
// Refresh viewport duration (in milliseconds)
static const std::size_t kRefreshDuration { 1000 };
namespace {
// USD `UsdImagingDelegate::ApplyPendingUpdates()` would request to
// remove the material then recreate, this is causing texture disappearing
// when user manipulating a prim (while holding mouse buttion).
// We hold a copy of the texture info reference, so that the texture will not
// get released immediately along with material removal.
// If the textures would have been requested to reload in `ApplyPendingUpdates()`,
// we could still reuse the loaded one from cache, otherwise the idle task can
// safely release the texture.
class _TransientTexturePreserver
{
public:
static _TransientTexturePreserver& GetInstance()
{
static _TransientTexturePreserver sInstance;
return sInstance;
}
void PreserveTextures(HdVP2LocalTextureMap& localTextureMap)
{
if (_isExiting) {
return;
}
// Locking to avoid race condition for insertion to pendingRemovalTextures
std::lock_guard<std::mutex> lock(_removalTaskMutex);
// Avoid creating multiple idle tasks if there is already one
bool hasRemovalTask = !_pendingRemovalTextures.empty();
for (const auto& info : localTextureMap) {
_pendingRemovalTextures.emplace(info.second);
}
if (!hasRemovalTask) {
// Note that we do not need locking inside idle task since it will
// only be executed serially.
MGlobal::executeTaskOnIdle(
[](void* data) { _TransientTexturePreserver::GetInstance().Clear(); });
}
}
void Clear() { _pendingRemovalTextures.clear(); }
void OnMayaExit()
{
_isExiting = true;
Clear();
}
private:
_TransientTexturePreserver() = default;
~_TransientTexturePreserver() = default;
std::unordered_set<HdVP2TextureInfoSharedPtr> _pendingRemovalTextures;
std::mutex _removalTaskMutex;
bool _isExiting = false;
};
// clang-format off
TF_DEFINE_PRIVATE_TOKENS(
_tokens,
(file)
(opacity)
(opacityThreshold)
(existence)
(transmission)
(transparency)
(alpha)
(alpha_mode)
(transmission_weight)
(geometry_opacity)
(useSpecularWorkflow)
(st)
(varname)
(sourceColorSpace)
((auto_, "auto"))
(sRGB)
(raw)
(fallback)
(input)
(output)
(rgb)
(r)
(g)
(b)
(a)
(xyz)
(x)
(y)
(z)
(w)
(Float4ToFloatX)
(Float4ToFloatY)
(Float4ToFloatZ)
(Float4ToFloatW)
(Float4ToFloat3)
(Float3ToFloatX)
(Float3ToFloatY)
(Float3ToFloatZ)
// When using OCIO from Maya:
(Maya_OCIO_)
(toColor3ForCM)
(extract)
(gltf_pbr)
(UsdPrimvarReader_color)
(UsdPrimvarReader_vector)
(Unknown)
(Computed)
// XXX Deprecated in PXR_VERSION > 2211
(result)
(cardsUv)
(diffuseColor)
(glslfx)
(UsdDrawModeCards)
((DrawMode, "drawMode.glslfx"))
(mayaIsBackFacing)
(isBackfacing)
(FallbackShader)
// Added in PXR_VERSION >= 2311
((ColorSpacePrefix, "colorSpace:"))
);
// clang-format on
#ifdef WANT_MATERIALX_BUILD
// clang-format off
TF_DEFINE_PRIVATE_TOKENS(
_mtlxTokens,
(USD_Mtlx_VP2_Material)
(NG_Maya)
(ND_surface)
(ND_standard_surface_surfaceshader)
(filename)
(i_geomprop_)
(geomprop)
(uaddressmode)
(vaddressmode)
(filtertype)
(closest)
(cubic)
(channels)
(out)
(surfaceshader)
// Texcoord reader identifiers:
(texcoord)
(index)
(UV0)
(geompropvalue)
(ST_reader)
(vector2)
// Tangent related identifiers:
(tangent)
(normalmap)
(arbitrarytangents)
(texcoordtangents)
(Tworld)
(Tobject)
(Tw_reader)
(vector3)
(transformvector)
(constant)
(value)
(Tw_to_To)
(in)
(space)
(fromspace)
(tospace)
(string)
(world)
(object)
(model)
(outTworld)
(outTobject)
(tangent_fix)
// Basic color-correction:
(outColor)
(colorSpace)
(color3)
(color4)
);
// These attribute names usually indicate we have a source color space to handle.
const auto _mtlxKnownColorSpaceAttrs
= std::vector<TfToken> { _tokens->sourceColorSpace, _mtlxTokens->colorSpace };
#ifndef HAS_COLOR_MANAGEMENT_SUPPORT_API
// Maps from a known Maya target color space name to the corresponding color correct category.
const std::unordered_map<std::string, std::string> _mtlxColorCorrectCategoryMap = {
{ "scene-linear Rec.709-sRGB", "MayaND_sRGBtoLinrec709_" },
{ "scene-linear Rec 709/sRGB", "MayaND_sRGBtoLinrec709_" },
{ "ACEScg", "MayaND_sRGBtoACEScg_" },
{ "ACES2065_1", "MayaND_sRGBtoACES2065_" },
{ "ACES2065-1", "MayaND_sRGBtoACES2065_" },
{ "scene-linear DCI-P3 D65", "MayaND_sRGBtoLinDCIP3D65_" },
{ "scene-linear DCI-P3", "MayaND_sRGBtoLinDCIP3D65_" },
{ "scene-linear Rec.2020", "MayaND_sRGBtoLinrec2020_" },
{ "scene-linear Rec 2020", "MayaND_sRGBtoLinrec2020_" },
};
#endif
// clang-format on
struct _MaterialXData
{
_MaterialXData()
{
_mtlxSearchPath = HdMtlxSearchPaths();
#if PXR_VERSION > 2311
_mtlxLibrary = HdMtlxStdLibraries();
#else
_mtlxLibrary = mx::createDocument();
mx::loadLibraries({}, _mtlxSearchPath, _mtlxLibrary);
#endif
_FixLibraryTangentInputs(_mtlxLibrary);
mx::OgsXmlGenerator::setUseLightAPI(MAYA_LIGHTAPI_VERSION_2);
// This environment variable is defined in USD: pxr\usd\usdMtlx\parser.cpp
static const std::string env = TfGetenv("USDMTLX_PRIMARY_UV_NAME");
_mainUvSetName = env.empty() ? UsdUtilsGetPrimaryUVSetName().GetString() : env;
}
MaterialX::FileSearchPath _mtlxSearchPath; //!< MaterialX library search path
MaterialX::DocumentPtr _mtlxLibrary; //!< MaterialX library
std::string _mainUvSetName; //!< Main UV set name
private:
void _FixLibraryTangentInputs(MaterialX::DocumentPtr& mtlxLibrary);
};
_MaterialXData& _GetMaterialXData()
{
static std::unique_ptr<_MaterialXData> materialXData;
static std::once_flag once;
std::call_once(once, []() { materialXData.reset(new _MaterialXData()); });
return *materialXData;
}
//! Return true if that node parameter has topological impact on the generated code.
//
// Swizzle and geompropvalue nodes are known to have an attribute that affects
// shader topology. The "channels" and "geomprop" attributes will have effects at the codegen level,
// not at runtime. Yes, this is forbidden internal knowledge of the MaterialX shader generator and
// we might get other nodes like this one in a future update.
//
// The index input of the texcoord and geomcolor nodes affect which stream to read and is topo
// affecting.
//
// Any geometric input that can specify model/object/world space is also topo affecting.
//
// Things to look out for are parameters of type "string" and parameters with the "uniform"
// metadata. These need to be reviewed against the code used in their registered
// implementations (see registerImplementation calls in the GlslShaderGenerator CTOR). Sadly
// we can not make that a rule because the filename of an image node is both a "string" and
// has the "uniform" metadata, yet is not affecting topology.
bool _IsTopologicalNode(const HdMaterialNode2& inNode)
{
mx::NodeDefPtr nodeDef
= _GetMaterialXData()._mtlxLibrary->getNodeDef(inNode.nodeTypeId.GetString());
if (nodeDef) {
return MaterialXMaya::ShaderGenUtil::TopoNeutralGraph::isTopologicalNodeDef(*nodeDef);
}
return false;
}
#if PXR_VERSION >= 2311
// Hydra in USD 23.11 will add a "colorspace:Foo" parameter matching color managed "Foo" parameter
bool _IsHydraColorSpace(const TfToken& paramName)
{
if (paramName.GetString().rfind(_tokens->ColorSpacePrefix.GetString(), 0) == 0) {
return true;
}
return std::find(_mtlxKnownColorSpaceAttrs.begin(), _mtlxKnownColorSpaceAttrs.end(), paramName)
!= _mtlxKnownColorSpaceAttrs.end();
};
#endif
bool _IsMaterialX(const HdMaterialNode& node)
{
SdrRegistry& shaderReg = SdrRegistry::GetInstance();
NdrNodeConstPtr ndrNode = shaderReg.GetNodeByIdentifier(node.identifier);
return ndrNode && ndrNode->GetSourceType() == HdVP2Tokens->mtlx;
}
bool _MxHasFilenameInput(const mx::NodeDefPtr nodeDef)
{
for (const auto& input : nodeDef->getActiveInputs()) {
if (input->getType() == _mtlxTokens->filename.GetString()) {
return true;
}
}
return false;
}
#ifdef HAS_COLOR_MANAGEMENT_SUPPORT_API
bool _MxHasFilenameInput(const HdMaterialNode2& inNode)
{
mx::NodeDefPtr nodeDef
= _GetMaterialXData()._mtlxLibrary->getNodeDef(inNode.nodeTypeId.GetString());
if (nodeDef) {
return _MxHasFilenameInput(nodeDef);
}
return false;
}
#endif
//! Helper function to generate a topo hash that can be used to detect if two networks share the
// same topology.
size_t _GenerateNetwork2TopoHash(const HdMaterialNetwork2& materialNetwork)
{
#ifdef HAS_COLOR_MANAGEMENT_SUPPORT_API
bool hasTextureNode = false;
#endif
// The HdMaterialNetwork2 structure is stable. Everything is alphabetically sorted.
size_t topoHash = 0;
for (const auto& c : materialNetwork.terminals) {
MayaUsd::hash_combine(topoHash, hash_value(c.first));
MayaUsd::hash_combine(topoHash, hash_value(c.second.upstreamNode));
MayaUsd::hash_combine(topoHash, hash_value(c.second.upstreamOutputName));
}
for (const auto& nodePair : materialNetwork.nodes) {
MayaUsd::hash_combine(topoHash, hash_value(nodePair.first));
const auto& node = nodePair.second;
MayaUsd::hash_combine(topoHash, hash_value(node.nodeTypeId));
if (_IsTopologicalNode(node)) {
// We need to capture values that affect topology:
for (auto const& p : node.parameters) {
MayaUsd::hash_combine(topoHash, hash_value(p.first));
MayaUsd::hash_combine(topoHash, hash_value(p.second));
}
}
#ifdef HAS_COLOR_MANAGEMENT_SUPPORT_API
if (MayaUsd::ColorManagementPreferences::Active()) {
// Explicit color management parameters affect topology:
#if PXR_VERSION < 2311
for (auto&& cmName : _mtlxKnownColorSpaceAttrs) {
auto cmIt = node.parameters.find(cmName);
if (cmIt != node.parameters.end()) {
MayaUsd::hash_combine(topoHash, hash_value(cmIt->first));
if (cmIt->second.IsHolding<TfToken>()) {
auto const& colorSpace = cmIt->second.UncheckedGet<TfToken>();
MayaUsd::hash_combine(topoHash, hash_value(colorSpace));
} else if (cmIt->second.IsHolding<std::string>()) {
auto const& colorSpace = cmIt->second.UncheckedGet<std::string>();
MayaUsd::hash_combine(topoHash, std::hash<std::string> {}(colorSpace));
}
}
}
#else
for (auto&& param : node.parameters) {
if (_IsHydraColorSpace(param.first)) {
MayaUsd::hash_combine(topoHash, hash_value(param.first));
if (param.second.IsHolding<TfToken>()) {
auto const& colorSpace = param.second.UncheckedGet<TfToken>();
MayaUsd::hash_combine(topoHash, hash_value(colorSpace));
} else if (param.second.IsHolding<std::string>()) {
auto const& colorSpace = param.second.UncheckedGet<std::string>();
MayaUsd::hash_combine(topoHash, std::hash<std::string> {}(colorSpace));
}
}
}
#endif
if (_MxHasFilenameInput(node)) {
hasTextureNode = true;
}
}
#endif
for (auto const& i : node.inputConnections) {
MayaUsd::hash_combine(topoHash, hash_value(i.first));
for (auto const& c : i.second) {
MayaUsd::hash_combine(topoHash, hash_value(c.upstreamNode));
MayaUsd::hash_combine(topoHash, hash_value(c.upstreamOutputName));
}
}
}
// The specular environment settings used affect the topology of the shader:
MayaUsd::hash_combine(topoHash, MaterialXMaya::OgsFragment::getSpecularEnvKey());
#ifdef HAS_COLOR_MANAGEMENT_SUPPORT_API
if (hasTextureNode) {
MayaUsd::hash_combine(
topoHash,
std::hash<std::string> {}(
MayaUsd::ColorManagementPreferences::RenderingSpaceName().asChar()));
}
#endif
return topoHash;
}
//! Helper function to generate a XML string about nodes, relationships and primvars in the
//! specified material network.
std::string _GenerateXMLString(const HdMaterialNetwork2& materialNetwork)
{
std::ostringstream result;
if (ARCH_LIKELY(!materialNetwork.nodes.empty())) {
result << "<terminals>\n";
for (const auto& c : materialNetwork.terminals) {
result << " <terminal name=\"" << c.first << "\" dest=\"" << c.second.upstreamNode
<< "\"/>\n";
}
result << "</terminals>\n";
result << "<nodes>\n";
for (const auto& nodePair : materialNetwork.nodes) {
const auto& node = nodePair.second;
const bool hasChildren = !(node.parameters.empty() && node.inputConnections.empty());
result << " <node path=\"" << nodePair.first << "\" id=\"" << node.nodeTypeId << "\""
<< (hasChildren ? ">\n" : "/>\n");
if (!node.parameters.empty()) {
result << " <parameters>\n";
for (auto const& p : node.parameters) {
result << " <param name=\"" << p.first << "\" value=\"" << p.second
<< "\"/>\n";
}
result << " </parameters>\n";
}
if (!node.inputConnections.empty()) {
result << " <inputs>\n";
for (auto const& i : node.inputConnections) {
if (i.second.size() == 1) {
result << " <input name=\"" << i.first << "\" dest=\""
<< i.second.back().upstreamNode << "."
<< i.second.back().upstreamOutputName << "\"/>\n";
} else {
// Extremely rare case seen only with array connections.
result << " <input name=\"" << i.first << "\">\n";
result << " <connections>\n";
for (auto const& c : i.second) {
result << " <cnx dest=\"" << c.upstreamNode << "."
<< c.upstreamOutputName << "\"/>\n";
}
result << " </connections>\n";
}
}
result << " </inputs>\n";
}
if (hasChildren) {
result << " </node>\n";
}
}
result << "</nodes>\n";
// We do not add primvars. They are found later while traversing the actual effect instance.
}
return result.str();
}
// MaterialX FA nodes will "upgrade" the in2 uniform to whatever the vector type it needs for its
// arithmetic operation. So we need to "upgrade" the value we want to set as well.
//
// One example: ND_multiply_vector3FA(vector3 in1, float in2) will generate a float3 in2 uniform.
bool _IsFAParameter(const HdMaterialNode& node, const MString& paramName)
{
auto _endsWith = [](const std::string& s, const std::string& suffix) {
return s.size() >= suffix.size()
&& s.compare(s.size() - suffix.size(), std::string::npos, suffix) == 0;
};
if (_IsMaterialX(node) && _endsWith(paramName.asChar(), "_in2")
&& _endsWith(node.identifier.GetString(), "FA")) {
return true;
}
return false;
}
// Recursively traverse a node graph, depth first, to find target node
mx::NodePtr _RecursiveFindNode(const mx::NodePtr& node, const TfToken& target)
{
mx::NodePtr retVal;
for (auto const& input : node->getInputs()) {
if (mx::NodePtr downstreamNode = input->getConnectedNode()) {
if (mx::NodeDefPtr nodeDef = downstreamNode->getNodeDef()) {
if (nodeDef->getNodeString() == _mtlxTokens->geompropvalue.GetString()
&& downstreamNode->getType() == _mtlxTokens->vector2.GetString()) {
retVal = downstreamNode;
break;
}
}
retVal = _RecursiveFindNode(downstreamNode, target);
if (retVal) {
break;
}
}
}
return retVal;
}
// We have a few library surface nodes that require tangent inputs, but since the tangent input is
// not expressed in the interface, we will miss it in the _AddMissingTangents function. This
// function goes thru the NodeGraphs in the library and fixes the issue by adding the missing input.
//
// This is done only once, after the libraries have been read.
//
// We voluntarily did not expose a tangent input on the blinn and phong MaterialX nodes in order to
// test this code, but the real target is UsdPreviewSurface.
//
// Note for future self. In some far future, we might start seeing surface shaders that are built
// from other surface shaders. This might require percolating the tangent interface by re-running
// the main loop once for each expected nesting level (or until the loop runs without updating any
// NodeDef).
void _MaterialXData::_FixLibraryTangentInputs(mx::DocumentPtr& mtlxDoc)
{
for (mx::NodeGraphPtr nodeGraph : mtlxDoc->getNodeGraphs()) {
mx::NodeDefPtr graphDef = nodeGraph->getNodeDef();
if (!graphDef) {
continue;
}
auto outputs = graphDef->getActiveOutputs();
if (outputs.empty()
|| outputs.front()->getType() != _mtlxTokens->surfaceshader.GetString()) {
continue;
}
bool hasTangentInput = false;
for (mx::InputPtr nodeInput : graphDef->getActiveInputs()) {
if (nodeInput->hasDefaultGeomPropString()) {
const std::string& geom = nodeInput->getDefaultGeomPropString();
if (geom == _mtlxTokens->Tworld.GetString()
|| geom == _mtlxTokens->Tobject.GetString()) {
hasTangentInput = true;
break;
}
}
}
if (hasTangentInput) {
continue;
}
mx::InputPtr tangentInput;
for (mx::NodePtr node : nodeGraph->getNodes()) {
mx::NodeDefPtr nodeDef = node->getNodeDef();
if (!nodeDef) {
break;
}
// Check the inputs of the node for Tworld and Tobject default geom properties
for (mx::InputPtr input : nodeDef->getActiveInputs()) {
if (input->hasDefaultGeomPropString()) {
const std::string& geomPropString = input->getDefaultGeomPropString();
if ((geomPropString == _mtlxTokens->Tworld.GetString()
|| geomPropString == _mtlxTokens->Tobject.GetString())
&& node->getConnectedNodeName(input->getName()).empty()) {
if (!tangentInput) {
tangentInput = graphDef->addInput(
_mtlxTokens->tangent_fix.GetString(),
_mtlxTokens->vector3.GetString());
tangentInput->setDefaultGeomPropString(geomPropString);
}
node->addInput(input->getName(), input->getType())
->setInterfaceName(_mtlxTokens->tangent_fix.GetString());
}
}
}
}
}
}
// USD does not provide tangents, so we need to build them from UV coordinates when possible:
void _AddMissingTangents(mx::DocumentPtr& mtlxDoc)
{
// We will need at least one geompropvalue reader to generate tangents:
mx::NodePtr stReader;
// If we find one implicit texcoord input we can still try to generate texcoord tangents:
bool hasOneImplicitTexcoordInput = false;
// List of all items to fix:
using nodeInput = std::pair<mx::NodePtr, std::string>;
std::vector<nodeInput> graphTworldInputs;
std::vector<nodeInput> graphTobjectInputs;
std::vector<nodeInput> materialTworldInputs;
std::vector<nodeInput> materialTobjectInputs;
std::vector<mx::NodePtr> nodesToReplace;
// The materialnode very often will have a tangent input:
for (mx::NodePtr material : mtlxDoc->getMaterialNodes()) {
if (material->getName() != _mtlxTokens->USD_Mtlx_VP2_Material.GetText()) {
continue;
}
mx::InputPtr surfaceInput = material->getInput(_mtlxTokens->surfaceshader.GetString());
if (surfaceInput) {
material = surfaceInput->getConnectedNode();
}
mx::NodeDefPtr nodeDef = material->getNodeDef();
if (!nodeDef) {
continue;
}
for (mx::InputPtr input : nodeDef->getActiveInputs()) {
if (input->hasDefaultGeomPropString()) {
const std::string& geomPropString = input->getDefaultGeomPropString();
if (geomPropString == _mtlxTokens->Tworld.GetString()
&& !material->getConnectedOutput(input->getName())) {
materialTworldInputs.emplace_back(material, input->getName());
}
if (geomPropString == _mtlxTokens->Tobject.GetString()
&& !material->getConnectedOutput(input->getName())) {
materialTobjectInputs.emplace_back(material, input->getName());
}
if (geomPropString == _mtlxTokens->UV0
&& !material->getConnectedOutput(input->getName())) {
hasOneImplicitTexcoordInput = true;
}
}
}
}
// If we have no nodegraph, but need tangent input on the material node, then we create one:
mx::NodeGraphPtr nodeGraph = mtlxDoc->getNodeGraph(_mtlxTokens->NG_Maya.GetString());
if (!nodeGraph && (!materialTworldInputs.empty() || !materialTobjectInputs.empty())) {
nodeGraph = mtlxDoc->addNodeGraph(_mtlxTokens->NG_Maya.GetString());
}
if (nodeGraph) {
for (mx::NodePtr node : nodeGraph->getNodes()) {
mx::NodeDefPtr nodeDef = node->getNodeDef();
// A missing node def is a very bad sign. No need to process further.
if (!TF_VERIFY(
nodeDef,
"Could not find MaterialX NodeDef for Node '%s'. Please recheck library paths.",
node->getNamePath().c_str())) {
return;
}
if (!stReader && nodeDef->getNodeString() == _mtlxTokens->geompropvalue.GetString()
&& node->getType() == _mtlxTokens->vector2.GetString()) {
// Grab the first st reader we can find. This will be the default one used for
// tangents unless we find something better.
stReader = node;
continue;
}
if (nodeDef->getNodeString() == _mtlxTokens->normalmap.GetString()) {
// That one is even more important, because the texcoord reader attached to the
// image is definitely the one we want for our tangents since it is used for normal
// mapping:
mx::NodePtr downstreamReader = _RecursiveFindNode(node, _mtlxTokens->geompropvalue);
if (downstreamReader) {
stReader = downstreamReader;
}
}
// Check the inputs of the node for Tworld and Tobject default geom properties
for (mx::InputPtr input : nodeDef->getActiveInputs()) {
if (input->hasDefaultGeomPropString()) {
const std::string& geomPropString = input->getDefaultGeomPropString();
if (geomPropString == _mtlxTokens->Tworld.GetString()
&& node->getConnectedNodeName(input->getName()).empty()) {
graphTworldInputs.emplace_back(node, input->getName());
}
if (geomPropString == _mtlxTokens->Tobject.GetString()
&& node->getConnectedNodeName(input->getName()).empty()) {
graphTobjectInputs.emplace_back(node, input->getName());
}
if (geomPropString == _mtlxTokens->UV0
&& node->getConnectedNodeName(input->getName()).empty()) {
hasOneImplicitTexcoordInput = true;
}
}
}
// Check if it is an explicit tangent reader:
if (nodeDef->getNodeString() == _mtlxTokens->tangent.GetString()) {
nodesToReplace.push_back(node);
}
}
if (nodesToReplace.empty() && graphTworldInputs.empty() && graphTobjectInputs.empty()
&& materialTworldInputs.empty() && materialTobjectInputs.empty()) {
// Nothing to do.
return;
}
// Create the tangent generator:
mx::NodePtr tangentGenerator;
if (stReader || hasOneImplicitTexcoordInput) {
tangentGenerator = nodeGraph->addNode(
_mtlxTokens->texcoordtangents.GetString(),
_mtlxTokens->Tw_reader.GetString(),
_mtlxTokens->vector3.GetString());
tangentGenerator->addInput(
_mtlxTokens->texcoord.GetString(), _mtlxTokens->vector2.GetString());
if (stReader) {
// Use an explicit geomprop reader if one was found, otherwise, leave it to the
// implicit geomprop reader code in shadergen.
tangentGenerator->setConnectedNodeName(
_mtlxTokens->texcoord.GetString(), stReader->getName());
}
} else {
tangentGenerator = nodeGraph->addNode(
_mtlxTokens->arbitrarytangents.GetString(),
_mtlxTokens->Tw_reader.GetString(),
_mtlxTokens->vector3.GetString());
}
// We create a world -> object transformation on demand. Computing an object tangent from
// object space normal and position might be more precise though.
mx::NodePtr transformVectorToObject;
mx::NodePtr transformVectorToModel;
auto _createTransformVector = [&](const TfToken& toSpace) {
mx::NodePtr retVal = nodeGraph->addNode(
_mtlxTokens->transformvector.GetString(),
_mtlxTokens->Tw_to_To.GetString(),
_mtlxTokens->vector3.GetString());
retVal->addInput(_mtlxTokens->in.GetString(), _mtlxTokens->vector3.GetString());
retVal->setConnectedNodeName(_mtlxTokens->in.GetString(), tangentGenerator->getName());
retVal->addInput(_mtlxTokens->fromspace.GetString(), _mtlxTokens->string.GetString())
->setValueString(_mtlxTokens->world.GetString());
retVal->addInput(_mtlxTokens->tospace.GetString(), _mtlxTokens->string.GetString())
->setValueString(toSpace.GetString());
return retVal;
};
// Reconnect nodes that require Tworld to the tangent generator:
for (const auto& nodeInput : graphTworldInputs) {
nodeInput.first->addInput(nodeInput.second, _mtlxTokens->vector3.GetString());
nodeInput.first->setConnectedNodeName(nodeInput.second, tangentGenerator->getName());
}
// Reconnect nodes that require Tobject to the tangent generator via a space transform:
for (const auto& nodeInput : graphTobjectInputs) {
if (!transformVectorToObject) {
transformVectorToObject = _createTransformVector(_mtlxTokens->object);
}
nodeInput.first->addInput(nodeInput.second, _mtlxTokens->vector3.GetString());
nodeInput.first->setConnectedNodeName(
nodeInput.second, transformVectorToObject->getName());
}
// Connect Tworld inputs on the material via an output port on the nodegraph:
mx::OutputPtr outTworld = nodeGraph->getOutput(_mtlxTokens->outTworld.GetString());
for (const auto& nodeInput : materialTworldInputs) {
if (!outTworld) {
outTworld = nodeGraph->addOutput(
_mtlxTokens->outTworld.GetString(), _mtlxTokens->vector3.GetString());
outTworld->setConnectedNode(tangentGenerator);
}
nodeInput.first->addInput(nodeInput.second, _mtlxTokens->vector3.GetString());
nodeInput.first->setConnectedOutput(nodeInput.second, outTworld);
}
// Connect Tobject inputs on the material via an output port on the nodegraph:
mx::OutputPtr outTobject = nodeGraph->getOutput(_mtlxTokens->outTobject.GetString());
for (const auto& nodeInput : materialTobjectInputs) {
if (!outTobject) {
outTobject = nodeGraph->addOutput(
_mtlxTokens->outTworld.GetString(), _mtlxTokens->vector3.GetString());
if (!transformVectorToObject) {
transformVectorToObject = _createTransformVector(_mtlxTokens->object);
}
outTobject->setConnectedNode(transformVectorToObject);
}
nodeInput.first->addInput(nodeInput.second, _mtlxTokens->vector3.GetString());
nodeInput.first->setConnectedOutput(nodeInput.second, outTobject);
}
// We will replace tangent nodes with a passthru that feeds on the tangent generator. A
// space transform will be used when appropriate.
auto replaceWithPassthru = [&](mx::NodePtr& toReplace, mx::NodePtr& newSource) {
std::string nodeName = toReplace->getName();
nodeGraph->removeNode(nodeName);
mx::NodePtr passthruNode = nodeGraph->addNode(
_mtlxTokens->constant.GetString(), nodeName, _mtlxTokens->vector3.GetString());
passthruNode->addInput(
_mtlxTokens->value.GetString(), _mtlxTokens->vector3.GetString());
passthruNode->setConnectedNodeName(
_mtlxTokens->value.GetString(), newSource->getName());
};
for (auto& tangentNode : nodesToReplace) {
mx::InputPtr spaceInput = tangentNode->getInput(_mtlxTokens->space.GetString());
if (spaceInput) {
if (spaceInput->getValueString() == _mtlxTokens->object.GetString()) {
if (!transformVectorToObject) {
transformVectorToObject = _createTransformVector(_mtlxTokens->object);
}
replaceWithPassthru(tangentNode, transformVectorToObject);
continue;
} else if (spaceInput->getValueString() == _mtlxTokens->model.GetString()) {
if (!transformVectorToModel) {
transformVectorToModel = _createTransformVector(_mtlxTokens->model);
}
replaceWithPassthru(tangentNode, transformVectorToModel);
continue;
}
}
// Default to world.
replaceWithPassthru(tangentNode, tangentGenerator);
}
}
}
#endif // WANT_MATERIALX_BUILD
#if PXR_VERSION <= 2211
bool _IsUsdDrawModeId(const TfToken& id)
{
return id == _tokens->DrawMode || id == _tokens->UsdDrawModeCards;
}
bool _IsUsdDrawModeNode(const HdMaterialNode& node) { return _IsUsdDrawModeId(node.identifier); }
bool _IsUsdFloat2PrimvarReader(const HdMaterialNode& node)
{
return (node.identifier == UsdImagingTokens->UsdPrimvarReader_float2);
}
#endif
//! Helper utility function to test whether a node is a UsdShade primvar reader.
bool _IsUsdPrimvarReader(const HdMaterialNode& node)
{
const TfToken& id = node.identifier;
return (
id == UsdImagingTokens->UsdPrimvarReader_float
|| id == UsdImagingTokens->UsdPrimvarReader_float2
|| id == UsdImagingTokens->UsdPrimvarReader_float3
|| id == UsdImagingTokens->UsdPrimvarReader_float4 || id == _tokens->UsdPrimvarReader_vector
|| id == UsdImagingTokens->UsdPrimvarReader_int);
}
//! Helper utility function to test whether a node is a UsdShade UV texture.
bool _IsUsdUVTexture(const HdMaterialNode& node)
{
if (node.identifier.GetString().rfind(UsdImagingTokens->UsdUVTexture.GetString(), 0) == 0) {
return true;
}
#ifdef WANT_MATERIALX_BUILD
if (_IsMaterialX(node)) {
mx::NodeDefPtr nodeDef
= _GetMaterialXData()._mtlxLibrary->getNodeDef(node.identifier.GetString());
return nodeDef && _MxHasFilenameInput(nodeDef);
}
#endif
return false;
}
bool _IsTextureFilenameAttribute(const HdMaterialNode& node, const TfToken& token)
{
if (node.identifier.GetString().rfind(UsdImagingTokens->UsdUVTexture.GetString(), 0) == 0
&& token == _tokens->file) {
return true;
}
#ifdef WANT_MATERIALX_BUILD
if (_IsMaterialX(node)) {
mx::NodeDefPtr nodeDef
= _GetMaterialXData()._mtlxLibrary->getNodeDef(node.identifier.GetString());
if (nodeDef) {
const auto input = nodeDef->getActiveInput(token.GetString());
if (input && input->getType() == _mtlxTokens->filename.GetString()) {
return true;
}
}
}
#endif
return false;
}
//! Helper function to generate a XML string about nodes, relationships and primvars in the