forked from AcademySoftwareFoundation/MaterialX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.cpp
More file actions
4202 lines (3944 loc) · 155 KB
/
Graph.cpp
File metadata and controls
4202 lines (3944 loc) · 155 KB
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 Contributors to the MaterialX Project
// SPDX-License-Identifier: Apache-2.0
//
#include <MaterialXGraphEditor/Graph.h>
#include <MaterialXRenderGlsl/External/Glad/glad.h>
#include <MaterialXFormat/Util.h>
#include <imgui_stdlib.h>
#include <imgui_node_editor_internal.h>
#include <widgets.h>
#include <iostream>
namespace
{
// the default node size is based off the of the size of the dot_color3 node using ed::getNodeSize() on that node
const ImVec2 DEFAULT_NODE_SIZE = ImVec2(138, 116);
const int DEFAULT_ALPHA = 255;
const int FILTER_ALPHA = 50;
// Function based off ImRect_Expanded function from ImGui Node Editor blueprints-example.cpp
ImRect expandImRect(const ImRect& rect, float x, float y)
{
ImRect result = rect;
result.Min.x -= x;
result.Min.y -= y;
result.Max.x += x;
result.Max.y += y;
return result;
}
// Get more user friendly node definition identifier.
// Will try and remove "ND_" prefix if it exists. Otherwise just returns
// the nodedef identifier.
std::string getNodeDefId(const std::string& val)
{
const std::string ND_PREFIX = "ND_";
std::string result = val;
if (mx::stringStartsWith(val, ND_PREFIX))
{
result = val.substr(3, val.length());
}
return result;
}
} // anonymous namespace
Graph::Graph(const std::string& materialFilename,
const std::string& meshFilename,
const mx::FileSearchPath& searchPath,
const mx::FilePathVec& libraryFolders,
int viewWidth,
int viewHeight) :
_materialFilename(materialFilename),
_searchPath(searchPath),
_libraryFolders(libraryFolders),
_initial(false),
_delete(false),
_fileDialogSave(FileDialog::EnterNewFilename),
_isNodeGraph(false),
_graphTotalSize(0),
_popup(false),
_shaderPopup(false),
_searchNodeId(-1),
_addNewNode(false),
_ctrlClick(false),
_isCut(false),
_autoLayout(false),
_frameCount(INT_MIN),
_pinFilterType(mx::EMPTY_STRING)
{
loadStandardLibraries();
setPinColor();
// Set up filters load and save
_mtlxFilter.push_back(".mtlx");
_geomFilter.push_back(".obj");
_geomFilter.push_back(".glb");
_geomFilter.push_back(".gltf");
_graphDoc = loadDocument(materialFilename);
_graphDoc->importLibrary(_stdLib);
_initial = true;
createNodeUIList(_stdLib);
if (_graphDoc)
{
buildUiBaseGraph(_graphDoc);
_currGraphElem = _graphDoc;
_prevUiNode = nullptr;
}
// Create a renderer using the initial startup document.
mx::FilePath captureFilename = "resources/Materials/Examples/example.png";
std::string envRadianceFilename = "resources/Lights/san_giuseppe_bridge_split.hdr";
_renderer = std::make_shared<RenderView>(_graphDoc, meshFilename, envRadianceFilename,
_searchPath, viewWidth, viewHeight);
_renderer->initialize();
for (const std::string& ext : _renderer->getImageHandler()->supportedExtensions())
{
_imageFilter.push_back("." + ext);
}
_renderer->updateMaterials(nullptr);
for (const std::string& incl : _renderer->getXincludeFiles())
{
_xincludeFiles.insert(incl);
}
}
mx::ElementPredicate Graph::getElementPredicate() const
{
return [this](mx::ConstElementPtr elem)
{
if (elem->hasSourceUri())
{
return (_xincludeFiles.count(elem->getSourceUri()) == 0);
}
return true;
};
}
void Graph::loadStandardLibraries()
{
// Initialize the standard library.
try
{
_stdLib = mx::createDocument();
_xincludeFiles = mx::loadLibraries(_libraryFolders, _searchPath, _stdLib);
if (_xincludeFiles.empty())
{
std::cerr << "Could not find standard data libraries on the given search path: " << _searchPath.asString() << std::endl;
}
}
catch (std::exception& e)
{
std::cerr << "Failed to load standard data libraries: " << e.what() << std::endl;
return;
}
}
mx::DocumentPtr Graph::loadDocument(mx::FilePath filename)
{
mx::FilePathVec libraryFolders = { "libraries" };
_libraryFolders = libraryFolders;
mx::XmlReadOptions readOptions;
readOptions.readXIncludeFunction = [](mx::DocumentPtr doc, const mx::FilePath& filename,
const mx::FileSearchPath& searchPath, const mx::XmlReadOptions* options)
{
mx::FilePath resolvedFilename = searchPath.find(filename);
if (resolvedFilename.exists())
{
try
{
readFromXmlFile(doc, resolvedFilename, searchPath, options);
}
catch (mx::Exception& e)
{
std::cerr << "Failed to read include file: " << filename.asString() << ". " <<
std::string(e.what()) << std::endl;
}
}
else
{
std::cerr << "Include file not found: " << filename.asString() << std::endl;
}
};
mx::DocumentPtr doc = mx::createDocument();
try
{
if (!filename.isEmpty())
{
mx::readFromXmlFile(doc, filename, _searchPath, &readOptions);
std::string message;
if (!doc->validate(&message))
{
std::cerr << "*** Validation warnings for " << filename.asString() << " ***" << std::endl;
std::cerr << message << std::endl;
}
}
}
catch (mx::Exception& e)
{
std::cerr << "Failed to read file: " << filename.asString() << ": \"" <<
std::string(e.what()) << "\"" << std::endl;
}
_graphStack = std::stack<std::vector<UiNodePtr>>();
_pinStack = std::stack<std::vector<UiPinPtr>>();
return doc;
}
// populate nodes to add with input output group and nodegraph nodes which are not found in the stdlib
void Graph::addExtraNodes()
{
if (!_graphDoc)
{
return;
}
// clear any old nodes, if we previously used tab with another graph doc
_extraNodes.clear();
// get all types from the doc
std::vector<std::string> types;
std::vector<mx::TypeDefPtr> typeDefs = _graphDoc->getTypeDefs();
types.reserve(typeDefs.size());
for (auto typeDef : typeDefs)
{
types.push_back(typeDef->getName());
}
// add input and output nodes for all types
for (const std::string& type : types)
{
std::string nodeName = "ND_input_" + type;
_extraNodes["Input Nodes"].push_back({ nodeName, type, "input" });
nodeName = "ND_output_" + type;
_extraNodes["Output Nodes"].push_back({ nodeName, type, "output" });
}
// add group node
std::vector<std::string> groupNode{ "ND_group", "", "group" };
_extraNodes["Group Nodes"].push_back(groupNode);
// add nodegraph node
std::vector<std::string> nodeGraph{ "ND_nodegraph", "", "nodegraph" };
_extraNodes["Node Graph"].push_back(nodeGraph);
}
// return output pin needed to link the inputs and outputs
ed::PinId Graph::getOutputPin(UiNodePtr node, UiNodePtr upNode, UiPinPtr input)
{
if (upNode->getNodeGraph() != nullptr)
{
// For nodegraph need to get the correct ouput pin accorinding to the names of the output nodes
mx::OutputPtr output = input->_pinNode->getNode() ? input->_pinNode->getNode()->getConnectedOutput(input->_name) : nullptr;
if (output)
{
std::string outName = output->getName();
for (UiPinPtr outputs : upNode->outputPins)
{
if (outputs->_name == outName)
{
return outputs->_pinId;
}
}
}
return ed::PinId();
}
else
{
// For node need to get the correct ouput pin based on the output attribute
if (!upNode->outputPins.empty())
{
std::string outputName = mx::EMPTY_STRING;
if (input->_input)
{
outputName = input->_input->getOutputString();
}
else if (input->_output)
{
outputName = input->_output->getOutputString();
}
size_t pinIndex = 0;
if (!outputName.empty())
{
for (size_t i = 0; i < upNode->outputPins.size(); i++)
{
if (upNode->outputPins[i]->_name == outputName)
{
pinIndex = i;
break;
}
}
}
return (upNode->outputPins[pinIndex]->_pinId);
}
return ed::PinId();
}
}
// connect links via connected nodes in UiNodePtr
void Graph::linkGraph()
{
_currLinks.clear();
// start with bottom of graph
for (UiNodePtr node : _graphNodes)
{
std::vector<UiPinPtr> inputs = node->inputPins;
if (node->getInput() == nullptr)
{
for (size_t i = 0; i < inputs.size(); i++)
{
// get upstream node for all inputs
std::string inputName = inputs[i]->_name;
UiNodePtr inputNode = node->getConnectedNode(inputName);
if (inputNode != nullptr)
{
Link link;
// getting the input connections for the current uiNode
ax::NodeEditor::PinId id = inputs[i]->_pinId;
inputs[i]->setConnected(true);
int end = int(id.Get());
link._endAttr = end;
// get id number of output of node
ed::PinId outputId = getOutputPin(node, inputNode, inputs[i]);
int start = int(outputId.Get());
if (start >= 0)
{
// Connect the correct output pin to this input
for (UiPinPtr outPin : inputNode->outputPins)
{
if (outPin->_pinId == outputId)
{
outPin->setConnected(true);
outPin->addConnection(inputs[i]);
}
}
link._startAttr = start;
if (!linkExists(link))
{
_currLinks.push_back(link);
}
}
}
else if (inputs[i]->_input)
{
if (inputs[i]->_input->getInterfaceInput())
{
inputs[i]->setConnected(true);
}
}
else
{
inputs[i]->setConnected(false);
}
}
}
}
}
// connect all the links via the graph editor library
void Graph::connectLinks()
{
for (Link const& link : _currLinks)
{
ed::Link(link.id, link._startAttr, link._endAttr);
}
}
// find link position in currLinks vector from link id
int Graph::findLinkPosition(int id)
{
int count = 0;
for (size_t i = 0; i < _currLinks.size(); i++)
{
if (_currLinks[i].id == id)
{
return count;
}
count++;
}
return -1;
}
// check if a node has already been assigned a position
bool Graph::checkPosition(UiNodePtr node)
{
if (node->getMxElement() != nullptr)
{
if (node->getMxElement()->getAttribute("xpos") != "")
{
return true;
}
}
return false;
}
// calculate the total vertical space the node level takes up
float Graph::totalHeight(int level)
{
float total = 0.f;
for (UiNodePtr node : _levelMap[level])
{
total += ed::GetNodeSize(node->getId()).y;
}
return total;
}
// set the y position of node based of the starting position and the nodes above it
void Graph::setYSpacing(int level, float startingPos)
{
// set the y spacing for each node
float currPos = startingPos;
for (UiNodePtr node : _levelMap[level])
{
ImVec2 oldPos = ed::GetNodePosition(node->getId());
ed::SetNodePosition(node->getId(), ImVec2(oldPos.x, currPos));
currPos += ed::GetNodeSize(node->getId()).y + 40;
}
}
// calculate the average y position for a specific node level
float Graph::findAvgY(const std::vector<UiNodePtr>& nodes)
{
// find the mid point of node level grou[
float total = 0.f;
int count = 0;
for (UiNodePtr node : nodes)
{
ImVec2 pos = ed::GetNodePosition(node->getId());
ImVec2 size = ed::GetNodeSize(node->getId());
total += ((size.y + pos.y) + pos.y) / 2;
count++;
}
return (total / count);
}
void Graph::findYSpacing(float startY)
{
// assume level 0 is set
// for each level find the average y position of the previous level to use as a spacing guide
int i = 0;
for (std::pair<int, std::vector<UiNodePtr>> levelChunk : _levelMap)
{
if (_levelMap[i].size() > 0)
{
if (_levelMap[i][0]->_level > 0)
{
int prevLevel = _levelMap[i].front()->_level - 1;
float avgY = findAvgY(_levelMap[prevLevel]);
float height = totalHeight(_levelMap[i].front()->_level);
// caculate the starting position to be above the previous level's center so that it is evenly spaced on either side of the center
float startingPos = avgY - ((height + (_levelMap[i].size() * 20)) / 2) + startY;
setYSpacing(_levelMap[i].front()->_level, startingPos);
}
else
{
setYSpacing(_levelMap[i].front()->_level, startY);
}
}
++i;
}
}
// layout the x position by assigning the node levels based off its distance from the first node
ImVec2 Graph::layoutPosition(UiNodePtr layoutNode, ImVec2 startingPos, bool initialLayout, int level)
{
if (checkPosition(layoutNode) && !_autoLayout)
{
for (UiNodePtr node : _graphNodes)
{
// since nodegrpah nodes do not have any materialX info they are placed based off their conneced node
if (node->getNodeGraph() != nullptr)
{
std::vector<UiNodePtr> outputCon = node->getOutputConnections();
if (outputCon.size() > 0)
{
ImVec2 outputPos = ed::GetNodePosition(outputCon[0]->getId());
ed::SetNodePosition(node->getId(), ImVec2(outputPos.x - 400, outputPos.y));
node->setPos(ImVec2(outputPos.x - 400, outputPos.y));
}
}
else
{
// don't set position of group nodes
if (node->getMessage().empty())
{
if (node->getMxElement()->hasAttribute("xpos"))
{
float x = std::stof(node->getMxElement()->getAttribute("xpos"));
if (node->getMxElement()->hasAttribute("ypos"))
{
float y = std::stof(node->getMxElement()->getAttribute("ypos"));
x *= DEFAULT_NODE_SIZE.x;
y *= DEFAULT_NODE_SIZE.y;
ed::SetNodePosition(node->getId(), ImVec2(x, y));
node->setPos(ImVec2(x, y));
}
}
}
}
}
return ImVec2(0.f, 0.f);
}
else
{
ImVec2 currPos = startingPos;
ImVec2 newPos = currPos;
if (layoutNode->_level != -1)
{
if (layoutNode->_level < level)
{
// remove the old instance of the node from the map
int levelNum = 0;
int removeNum = -1;
for (UiNodePtr levelNode : _levelMap[layoutNode->_level])
{
if (levelNode->getName() == layoutNode->getName())
{
removeNum = levelNum;
}
levelNum++;
}
if (removeNum > -1)
{
_levelMap[layoutNode->_level].erase(_levelMap[layoutNode->_level].begin() + removeNum);
}
layoutNode->_level = level;
}
}
else
{
layoutNode->_level = level;
}
auto it = _levelMap.find(layoutNode->_level);
if (it != _levelMap.end())
{
// key already exists add to it
bool nodeFound = false;
for (UiNodePtr node : it->second)
{
if (node && node->getName() == layoutNode->getName())
{
nodeFound = true;
break;
}
}
if (!nodeFound)
{
_levelMap[layoutNode->_level].push_back(layoutNode);
}
}
else
{
// insert new vector into key
std::vector<UiNodePtr> newValue = { layoutNode };
_levelMap.insert({ layoutNode->_level, newValue });
}
std::vector<UiPinPtr> pins = layoutNode->inputPins;
if (initialLayout)
{
// check number of inputs that are connected to node
if (layoutNode->getInputConnect() > 0)
{
// not top of node graph stop recursion
if (pins.size() != 0 && layoutNode->getInput() == nullptr)
{
for (size_t i = 0; i < pins.size(); i++)
{
// get upstream node for all inputs
newPos = startingPos;
UiNodePtr nextNode = layoutNode->getConnectedNode(pins[i]->_name);
if (nextNode)
{
startingPos.x = (1200.f - ((layoutNode->_level) * 350)) * _fontScale;
ed::SetNodePosition(layoutNode->getId(), startingPos);
layoutNode->setPos(ImVec2(startingPos));
// call layout position on upstream node with newPos as -140 to the left of current node
layoutPosition(nextNode, ImVec2(newPos.x, startingPos.y), initialLayout, layoutNode->_level + 1);
}
}
}
}
else
{
startingPos.x = (1200.f - ((layoutNode->_level) * 350)) * _fontScale;
layoutNode->setPos(ImVec2(startingPos));
// set current node position
ed::SetNodePosition(layoutNode->getId(), ImVec2(startingPos));
}
}
return ImVec2(0.f, 0.f);
}
}
// extra layout pass for inputs and nodes that do not attach to an output node
void Graph::layoutInputs()
{
// layout inputs after other nodes so that they can be all in a line on far left side of node graph
if (_levelMap.begin() != _levelMap.end())
{
int levelCount = -1;
for (std::pair<int, std::vector<UiNodePtr>> nodes : _levelMap)
{
++levelCount;
}
ImVec2 startingPos = ed::GetNodePosition(_levelMap[levelCount].back()->getId());
startingPos.y += ed::GetNodeSize(_levelMap[levelCount].back()->getId()).y + 20;
for (UiNodePtr uiNode : _graphNodes)
{
if (uiNode->getOutputConnections().size() == 0 && (uiNode->getInput() != nullptr))
{
ed::SetNodePosition(uiNode->getId(), ImVec2(startingPos));
startingPos.y += ed::GetNodeSize(uiNode->getId()).y;
startingPos.y += 23;
}
// accoutning for extra nodes like in gltf
else if (uiNode->getOutputConnections().size() == 0 && (uiNode->getNode() != nullptr))
{
if (uiNode->getNode()->getCategory() != mx::SURFACE_MATERIAL_NODE_STRING)
{
layoutPosition(uiNode, ImVec2(1200, 750), _initial, 0);
}
}
}
}
}
// reutrn pin color based on the type of the value of that pin
void Graph::setPinColor()
{
_pinColor.insert(std::make_pair("integer", ImColor(255, 255, 28, 255)));
_pinColor.insert(std::make_pair("boolean", ImColor(255, 0, 255, 255)));
_pinColor.insert(std::make_pair("float", ImColor(50, 100, 255, 255)));
_pinColor.insert(std::make_pair("color3", ImColor(178, 34, 34, 255)));
_pinColor.insert(std::make_pair("color4", ImColor(50, 10, 255, 255)));
_pinColor.insert(std::make_pair("vector2", ImColor(100, 255, 100, 255)));
_pinColor.insert(std::make_pair("vector3", ImColor(0, 255, 0, 255)));
_pinColor.insert(std::make_pair("vector4", ImColor(100, 0, 100, 255)));
_pinColor.insert(std::make_pair("matrix33", ImColor(0, 100, 100, 255)));
_pinColor.insert(std::make_pair("matrix44", ImColor(50, 255, 100, 255)));
_pinColor.insert(std::make_pair("filename", ImColor(255, 184, 28, 255)));
_pinColor.insert(std::make_pair("string", ImColor(100, 100, 50, 255)));
_pinColor.insert(std::make_pair("geomname", ImColor(121, 60, 180, 255)));
_pinColor.insert(std::make_pair("BSDF", ImColor(10, 181, 150, 255)));
_pinColor.insert(std::make_pair("EDF", ImColor(255, 50, 100, 255)));
_pinColor.insert(std::make_pair("VDF", ImColor(0, 100, 151, 255)));
_pinColor.insert(std::make_pair("surfaceshader", ImColor(150, 255, 255, 255)));
_pinColor.insert(std::make_pair("material", ImColor(255, 255, 255, 255)));
_pinColor.insert(std::make_pair(mx::DISPLACEMENT_SHADER_TYPE_STRING, ImColor(155, 50, 100, 255)));
_pinColor.insert(std::make_pair(mx::VOLUME_SHADER_TYPE_STRING, ImColor(155, 250, 100, 255)));
_pinColor.insert(std::make_pair(mx::LIGHT_SHADER_TYPE_STRING, ImColor(100, 150, 100, 255)));
_pinColor.insert(std::make_pair("none", ImColor(140, 70, 70, 255)));
_pinColor.insert(std::make_pair(mx::MULTI_OUTPUT_TYPE_STRING, ImColor(70, 70, 70, 255)));
_pinColor.insert(std::make_pair("integerarray", ImColor(200, 10, 100, 255)));
_pinColor.insert(std::make_pair("floatarray", ImColor(25, 250, 100)));
_pinColor.insert(std::make_pair("color3array", ImColor(25, 200, 110)));
_pinColor.insert(std::make_pair("color4array", ImColor(50, 240, 110)));
_pinColor.insert(std::make_pair("vector2array", ImColor(50, 200, 75)));
_pinColor.insert(std::make_pair("vector3array", ImColor(20, 200, 100)));
_pinColor.insert(std::make_pair("vector4array", ImColor(100, 200, 100)));
_pinColor.insert(std::make_pair("geomnamearray", ImColor(150, 200, 100)));
_pinColor.insert(std::make_pair("stringarray", ImColor(120, 180, 100)));
}
// based off of showLabel from ImGui Node Editor blueprints-example.cpp
auto showLabel = [](const char* label, ImColor color)
{
ImGui::SetCursorPosY(ImGui::GetCursorPosY() - ImGui::GetTextLineHeight());
auto size = ImGui::CalcTextSize(label);
auto padding = ImGui::GetStyle().FramePadding;
auto spacing = ImGui::GetStyle().ItemSpacing;
ImGui::SetCursorPos(ImGui::GetCursorPos() + ImVec2(spacing.x, -spacing.y));
auto rectMin = ImGui::GetCursorScreenPos() - padding;
auto rectMax = ImGui::GetCursorScreenPos() + size + padding;
auto drawList = ImGui::GetWindowDrawList();
drawList->AddRectFilled(rectMin, rectMax, color, size.y * 0.15f);
ImGui::TextUnformatted(label);
};
void Graph::selectMaterial(UiNodePtr uiNode)
{
// find renderable element that correspond with material uiNode
std::vector<mx::TypedElementPtr> elems = mx::findRenderableElements(_graphDoc);
mx::TypedElementPtr typedElem = nullptr;
for (mx::TypedElementPtr elem : elems)
{
mx::TypedElementPtr renderableElem = elem;
mx::NodePtr node = elem->asA<mx::Node>();
if (node == uiNode->getNode())
{
typedElem = elem;
}
}
_renderer->setMaterial(typedElem);
}
// set the node to display in render veiw based off the selected node or nodegraph
void Graph::setRenderMaterial(UiNodePtr node)
{
// set render node right away is node is a material
if (node->getNode() && node->getNode()->getType() == "material")
{
// only set new render node if different material has been selected
if (_currRenderNode != node)
{
_currRenderNode = node;
_frameCount = ImGui::GetFrameCount();
_renderer->setMaterialCompilation(true);
}
}
else
{
// continue downstream using output connections until a material node is found
std::vector<UiNodePtr> outNodes = node->getOutputConnections();
if (outNodes.size() > 0)
{
if (outNodes[0]->getNode())
{
if (outNodes[0]->getNode()->getType() == mx::SURFACE_SHADER_TYPE_STRING)
{
std::vector<UiNodePtr> shaderOut = outNodes[0]->getOutputConnections();
if (shaderOut.size() > 0)
{
if (shaderOut[0])
{
if (shaderOut[0]->getNode()->getType() == "material")
{
if (_currRenderNode != shaderOut[0])
{
_currRenderNode = shaderOut[0];
_frameCount = ImGui::GetFrameCount();
_renderer->setMaterialCompilation(true);
}
}
}
}
else
{
_currRenderNode = nullptr;
}
}
else if (outNodes[0]->getNode()->getType() == mx::MATERIAL_TYPE_STRING)
{
if (_currRenderNode != outNodes[0])
{
_currRenderNode = outNodes[0];
_frameCount = ImGui::GetFrameCount();
_renderer->setMaterialCompilation(true);
}
}
}
else
{
_currRenderNode = nullptr;
}
}
else
{
_currRenderNode = nullptr;
}
}
}
void Graph::updateMaterials(mx::InputPtr input, mx::ValuePtr value)
{
std::string renderablePath;
mx::TypedElementPtr renderableElem;
std::vector<mx::TypedElementPtr> elems = mx::findRenderableElements(_graphDoc);
size_t num = 0;
int num2 = 0;
for (mx::TypedElementPtr elem : elems)
{
renderableElem = elem;
mx::NodePtr node = elem->asA<mx::Node>();
if (node)
{
if (_currRenderNode)
{
if (node->getName() == _currRenderNode->getName())
{
renderablePath = renderableElem->getNamePath();
break;
}
}
else
{
renderablePath = renderableElem->getNamePath();
}
}
else
{
renderablePath = renderableElem->getNamePath();
if (num2 == 2)
{
break;
}
num2++;
}
}
if (renderablePath.empty())
{
_renderer->updateMaterials(nullptr);
}
else
{
if (!input)
{
mx::ElementPtr elem = nullptr;
{
elem = _graphDoc->getDescendant(renderablePath);
}
mx::TypedElementPtr typedElem = elem ? elem->asA<mx::TypedElement>() : nullptr;
_renderer->updateMaterials(typedElem);
}
else
{
std::string name = input->getNamePath();
// need to use exact interface name in order for input
mx::InputPtr interfaceInput = findInput(input, input->getName());
if (interfaceInput)
{
name = interfaceInput->getNamePath();
}
// Note that if there is a topogical change due to
// this value change or a transparency change, then
// this is not currently caught here.
_renderer->getMaterials()[num]->modifyUniform(name, value);
}
}
}
// set the value of the selected node constants in the node property editor
void Graph::setConstant(UiNodePtr node, mx::InputPtr& input, const mx::UIProperties& uiProperties)
{
std::string inName = !uiProperties.uiName.empty() ? uiProperties.uiName : input->getName();
ImGui::PushItemWidth(-1);
mx::ValuePtr minVal = uiProperties.uiMin;
mx::ValuePtr maxVal = uiProperties.uiMax;
// if input is a float set the float slider Ui to the value
if (input->getType() == "float")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<float>())
{
// updates the value to the default for new nodes
float prev = val->asA<float>(), temp = val->asA<float>();
float min = minVal ? minVal->asA<float>() : 0.f;
float max = maxVal ? maxVal->asA<float>() : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat("##hidelabel", &temp, speed, min, max);
// set input value and update materials if different from previous value
if (prev != temp)
{
addNodeInput(_currUiNode, input);
input->setValue(temp, input->getType());
updateMaterials(input, input->getValue());
}
}
}
else if (input->getType() == "integer")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<int>())
{
int prev = val->asA<int>(), temp = val->asA<int>();
int min = minVal ? minVal->asA<int>() : 0;
int max = maxVal ? maxVal->asA<int>() : 100;
float speed = (max - min) / 100.0f;
ImGui::DragInt("##hidelabel", &temp, speed, min, max);
// set input value and update materials if different from previous value
if (prev != temp)
{
addNodeInput(_currUiNode, input);
input->setValue(temp, input->getType());
updateMaterials(input, input->getValue());
}
}
}
else if (input->getType() == "color3")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Color3>())
{
mx::Color3 prev = val->asA<mx::Color3>(), temp = val->asA<mx::Color3>();
float min = minVal ? minVal->asA<mx::Color3>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Color3>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::PushItemWidth(-100);
ImGui::DragFloat3("##hidelabel", &temp[0], speed, min, max);
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::ColorEdit3("##color", &temp[0], ImGuiColorEditFlags_NoInputs);
// set input value and update materials if different from previous value
if (prev != temp)
{
addNodeInput(_currUiNode, input);
input->setValue(temp, input->getType());
updateMaterials(input, input->getValue());
}
}
}
else if (input->getType() == "color4")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Color4>())
{
mx::Color4 prev = val->asA<mx::Color4>(), temp = val->asA<mx::Color4>();
float min = minVal ? minVal->asA<mx::Color4>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Color4>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::PushItemWidth(-100);
ImGui::DragFloat4("##hidelabel", &temp[0], speed, min, max);
ImGui::PopItemWidth();
ImGui::SameLine();
// color edit for the color picker to the right of the color floats
ImGui::ColorEdit4("##color", &temp[0], ImGuiColorEditFlags_NoInputs);
// set input value and update materials if different from previous value
if (temp != prev)
{
addNodeInput(_currUiNode, input);
input->setValue(temp, input->getType());
updateMaterials(input, input->getValue());
}
}
}
else if (input->getType() == "vector2")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Vector2>())
{
mx::Vector2 prev = val->asA<mx::Vector2>(), temp = val->asA<mx::Vector2>();
float min = minVal ? minVal->asA<mx::Vector2>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Vector2>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat2("##hidelabel", &temp[0], speed, min, max);
// set input value and update materials if different from previous value
if (prev != temp)
{
addNodeInput(_currUiNode, input);
input->setValue(temp, input->getType());
updateMaterials(input, input->getValue());
}
}
}
else if (input->getType() == "vector3")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Vector3>())
{
mx::Vector3 prev = val->asA<mx::Vector3>(), temp = val->asA<mx::Vector3>();
float min = minVal ? minVal->asA<mx::Vector3>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Vector3>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat3("##hidelabel", &temp[0], speed, min, max);
// set input value and update materials if different from previous value
if (prev != temp)
{
addNodeInput(_currUiNode, input);
input->setValue(temp, input->getType());
updateMaterials(input, input->getValue());
}
}
}
else if (input->getType() == "vector4")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<mx::Vector4>())
{
mx::Vector4 prev = val->asA<mx::Vector4>(), temp = val->asA<mx::Vector4>();
float min = minVal ? minVal->asA<mx::Vector4>()[0] : 0.f;
float max = maxVal ? maxVal->asA<mx::Vector4>()[0] : 100.f;
float speed = (max - min) / 1000.0f;
ImGui::DragFloat4("##hidelabel", &temp[0], speed, min, max);
// set input value and update materials if different from previous value
if (prev != temp)
{
addNodeInput(_currUiNode, input);
input->setValue(temp, input->getType());
updateMaterials(input, input->getValue());
}
}
}
else if (input->getType() == "string")
{
mx::ValuePtr val = input->getValue();
if (val && val->isA<std::string>())
{
std::string prev = val->asA<std::string>(), temp = val->asA<std::string>();
ImGui::InputText("##constant", &temp);
// set input value and update materials if different from previous value
if (prev != temp)