forked from autodesk-forks/MaterialX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShaderGraph.cpp
1517 lines (1326 loc) · 54 KB
/
ShaderGraph.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
//
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXGenShader/ShaderGraph.h>
#include <MaterialXGenShader/GenContext.h>
#include <MaterialXGenShader/ShaderNodeImpl.h>
#include <MaterialXGenShader/ShaderGenerator.h>
#include <MaterialXGenShader/TypeDesc.h>
#include <MaterialXGenShader/Util.h>
#include <MaterialXCore/Document.h>
namespace MaterialX
{
//
// ShaderGraph methods
//
ShaderGraph::ShaderGraph(const ShaderGraph* parent, const string& name, ConstDocumentPtr document, const StringSet& reservedWords) :
ShaderNode(parent, name),
_document(document)
{
// Add all reserved words as taken identifiers
for (const string& n : reservedWords)
{
_identifiers[n] = 1;
}
}
void ShaderGraph::addInputSockets(const InterfaceElement& elem, GenContext& context)
{
for (ValueElementPtr port : elem.getActiveValueElements())
{
if (!port->isA<Output>())
{
const string& portValue = port->getResolvedValueString();
std::pair<const TypeDesc*, ValuePtr> enumResult;
if (context.getShaderGenerator().remapEnumeration(*port, portValue, enumResult))
{
ShaderGraphInputSocket* inputSocket = addInputSocket(port->getName(), enumResult.first);
inputSocket->setValue(enumResult.second);
}
else
{
ShaderGraphInputSocket* inputSocket = addInputSocket(port->getName(), TypeDesc::get(port->getType()));
if (!portValue.empty())
{
inputSocket->setValue(port->getValue());
}
}
}
}
}
void ShaderGraph::addOutputSockets(const InterfaceElement& elem)
{
for (const OutputPtr& output : elem.getActiveOutputs())
{
ShaderGraphOutputSocket* outputSocket = addOutputSocket(output->getName(), TypeDesc::get(output->getType()));
outputSocket->setChannels(output->getChannels());
}
if (numOutputSockets() == 0)
{
addOutputSocket("out", TypeDesc::get(elem.getType()));
}
}
void ShaderGraph::addUpstreamDependencies(const Element& root, ConstMaterialPtr material, GenContext& context)
{
// Keep track of our root node in the graph.
// This is needed when the graph is a shader graph and we need
// to make connections for BindInputs during traversal below.
ShaderNode* rootNode = getNode(root.getName());
std::set<ElementPtr> processedOutputs;
for (Edge edge : root.traverseGraph(material))
{
ElementPtr upstreamElement = edge.getUpstreamElement();
if (!upstreamElement)
{
continue;
}
ElementPtr downstreamElement = edge.getDownstreamElement();
// Early out if downstream element is an output that
// we have already processed. This might happen since
// we perform jumps over output elements below.
if (processedOutputs.count(downstreamElement))
{
continue;
}
// If upstream is an output jump to the actual node connected to the output.
if (upstreamElement->isA<Output>())
{
// Record this output so we don't process it again when it
// shows up as a downstream element in the next iteration.
processedOutputs.insert(upstreamElement);
upstreamElement = upstreamElement->asA<Output>()->getConnectedNode();
if (!upstreamElement)
{
continue;
}
}
// Create the node if it doesn't exists
NodePtr upstreamNode = upstreamElement->asA<Node>();
const string& newNodeName = upstreamNode->getName();
ShaderNode* newNode = getNode(newNodeName);
if (!newNode)
{
newNode = createNode(*upstreamNode, context);
}
//
// Make connections
//
// Find the output to connect to.
ElementPtr connectingElement = edge.getConnectingElement();
if (!connectingElement && downstreamElement->isA<Output>())
{
// Edge case for having an output downstream but no connecting
// element (input) reported upstream. In this case we set the
// output itself as connecting element, which handles finding
// the nodedef output in case of a multioutput node upstream.
connectingElement = downstreamElement->asA<Output>();
}
OutputPtr nodeDefOutput = connectingElement ? upstreamNode->getNodeDefOutput(connectingElement) : nullptr;
ShaderOutput* output = nodeDefOutput ? newNode->getOutput(nodeDefOutput->getName()) : newNode->getOutput();
if (!output)
{
throw ExceptionShaderGenError("Could not find an output named '" + (nodeDefOutput ? nodeDefOutput->getName() : string("out")) +
"' on upstream node '" + upstreamNode->getName() + "'");
}
// First check if this was a bind input connection
// In this case we must have a root node as well
if (rootNode && connectingElement && connectingElement->isA<BindInput>())
{
// Connect to the corresponding input on the root node
ShaderInput* input = rootNode->getInput(connectingElement->getName());
if (input)
{
input->breakConnection();
input->makeConnection(output);
}
}
else
{
// Check if it was a node downstream
NodePtr downstreamNode = downstreamElement->asA<Node>();
if (downstreamNode)
{
// We have a node downstream
ShaderNode* downstream = getNode(downstreamNode->getName());
if (downstream && connectingElement)
{
ShaderInput* input = downstream->getInput(connectingElement->getName());
if (!input)
{
throw ExceptionShaderGenError("Could not find an input named '" + connectingElement->getName() +
"' on downstream node '" + downstream->getName() + "'");
}
input->makeConnection(output);
}
}
else
{
// Not a node, then it must be an output
ShaderGraphOutputSocket* outputSocket = getOutputSocket(downstreamElement->getName());
if (outputSocket)
{
outputSocket->makeConnection(output);
}
}
}
}
}
void ShaderGraph::addDefaultGeomNode(ShaderInput* input, const GeomPropDef& geomprop, GenContext& context)
{
const string geomNodeName = "geomprop_" + geomprop.getName();
ShaderNode* node = getNode(geomNodeName);
if (!node)
{
// Find the nodedef for the geometric node referenced by the geomprop. Use the type of the
// input here and ignore the type of the geomprop. They are required to have the same type.
string geomNodeDefName = "ND_" + geomprop.getGeomProp() + "_" + input->getType()->getName();
NodeDefPtr geomNodeDef = _document->getNodeDef(geomNodeDefName);
if (!geomNodeDef)
{
throw ExceptionShaderGenError("Could not find a nodedef named '" + geomNodeDefName +
"' for defaultgeomprop on input '" + input->getFullName() + "'");
}
ShaderNodePtr geomNode = ShaderNode::create(this, geomNodeName, *geomNodeDef, context);
addNode(geomNode);
// Set node inputs if given.
const string& namePath = geomprop.getNamePath();
const string& space = geomprop.getSpace();
if (!space.empty())
{
ShaderInput* spaceInput = geomNode->getInput(GeomPropDef::SPACE_ATTRIBUTE);
ValueElementPtr nodeDefSpaceInput = geomNodeDef->getActiveValueElement(GeomPropDef::SPACE_ATTRIBUTE);
if (spaceInput && nodeDefSpaceInput)
{
std::pair<const TypeDesc*, ValuePtr> enumResult;
if (context.getShaderGenerator().remapEnumeration(*nodeDefSpaceInput, space, enumResult))
{
spaceInput->setValue(enumResult.second);
}
else
{
spaceInput->setValue(Value::createValue<string>(space));
}
spaceInput->setPath(namePath);
}
}
const string& index = geomprop.getIndex();
if (!index.empty())
{
ShaderInput* indexInput = geomNode->getInput("index");
if (indexInput)
{
indexInput->setValue(Value::createValue<string>(index));
indexInput->setPath(namePath);
}
}
const string& geomProp = geomprop.getGeomProp();
if (!geomProp.empty())
{
ShaderInput* geomPropInput = geomNode->getInput("geomprop");
if (geomPropInput)
{
geomPropInput->setValue(Value::createValue<string>(geomProp));
geomPropInput->setPath(namePath);
}
}
node = geomNode.get();
}
input->makeConnection(node->getOutput());
}
void ShaderGraph::addColorTransformNode(ShaderInput* input, const ColorSpaceTransform& transform, GenContext& context)
{
ColorManagementSystemPtr colorManagementSystem = context.getShaderGenerator().getColorManagementSystem();
if (!input->isBindInput() && (!colorManagementSystem || input->getConnection()))
{
// Ignore unbound inputs with connections as they are not
// allowed to have colorspaces specified.
return;
}
const string colorTransformNodeName = input->getFullName() + "_cm";
ShaderNodePtr colorTransformNodePtr = colorManagementSystem->createNode(this, transform, colorTransformNodeName, context);
if (colorTransformNodePtr)
{
addNode(colorTransformNodePtr);
ShaderNode* colorTransformNode = colorTransformNodePtr.get();
ShaderOutput* colorTransformNodeOutput = colorTransformNode->getOutput(0);
ShaderInput* shaderInput = colorTransformNode->getInput(0);
shaderInput->setVariable(input->getFullName());
shaderInput->setValue(input->getValue());
shaderInput->setPath(input->getPath());
shaderInput->setUnit(EMPTY_STRING);
if (input->isBindInput())
{
ShaderOutput* oldConnection = input->getConnection();
shaderInput->makeConnection(oldConnection);
}
input->makeConnection(colorTransformNodeOutput);
}
}
void ShaderGraph::addColorTransformNode(ShaderOutput* output, const ColorSpaceTransform& transform, GenContext& context)
{
ColorManagementSystemPtr colorManagementSystem = context.getShaderGenerator().getColorManagementSystem();
if (!colorManagementSystem)
{
return;
}
const string colorTransformNodeName = output->getFullName() + "_cm";
ShaderNodePtr colorTransformNodePtr = colorManagementSystem->createNode(this, transform, colorTransformNodeName, context);
if (colorTransformNodePtr)
{
addNode(colorTransformNodePtr);
ShaderNode* colorTransformNode = colorTransformNodePtr.get();
ShaderOutput* colorTransformNodeOutput = colorTransformNode->getOutput(0);
ShaderInputSet inputs = output->getConnections();
for (ShaderInput* input : inputs)
{
input->breakConnection();
input->makeConnection(colorTransformNodeOutput);
}
// Connect the node to the upstream output
ShaderInput* colorTransformNodeInput = colorTransformNode->getInput(0);
colorTransformNodeInput->makeConnection(output);
}
}
void ShaderGraph::addUnitTransformNode(ShaderInput* input, const UnitTransform& transform, GenContext& context)
{
UnitSystemPtr unitSystem = context.getShaderGenerator().getUnitSystem();
if (!input->isBindInput() && (!unitSystem || input->getConnection()))
{
return;
}
const string unitTransformNodeName = input->getFullName() + "_unit";
ShaderNodePtr unitTransformNodePtr = unitSystem->createNode(this, transform, unitTransformNodeName, context);
if (unitTransformNodePtr)
{
addNode(unitTransformNodePtr);
ShaderNode* unitTransformNode = unitTransformNodePtr.get();
ShaderOutput* unitTransformNodeOutput = unitTransformNode->getOutput(0);
ShaderInput* shaderInput = unitTransformNode->getInput(0);
shaderInput->setVariable(input->getFullName());
shaderInput->setValue(input->getValue());
shaderInput->setPath(input->getPath());
shaderInput->setUnit(input->getUnit());
if (input->isBindInput())
{
ShaderOutput* oldConnection = input->getConnection();
shaderInput->makeConnection(oldConnection);
}
input->makeConnection(unitTransformNodeOutput);
}
}
void ShaderGraph::addUnitTransformNode(ShaderOutput* output, const UnitTransform& transform, GenContext& context)
{
UnitSystemPtr unitSystem = context.getShaderGenerator().getUnitSystem();
if (!unitSystem)
{
return;
}
const string unitTransformNodeName = output->getFullName() + "_unit";
ShaderNodePtr unitTransformNodePtr = unitSystem->createNode(this, transform, unitTransformNodeName, context);
if (unitTransformNodePtr)
{
addNode(unitTransformNodePtr);
ShaderNode* unitTransformNode = unitTransformNodePtr.get();
ShaderOutput* unitTransformNodeOutput = unitTransformNode->getOutput(0);
ShaderInputSet inputs = output->getConnections();
for (ShaderInput* input : inputs)
{
string inname = input->getFullName();
input->breakConnection();
input->makeConnection(unitTransformNodeOutput);
}
// Connect the node to the upstream output
ShaderInput* unitTransformNodeInput = unitTransformNode->getInput(0);
unitTransformNodeInput->makeConnection(output);
}
}
ShaderGraphPtr ShaderGraph::create(const ShaderGraph* parent, const NodeGraph& nodeGraph, GenContext& context)
{
NodeDefPtr nodeDef = nodeGraph.getNodeDef();
if (!nodeDef)
{
throw ExceptionShaderGenError("Can't find nodedef '" + nodeGraph.getNodeDefString() + "' referenced by nodegraph '" + nodeGraph.getName() + "'");
}
string graphName = nodeGraph.getName();
context.getShaderGenerator().getSyntax().makeValidName(graphName);
ShaderGraphPtr graph = std::make_shared<ShaderGraph>(parent, graphName, nodeGraph.getDocument(), context.getReservedWords());
// Clear classification
graph->_classification = 0;
// Create input sockets from the nodedef
graph->addInputSockets(*nodeDef, context);
// Create output sockets from the nodegraph
graph->addOutputSockets(nodeGraph);
// Traverse all outputs and create all upstream dependencies
for (OutputPtr graphOutput : nodeGraph.getActiveOutputs())
{
graph->addUpstreamDependencies(*graphOutput, nullptr, context);
}
// Add classification according to last node
// TODO: What if the graph has multiple outputs?
{
ShaderGraphOutputSocket* outputSocket = graph->getOutputSocket();
graph->_classification |= outputSocket->getConnection() ? outputSocket->getConnection()->getNode()->_classification : 0;
}
// Finalize the graph
graph->finalize(context);
return graph;
}
ShaderGraphPtr ShaderGraph::create(const ShaderGraph* parent, const string& name, ElementPtr element, GenContext& context)
{
ShaderGraphPtr graph;
ElementPtr root;
MaterialPtr material;
if (element->isA<Output>())
{
OutputPtr output = element->asA<Output>();
ElementPtr outputParent = output->getParent();
InterfaceElementPtr interface;
if (outputParent->isA<NodeGraph>())
{
// A nodegraph output.
NodeGraphPtr nodeGraph = outputParent->asA<NodeGraph>();
NodeDefPtr nodeDef = nodeGraph->getNodeDef();
if (nodeDef)
{
interface = nodeDef;
}
else
{
interface = nodeGraph;
}
}
else if (outputParent->isA<Document>())
{
// A free floating output.
outputParent = output->getConnectedNode();
interface = outputParent->asA<InterfaceElement>();
}
if (!interface)
{
throw ExceptionShaderGenError("Given output '" + output->getName() + "' has no interface valid for shader generation");
}
graph = std::make_shared<ShaderGraph>(parent, name, element->getDocument(), context.getReservedWords());
// Clear classification
graph->_classification = 0;
// Create input sockets
graph->addInputSockets(*interface, context);
// Create the given output socket
ShaderGraphOutputSocket* outputSocket = graph->addOutputSocket(output->getName(), TypeDesc::get(output->getType()));
outputSocket->setPath(output->getNamePath());
outputSocket->setChannels(output->getChannels());
const string& outputUnit = output->getUnit();
if (!outputUnit.empty())
{
outputSocket->setUnit(outputUnit);
}
// Start traversal from this output
root = output;
}
else if (element->isA<Node>())
{
NodePtr node = element->asA<Node>();
NodeDefPtr nodeDef = node->getNodeDef();
if (!nodeDef)
{
throw ExceptionShaderGenError("Could not find a nodedef for node '" + node->getName() + "'");
}
graph = std::make_shared<ShaderGraph>(parent, name, element->getDocument(), context.getReservedWords());
// Create input sockets
graph->addInputSockets(*nodeDef, context);
// Create output sockets
graph->addOutputSockets(*nodeDef);
// Create this shader node in the graph.
ShaderNodePtr newNode = ShaderNode::create(graph.get(), node->getName(), *nodeDef, context);
graph->addNode(newNode);
// Connect it to the graph outputs
for (size_t i = 0; i < newNode->numOutputs(); ++i)
{
ShaderGraphOutputSocket* outputSocket = graph->getOutputSocket(i);
outputSocket->makeConnection(newNode->getOutput(i));
outputSocket->setPath(node->getNamePath());
}
// Handle node input ports
for (const ValueElementPtr& nodedefPort : nodeDef->getActiveValueElements())
{
if (nodedefPort->isA<Output>())
continue;
ShaderGraphInputSocket* inputSocket = graph->getInputSocket(nodedefPort->getName());
ShaderInput* input = newNode->getInput(nodedefPort->getName());
if (!inputSocket || !input)
{
throw ExceptionShaderGenError("Node port '" + nodedefPort->getName() + "' doesn't match an existing input on graph '" + graph->getName() + "'");
}
ValueElementPtr nodePort = node->getValueElement(nodedefPort->getName());
if (nodePort)
{
ValuePtr value = nodePort->getResolvedValue();
if (value)
{
inputSocket->setValue(value);
}
inputSocket->setPath(nodePort->getNamePath());
input->setPath(inputSocket->getPath());
const string& unit = nodePort->getUnit();
if (!unit.empty())
{
inputSocket->setUnit(unit);
input->setUnit(unit);
}
}
if (nodedefPort->isA<Input>())
{
GeomPropDefPtr geomprop = nodedefPort->asA<Input>()->getDefaultGeomProp();
if (geomprop)
{
inputSocket->setGeomProp(geomprop->getName());
input->setGeomProp(geomprop->getName());
}
}
// Connect to the graph input
inputSocket->makeConnection(input);
}
// No traversal of upstream dependencies
root = nullptr;
}
else if (element->isA<ShaderRef>())
{
ShaderRefPtr shaderRef = element->asA<ShaderRef>();
NodeDefPtr nodeDef = shaderRef->getNodeDef();
if (!nodeDef)
{
throw ExceptionShaderGenError("Could not find a nodedef for shader '" + shaderRef->getName() + "'");
}
graph = std::make_shared<ShaderGraph>(parent, name, element->getDocument(), context.getReservedWords());
// Create input sockets
graph->addInputSockets(*nodeDef, context);
// Create output sockets
graph->addOutputSockets(*nodeDef);
// Create this shader node in the graph.
const string& newNodeName = shaderRef->getName();
ShaderNodePtr newNode = ShaderNode::create(graph.get(), newNodeName, *nodeDef, context);
graph->addNode(newNode);
// Connect it to the graph output
ShaderGraphOutputSocket* outputSocket = graph->getOutputSocket();
outputSocket->makeConnection(newNode->getOutput());
outputSocket->setPath(shaderRef->getNamePath());
string targetColorSpace;
ColorManagementSystemPtr colorManagementSystem = context.getShaderGenerator().getColorManagementSystem();
if (colorManagementSystem)
{
targetColorSpace = context.getOptions().targetColorSpaceOverride.empty() ?
element->getDocument()->getColorSpace() : context.getOptions().targetColorSpaceOverride;
}
// Handle node parameters
const string& targetDistanceUnit = context.getOptions().targetDistanceUnit;
UnitSystemPtr unitSystem = context.getShaderGenerator().getUnitSystem();
for (ParameterPtr elem : nodeDef->getActiveParameters())
{
ShaderGraphInputSocket* inputSocket = graph->getInputSocket(elem->getName());
ShaderInput* input = newNode->getInput(elem->getName());
if (!inputSocket || !input)
{
throw ExceptionShaderGenError("Shader parameter '" + elem->getName() + "' doesn't match an existing input on graph '" + graph->getName() + "'");
}
BindParamPtr bindParam = shaderRef->getBindParam(elem->getName());
if (bindParam)
{
// Copy value from binding
ValuePtr bindParamValue = bindParam->getResolvedValue();
if (bindParamValue)
{
inputSocket->setValue(bindParamValue);
input->setBindInput();
graph->populateColorTransformMap(colorManagementSystem, input, bindParam, targetColorSpace, true);
graph->populateUnitTransformMap(unitSystem, input, bindParam, targetDistanceUnit, true);
}
inputSocket->setPath(bindParam->getNamePath());
input->setPath(inputSocket->getPath());
const string& bindParamUnit = bindParam->getUnit();
if (!bindParamUnit.empty())
{
inputSocket->setUnit(bindParamUnit);
input->setUnit(bindParamUnit);
}
}
// Connect to the graph input
inputSocket->makeConnection(input);
}
// Handle node inputs
for (const InputPtr& nodeDefInput : nodeDef->getActiveInputs())
{
ShaderGraphInputSocket* inputSocket = graph->getInputSocket(nodeDefInput->getName());
ShaderInput* input = newNode->getInput(nodeDefInput->getName());
if (!inputSocket || !input)
{
throw ExceptionShaderGenError("Shader input '" + nodeDefInput->getName() + "' doesn't match an existing input on graph '" + graph->getName() + "'");
}
BindInputPtr bindInput = shaderRef->getBindInput(nodeDefInput->getName());
if (bindInput)
{
// Copy value from binding
ValuePtr bindInputValue = bindInput->getResolvedValue();
if (bindInputValue)
{
inputSocket->setValue(bindInputValue);
input->setBindInput();
graph->populateColorTransformMap(colorManagementSystem, input, bindInput, targetColorSpace, true);
graph->populateUnitTransformMap(unitSystem, input, bindInput, targetDistanceUnit, true);
}
inputSocket->setPath(bindInput->getNamePath());
input->setPath(inputSocket->getPath());
const string& bindInputUnit = bindInput->getUnit();
if (!bindInputUnit.empty())
{
inputSocket->setUnit(bindInputUnit);
input->setUnit(bindInputUnit);
}
}
GeomPropDefPtr geomprop = nodeDefInput->getDefaultGeomProp();
if (geomprop)
{
inputSocket->setGeomProp(geomprop->getName());
input->setGeomProp(geomprop->getName());
}
// If no explicit connection, connect to geometric node if a geomprop is used
// or otherwise to the graph interface.
const string& connection = bindInput ? bindInput->getOutputString() : EMPTY_STRING;
if (connection.empty())
{
if (geomprop)
{
graph->addDefaultGeomNode(input, *geomprop, context);
}
else
{
inputSocket->makeConnection(input);
}
}
}
// Add shaderRef nodedef paths
const string& nodePath = shaderRef->getNamePath();
for (const ValueElementPtr& nodeInput : nodeDef->getActiveInputs())
{
const string& inputName = nodeInput->getName();
const string path = nodePath + NAME_PATH_SEPARATOR + inputName;
const string& unit = nodeInput->getUnit();
ShaderInput* input = newNode->getInput(inputName);
if (input && input->getPath().empty())
{
input->setPath(path);
}
if (input && input->getUnit().empty() && !unit.empty())
{
input->setUnit(unit);
}
ShaderGraphInputSocket* inputSocket = graph->getInputSocket(inputName);
if (inputSocket && inputSocket->getPath().empty())
{
inputSocket->setPath(path);
}
if (inputSocket && inputSocket->getUnit().empty() && !unit.empty())
{
inputSocket->setUnit(unit);
}
}
for (const ParameterPtr& nodeParameter : nodeDef->getActiveParameters())
{
const string& paramName = nodeParameter->getName();
const string path = nodePath + NAME_PATH_SEPARATOR + paramName;
ShaderInput* input = newNode->getInput(paramName);
if (input && input->getPath().empty())
{
input->setPath(path);
}
ShaderGraphInputSocket* inputSocket = graph->getInputSocket(paramName);
if (inputSocket && inputSocket->getPath().empty())
{
inputSocket->setPath(path);
}
}
// Start traversal from this shaderref and material
root = shaderRef;
material = shaderRef->getParent()->asA<Material>();
}
if (!graph)
{
throw ExceptionShaderGenError("Shader generation from element '" + element->getName() + "' of type '" + element->getCategory() + "' is not supported");
}
// Traverse and create all dependencies upstream
if (root)
{
graph->addUpstreamDependencies(*root, material, context);
}
// Add classification according to root node
ShaderGraphOutputSocket* outputSocket = graph->getOutputSocket();
graph->_classification |= outputSocket->getConnection() ? outputSocket->getConnection()->getNode()->_classification : 0;
graph->finalize(context);
return graph;
}
ShaderNode* ShaderGraph::createNode(const Node& node, GenContext& context)
{
NodeDefPtr nodeDef = node.getNodeDef();
if (!nodeDef)
{
throw ExceptionShaderGenError("Could not find a nodedef for node '" + node.getName() + "'");
}
// Create this node in the graph.
const string& name = node.getName();
ShaderNodePtr newNode = ShaderNode::create(this, name, *nodeDef, context);
newNode->setValues(node, *nodeDef, context);
newNode->setPaths(node, *nodeDef);
_nodeMap[name] = newNode;
_nodeOrder.push_back(newNode.get());
// Check if the node is a convolution node and mark the graph as such.
if (newNode->hasClassification(Classification::CONVOLUTION2D))
{
_classification |= Classification::CONVOLUTION2D;
}
// Check if any of the node inputs should be connected to the graph interface
for (ValueElementPtr elem : node.getChildrenOfType<ValueElement>())
{
const string& interfaceName = elem->getInterfaceName();
if (!interfaceName.empty())
{
ShaderGraphInputSocket* inputSocket = getInputSocket(interfaceName);
if (!inputSocket)
{
throw ExceptionShaderGenError("Interface name '" + interfaceName + "' doesn't match an existing input on nodegraph '" + getName() + "'");
}
ShaderInput* input = newNode->getInput(elem->getName());
if (input)
{
input->makeConnection(inputSocket);
}
}
}
// Handle the "defaultgeomprop" directives on the nodedef inputs.
// Create and connect default geometric nodes on unconnected inputs.
for (const InputPtr& nodeDefInput : nodeDef->getActiveInputs())
{
ShaderInput* input = newNode->getInput(nodeDefInput->getName());
InputPtr nodeInput = node.getInput(nodeDefInput->getName());
const string& connection = nodeInput ? nodeInput->getNodeName() : EMPTY_STRING;
if (connection.empty() && !input->getConnection())
{
GeomPropDefPtr geomprop = nodeDefInput->getDefaultGeomProp();
if (geomprop)
{
addDefaultGeomNode(input, *geomprop, context);
}
}
}
string targetColorSpace;
ColorManagementSystemPtr colorManagementSystem = context.getShaderGenerator().getColorManagementSystem();
if (colorManagementSystem)
{
targetColorSpace = context.getOptions().targetColorSpaceOverride.empty() ?
_document->getActiveColorSpace() : context.getOptions().targetColorSpaceOverride;
}
if (colorManagementSystem && !targetColorSpace.empty())
{
for (InputPtr input : node.getInputs())
{
ShaderInput* shaderInput = newNode->getInput(input->getName());
populateColorTransformMap(colorManagementSystem, shaderInput, input, targetColorSpace, true);
}
for (ParameterPtr parameter : node.getParameters())
{
if (parameter->getType() == FILENAME_TYPE_STRING)
{
ShaderOutput* shaderOutput = newNode->getOutput();
if (shaderOutput)
{
populateColorTransformMap(colorManagementSystem, shaderOutput, parameter, targetColorSpace, false);
}
}
else
{
ShaderInput* shaderInput = newNode->getInput(parameter->getName());
populateColorTransformMap(colorManagementSystem, shaderInput, parameter, targetColorSpace, true);
}
}
}
// Unit Conversion: Only applicable if Unit system and a "targetDistanceUnit" is defined for now.
UnitSystemPtr unitSystem = context.getShaderGenerator().getUnitSystem();
const string& targetDistanceUnit = context.getOptions().targetDistanceUnit;
if (unitSystem && !targetDistanceUnit.empty())
{
for (InputPtr input : node.getInputs())
{
ShaderInput* inputPort = newNode->getInput(input->getName());
populateUnitTransformMap(unitSystem, inputPort, input, targetDistanceUnit, true);
}
for (ParameterPtr parameter : node.getParameters())
{
ShaderInput* inputPort = newNode->getInput(parameter->getName());
if (parameter->getType() == FILENAME_TYPE_STRING)
{
// Check output port for any parameters which are file names
ShaderOutput* shaderOutput = newNode->getOutput();
if (shaderOutput)
{
populateUnitTransformMap(unitSystem, shaderOutput, parameter, targetDistanceUnit, false);
}
}
populateUnitTransformMap(unitSystem, inputPort, parameter, targetDistanceUnit, true);
}
}
return newNode.get();
}
ShaderGraphInputSocket* ShaderGraph::addInputSocket(const string& name, const TypeDesc* type)
{
return ShaderNode::addOutput(name, type);
}
ShaderGraphOutputSocket* ShaderGraph::addOutputSocket(const string& name, const TypeDesc* type)
{
return ShaderNode::addInput(name, type);
}
ShaderGraphEdgeIterator ShaderGraph::traverseUpstream(ShaderOutput* output)
{
return ShaderGraphEdgeIterator(output);
}
void ShaderGraph::addNode(ShaderNodePtr node)
{
_nodeMap[node->getName()] = node;
_nodeOrder.push_back(node.get());
}
ShaderNode* ShaderGraph::getNode(const string& name)
{
auto it = _nodeMap.find(name);
return it != _nodeMap.end() ? it->second.get() : nullptr;
}
const ShaderNode* ShaderGraph::getNode(const string& name) const
{
return const_cast<ShaderGraph*>(this)->getNode(name);
}
void ShaderGraph::finalize(GenContext& context)
{
// Insert color transformation nodes where needed
for (const auto& it : _inputColorTransformMap)
{
addColorTransformNode(it.first, it.second, context);
}
for (const auto& it : _outputColorTransformMap)
{
addColorTransformNode(it.first, it.second, context);
}
_inputColorTransformMap.clear();
_outputColorTransformMap.clear();
// Insert unit transformation nodes where needed
for (const auto& it : _inputUnitTransformMap)
{
addUnitTransformNode(it.first, it.second, context);
}
for (const auto& it : _outputUnitTransformMap)
{
addUnitTransformNode(it.first, it.second, context);
}
_inputUnitTransformMap.clear();
_outputUnitTransformMap.clear();
// Optimize the graph, removing redundant paths.
optimize(context);
if (context.getOptions().shaderInterfaceType == SHADER_INTERFACE_COMPLETE)
{
// Publish all node inputs that has not been connected already.
for (const ShaderNode* node : getNodes())
{
for (ShaderInput* input : node->getInputs())
{
if (!input->getConnection())
{
// Check if the type is editable otherwise we can't
// publish the input as an editable uniform.
if (input->getType()->isEditable() && node->isEditable(*input))
{
// Use a consistent naming convention: <nodename>_<inputname>
// so application side can figure out what uniforms to set
// when node inputs change on application side.
const string interfaceName = node->getName() + "_" + input->getName();
ShaderGraphInputSocket* inputSocket = getInputSocket(interfaceName);
if (!inputSocket)
{
inputSocket = addInputSocket(interfaceName, input->getType());
inputSocket->setPath(input->getPath());
inputSocket->setValue(input->getValue());
inputSocket->setUnit(input->getUnit());
}
inputSocket->makeConnection(input);
}
}
}
}
}
// Sort the nodes in topological order.
topologicalSort();
// Calculate scopes for all nodes in the graph.
calculateScopes();
// Set variable names for inputs and outputs in the graph.
setVariableNames(context);
// Track closure nodes used by each surface shader.
//
// TODO: Optimize this search for closures.
// No need to do a full traversal when
// texture nodes are reached.
for (ShaderNode* node : _nodeOrder)
{
if (node->hasClassification(ShaderNode::Classification::SHADER))
{
for (ShaderGraphEdge edge : ShaderGraph::traverseUpstream(node->getOutput()))
{
if (edge.upstream)
{
if (edge.upstream->getNode()->hasClassification(ShaderNode::Classification::CLOSURE))
{