Blender V5.3
shader_graph.cpp
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2022 Blender Foundation
2 *
3 * SPDX-License-Identifier: Apache-2.0 */
4
6#include "scene/attribute.h"
8#include "scene/scene.h"
9#include "scene/shader.h"
10#include "scene/shader_nodes.h"
11
12#include "util/algorithm.h"
13
14#include "util/log.h"
15#include "util/md5.h"
16#include "util/queue.h"
17
19
20namespace {
21
23{
24 for (const ShaderInput *in : node->inputs) {
25 if (in->link) {
26 return true;
27 }
28 }
29 return false;
30}
31
33{
34 for (const ShaderInput *in : node->inputs) {
35 if (in->link) {
36 if (!done.contains(in->link->parent)) {
37 return false;
38 }
39 }
40 }
41 return true;
42}
43
44} /* namespace */
45
46/* Sockets */
47
49{
50 if (link) {
51 link->links.erase(remove(link->links.begin(), link->links.end(), this), link->links.end());
52 }
53 link = nullptr;
54}
55
57{
58 for (ShaderInput *sock : links) {
59 sock->link = nullptr;
60 }
61
62 links.clear();
63}
64
65/* Node */
66
71
73 : Node(other.type), bump(other.bump), special_type(other.special_type)
74{
75 /* Inputs and outputs are recreated, no links to other nodes will remain. */
76 name = other.name;
78}
79
81{
82 for (const SocketType &socket : type->inputs) {
83 if (socket.flags & SocketType::LINKABLE) {
84 inputs.push_back(make_unique<ShaderInput>(socket, this));
85 }
86 }
87
88 for (const SocketType &socket : type->outputs) {
89 outputs.push_back(make_unique<ShaderOutput>(socket, this));
90 }
91}
92
94{
95 for (ShaderInput *socket : inputs) {
96 if (socket->name() == name) {
97 return socket;
98 }
99 }
100
101 return nullptr;
102}
103
105{
106 for (ShaderOutput *socket : outputs) {
107 if (socket->name() == name) {
108 return socket;
109 }
110 }
111
112 return nullptr;
113}
114
116{
117 for (ShaderInput *socket : inputs) {
118 if (socket->name() == name) {
119 return socket;
120 }
121 }
122
123 return nullptr;
124}
125
127{
128 for (ShaderOutput *socket : outputs) {
129 if (socket->name() == name) {
130 return socket;
131 }
132 }
133
134 return nullptr;
135}
136
138{
139 ShaderInput *socket = input(name);
140 if (socket && socket->link) {
141 socket->disconnect();
142 }
143}
144
146{
147 assert(input->link == nullptr);
149}
150
152{
153 for (ShaderInput *input : inputs) {
154 if (!input->link) {
156 if (shader->has_surface_link()) {
158 }
159 if (shader->has_volume) {
161 }
162 }
164 if (shader->has_surface_link()) {
166 }
167 }
168 }
169 }
170}
171
172void ShaderNode::global_attributes(Shader * /*shader*/, AttributeRequestSet * /*attributes*/) {}
173
175{
176 if (type != other.type || bump != other.bump) {
177 return false;
178 }
179
180 assert(inputs.size() == other.inputs.size());
181
182 /* Compare unlinkable sockets */
183 for (const SocketType &socket : type->inputs) {
184 if (!(socket.flags & SocketType::LINKABLE)) {
185 if (!Node::equals_value(other, socket)) {
186 return false;
187 }
188 }
189 }
190
191 /* Compare linkable input sockets */
192 for (int i = 0; i < inputs.size(); ++i) {
193 ShaderInput *input_a = inputs[i];
194 ShaderInput *input_b = other.inputs[i];
195 if (input_a->link == nullptr && input_b->link == nullptr) {
196 /* Unconnected inputs are expected to have the same value. */
197 if (!Node::equals_value(other, input_a->socket_type)) {
198 return false;
199 }
200 }
201 else if (input_a->link != nullptr && input_b->link != nullptr) {
202 /* Expect links are to come from the same exact socket. */
203 if (input_a->link != input_b->link) {
204 return false;
205 }
206 }
207 else {
208 /* One socket has a link and another has not, inputs can't be
209 * considered equal.
210 */
211 return false;
212 }
213 }
214
215 return true;
216}
217
218/* Graph */
219
221{
222 finalized = false;
223 simplified = false;
224 num_node_ids = 0;
226}
227
232
234{
236 simplified = false;
237
238 node->set_owner(this);
239 node->id = num_node_ids++;
240 nodes.push_back(std::move(node));
241}
242
244{
245 return static_cast<OutputNode *>(nodes[0]);
246}
247
249{
251 assert(from && to);
252
253 if (to->link) {
254 LOG_WARNING << "Graph connect: input already connected.";
255 return;
256 }
257
258 if (from->type() != to->type()) {
259 /* can't do automatic conversion from closure */
260 if (from->type() == SocketType::CLOSURE) {
261 LOG_WARNING << "Shader graph connect: can only connect closure to closure ("
262 << from->parent->name.c_str() << "." << from->name().c_str() << " to "
263 << to->parent->name.c_str() << "." << to->name().c_str() << ")";
264 return;
265 }
266
267 /* add automatic conversion node in case of type mismatch */
268 ShaderNode *convert;
269 ShaderInput *convert_in;
270
271 if (to->type() == SocketType::CLOSURE) {
273 emission->from_auto_conversion = true;
274 emission->set_color(one_float3());
275 emission->set_strength(1.0f);
276 convert = emission;
277 /* Connect float inputs to Strength to save an additional Value->Color conversion. */
278 if (from->type() == SocketType::FLOAT) {
279 convert_in = convert->input("Strength");
280 }
281 else {
282 convert_in = convert->input("Color");
283 }
284 }
285 else {
286 convert = create_node<ConvertNode>(from->type(), to->type(), true);
287 convert_in = convert->inputs[0];
288 }
289
290 connect(from, convert_in);
291 connect(convert->outputs[0], to);
292 }
293 else {
294 /* types match, just connect */
295 to->link = from;
296 from->links.push_back(to);
297 }
298}
299
301{
303 simplified = false;
304
305 from->disconnect();
306}
307
309{
311 assert(to->link);
312 simplified = false;
313
314 to->disconnect();
315}
316
318{
319 ShaderOutput *out = from->link;
320 if (out) {
321 disconnect(from);
322 connect(out, to);
323 }
324 to->parent->copy_value(to->socket_type, *(from->parent), from->socket_type);
325}
326
328{
329 /* Copy because disconnect modifies this list. */
330 const vector<ShaderInput *> outputs = from->links;
331
332 for (ShaderInput *sock : outputs) {
333 disconnect(sock);
334 if (to) {
335 connect(to, sock);
336 }
337 }
338}
339
341{
342 simplified = false;
343
344 /* Copy because disconnect modifies this list */
345 const vector<ShaderInput *> outputs = from->links;
346
347 /* Bypass node by moving all links from "from" to "to" */
348 for (ShaderInput *sock : node->inputs) {
349 if (sock->link) {
350 disconnect(sock);
351 }
352 }
353
354 for (ShaderInput *sock : outputs) {
355 disconnect(sock);
356 if (to) {
357 connect(to, sock);
358 }
359 }
360}
361
363{
364 if (!simplified) {
365 expand();
366 default_inputs(scene->shader_manager->use_osl());
367 clean(scene);
369
370 simplified = true;
371 }
372}
373
374void ShaderGraph::finalize(Scene *scene, bool do_bump, bool bump_in_object_space)
375{
376 /* before compiling, the shader graph may undergo a number of modifications.
377 * currently we set default geometry shader inputs, and create automatic bump
378 * from displacement. a graph can be finalized only once, and should not be
379 * modified afterwards. */
380
381 if (!finalized) {
382 simplify(scene);
383
384 if (do_bump) {
385 bump_from_displacement(bump_in_object_space);
386 }
387
388 ShaderInput *surface_in = output()->input("Surface");
389 ShaderInput *volume_in = output()->input("Volume");
390
391 /* todo: make this work when surface and volume closures are tangled up */
392
393 if (surface_in->link) {
394 transform_multi_closure(surface_in->link->parent, nullptr, false);
395 }
396 if (volume_in->link) {
397 transform_multi_closure(volume_in->link->parent, nullptr, true);
398 }
399
400 finalized = true;
401 }
402}
403
405{
406 /* find all nodes that this input depends on directly and indirectly */
407 ShaderNode *node = (input->link) ? input->link->parent : nullptr;
408
409 if (node != nullptr && !dependencies.contains(node)) {
410 for (ShaderInput *in : node->inputs) {
411 find_dependencies(dependencies, in);
412 }
413
414 dependencies.insert(node);
415 }
416}
417
419{
420 nodes.clear();
421}
422
424{
425 /* copy a set of nodes, and the links between them. the assumption is
426 * made that all nodes that inputs are linked to are in the set too. */
427
428 /* copy nodes */
429 for (ShaderNode *node : nodes) {
430 ShaderNode *nnode = node->clone(this);
431 nnodemap[node] = nnode;
432 }
433
434 /* recreate links */
435 for (ShaderNode *node : nodes) {
436 for (ShaderInput *input : node->inputs) {
437 if (input->link) {
438 /* find new input and output */
439 ShaderNode *nfrom = nnodemap[input->link->parent];
440 ShaderNode *nto = nnodemap[input->parent];
441 ShaderOutput *noutput = nfrom->output(input->link->name());
442 ShaderInput *ninput = nto->input(input->name());
443
444 /* connect */
445 connect(noutput, ninput);
446 }
447 }
448 }
449}
450
451/* Graph simplification */
452/* ******************** */
453
454/* Remove proxy nodes.
455 *
456 * These only exists temporarily when exporting groups, and we must remove them
457 * early so that node->attributes() and default links do not see them.
458 */
460{
461 vector<bool> removed(num_node_ids, false);
462 bool any_node_removed = false;
463
464 for (ShaderNode *node : nodes) {
465 if (node->special_type == SHADER_SPECIAL_TYPE_PROXY) {
466 ConvertNode *proxy = static_cast<ConvertNode *>(node);
467 ShaderInput *input = proxy->inputs[0];
468 ShaderOutput *output = proxy->outputs[0];
469
470 /* bypass the proxy node */
471 if (input->link) {
472 relink(proxy, output, input->link);
473 }
474 else {
475 /* Copy because disconnect modifies this list */
476 const vector<ShaderInput *> links(output->links);
477
478 for (ShaderInput *to : links) {
479 /* Remove any auto-convert nodes too if they lead to
480 * sockets with an automatically set default value. */
481 ShaderNode *tonode = to->parent;
482
484 bool all_links_removed = true;
485 const vector<ShaderInput *> links = tonode->outputs[0]->links;
486
487 for (ShaderInput *autoin : links) {
488 if (autoin->flags() & SocketType::DEFAULT_LINK_MASK) {
489 disconnect(autoin);
490 }
491 else {
492 all_links_removed = false;
493 }
494 }
495
496 if (all_links_removed) {
497 removed[tonode->id] = true;
498 }
499 }
500
501 disconnect(to);
502
503 /* transfer the default input value to the target socket */
504 tonode->copy_value(to->socket_type, *proxy, input->socket_type);
505 }
506 }
507
508 removed[proxy->id] = true;
509 any_node_removed = true;
510 }
511 }
512
513 /* remove nodes */
514 if (any_node_removed) {
516
517 for (size_t i = 0; i < nodes.size(); i++) {
519 if (!removed[node->id]) {
520 newnodes.push_back(std::move(node));
521 }
522 }
523
524 nodes = std::move(newnodes);
525 }
526}
527
528/* Constant folding.
529 *
530 * Try to constant fold some nodes, and pipe result directly to
531 * the input socket of connected nodes.
532 */
534{
535 ShaderNodeSet done;
536 ShaderNodeSet scheduled;
537 queue<ShaderNode *> traverse_queue;
538
539 const bool has_displacement = (output()->input("Displacement")->link != nullptr);
540
541 /* Schedule nodes which doesn't have any dependencies. */
542 for (ShaderNode *node : nodes) {
543 if (!check_node_inputs_has_links(node)) {
544 traverse_queue.push(node);
545 scheduled.insert(node);
546 }
547 }
548
549 while (!traverse_queue.empty()) {
550 ShaderNode *node = traverse_queue.front();
551 traverse_queue.pop();
552 done.insert(node);
553 for (ShaderOutput *output : node->outputs) {
554 if (output->links.empty()) {
555 continue;
556 }
557 /* Schedule node which was depending on the value,
558 * when possible. Do it before disconnect.
559 */
560 for (ShaderInput *input : output->links) {
561 if (scheduled.contains(input->parent)) {
562 /* Node might not be optimized yet but scheduled already
563 * by other dependencies. No need to re-schedule it.
564 */
565 continue;
566 }
567 /* Schedule node if its inputs are fully done. */
568 if (check_node_inputs_traversed(input->parent, done)) {
569 traverse_queue.push(input->parent);
570 scheduled.insert(input->parent);
571 }
572 }
573 /* Optimize current node. */
574 const ConstantFolder folder(this, node, output, scene);
575 node->constant_fold(folder);
576 }
577 }
578
579 /* Folding might have removed all nodes connected to the displacement output
580 * even tho there is displacement to be applied, so add in a value node if
581 * that happens to ensure there is still a valid graph for displacement.
582 */
583 if (has_displacement && !output()->input("Displacement")->link) {
585 value->set_value(output()->get_displacement());
586
587 connect(value->output("Color"), output()->input("Displacement"));
588 }
589}
590
591/* Simplification. */
593{
594 for (ShaderNode *node : nodes) {
595 node->simplify_settings(scene);
596 }
597}
598
599/* Deduplicate nodes with same settings. */
601{
602 /* NOTES:
603 * - Deduplication happens for nodes which has same exact settings and same
604 * exact input links configuration (either connected to same output or has
605 * the same exact default value).
606 * - Deduplication happens in the bottom-top manner, so we know for fact that
607 * all traversed nodes are either can not be deduplicated at all or were
608 * already deduplicated.
609 */
610
611 ShaderNodeSet scheduled;
612 ShaderNodeSet done;
613 map<ustring, ShaderNodeSet> candidates;
614 queue<ShaderNode *> traverse_queue;
615 int num_deduplicated = 0;
616
617 /* Schedule nodes which doesn't have any dependencies. */
618 for (ShaderNode *node : nodes) {
619 if (!check_node_inputs_has_links(node)) {
620 traverse_queue.push(node);
621 scheduled.insert(node);
622 }
623 }
624
625 while (!traverse_queue.empty()) {
626 ShaderNode *node = traverse_queue.front();
627 traverse_queue.pop();
628 done.insert(node);
629 /* Schedule the nodes which were depending on the current node. */
630 bool has_output_links = false;
631 for (ShaderOutput *output : node->outputs) {
632 for (ShaderInput *input : output->links) {
633 has_output_links = true;
634 if (scheduled.contains(input->parent)) {
635 /* Node might not be optimized yet but scheduled already
636 * by other dependencies. No need to re-schedule it.
637 */
638 continue;
639 }
640 /* Schedule node if its inputs are fully done. */
641 if (check_node_inputs_traversed(input->parent, done)) {
642 traverse_queue.push(input->parent);
643 scheduled.insert(input->parent);
644 }
645 }
646 }
647 /* Only need to care about nodes that are actually used */
648 if (!has_output_links) {
649 continue;
650 }
651 /* Try to merge this node with another one. */
652 ShaderNode *merge_with = nullptr;
653 for (ShaderNode *other_node : candidates[node->type->name]) {
654 if (node != other_node && node->equals(*other_node)) {
655 merge_with = other_node;
656 break;
657 }
658 }
659 /* If found an equivalent, merge; otherwise keep node for later merges */
660 if (merge_with != nullptr) {
661 for (int i = 0; i < node->outputs.size(); ++i) {
662 relink(node, node->outputs[i], merge_with->outputs[i]);
663 }
664 num_deduplicated++;
665 }
666 else {
667 candidates[node->type->name].insert(node);
668 }
669 }
670
671 if (num_deduplicated > 0) {
672 LOG_TRACE << "Deduplicated " << num_deduplicated << " nodes.";
673 }
674}
675
676/* Does two optimizations:
677 * - Check whether volume output has meaningful nodes, otherwise disconnect the output.
678 * - Tag volume attribute nodes as supporting stochastic sampling. */
680{
681 ShaderInput *volume_in = output()->input("Volume");
682 if (volume_in->link == nullptr) {
683 return;
684 }
685
686 bool has_valid_volume = false;
687
688 using ShaderNodeAndNonLinear = std::pair<ShaderNode *, bool>;
689 set<ShaderNodeAndNonLinear, ShaderNodeIDAndBoolComparator> scheduled;
690 queue<ShaderNodeAndNonLinear> traverse_queue;
691
692 /* Schedule volume output. */
693 traverse_queue.emplace(volume_in->link->parent, false);
694 scheduled.insert({volume_in->link->parent, false});
695
696 /* Traverse down the tree. */
697 while (!traverse_queue.empty()) {
698 auto [node, nonlinear] = traverse_queue.front();
699 traverse_queue.pop();
700
701 /* Disable stochastic sampling on node if its contribution is nonlinear.
702 * This defaults to true in the class, so we only need to disable it. */
703 if (nonlinear && node->type == AttributeNode::get_node_type()) {
704 static_cast<AttributeNode *>(node)->stochastic_sample = false;
705 }
706 nonlinear = nonlinear || !node->is_linear_operation();
707
708 /* Node is fully valid for volume, won't be able to optimize it out. */
709 if (node->has_volume_support()) {
710 has_valid_volume = true;
711 }
712
713 for (ShaderInput *input : node->inputs) {
714 if (input->link == nullptr) {
715 continue;
716 }
717 ShaderNode *input_node = input->link->parent;
718 if (scheduled.contains({input_node, nonlinear})) {
719 continue;
720 }
721 traverse_queue.emplace(input_node, nonlinear);
722 scheduled.insert({input_node, nonlinear});
723 }
724 }
725
727 for (ShaderNode *node : nodes) {
728 if (node->type == AttributeNode::get_node_type() &&
729 static_cast<AttributeNode *>(node)->stochastic_sample)
730 {
731 LOG_TRACE << "Volume attribute node " << node->name << " uses stochastic sampling";
732 }
733 }
734 }
735
736 if (!has_valid_volume) {
737 /* We can remove the entire volume shader. */
738 LOG_TRACE << "Disconnect meaningless volume output.";
739 disconnect(volume_in->link);
740 }
741}
742
744{
745 visited[node->id] = true;
746 on_stack[node->id] = true;
747
748 for (ShaderInput *input : node->inputs) {
749 if (input->link) {
750 ShaderNode *depnode = input->link->parent;
751
752 if (on_stack[depnode->id]) {
753 /* break cycle */
754 disconnect(input);
755 LOG_WARNING << "Shader graph: detected cycle in graph, connection removed.";
756 }
757 else if (!visited[depnode->id]) {
758 /* visit dependencies */
759 break_cycles(depnode, visited, on_stack);
760 }
761 }
762 }
763
764 on_stack[node->id] = false;
765}
766
768{
769 /* Compute hash of all nodes linked to displacement, to detect if we need
770 * to recompute displacement when shader nodes change. */
771 ShaderInput *displacement_in = output()->input("Displacement");
772
773 if (!displacement_in->link) {
775 return;
776 }
777
778 ShaderNodeSet nodes_displace;
779 find_dependencies(nodes_displace, displacement_in);
780
781 MD5Hash md5;
782 for (ShaderNode *node : nodes_displace) {
783 node->hash(md5);
784 for (ShaderInput *input : node->inputs) {
785 int link_id = (input->link) ? input->link->parent->id : 0;
786 md5.append((uint8_t *)&link_id, sizeof(link_id));
787 md5.append((input->link) ? input->link->name().c_str() : "");
788 }
789
790 if (node->special_type == SHADER_SPECIAL_TYPE_OSL) {
791 /* Hash takes into account socket values, to detect changes
792 * in the code of the node we need an exception. */
793 OSLNode *oslnode = static_cast<OSLNode *>(node);
794 md5.append(oslnode->bytecode_hash);
795 }
796 }
797
799}
800
802{
803 /* Graph simplification */
804
805 /* NOTE: Remove proxy nodes was already done. */
806 constant_fold(scene);
807 simplify_settings(scene);
810
811 /* we do two things here: find cycles and break them, and remove unused
812 * nodes that don't feed into the output. how cycles are broken is
813 * undefined, they are invalid input, the important thing is to not crash */
814
815 vector<bool> visited(num_node_ids, false);
816 vector<bool> on_stack(num_node_ids, false);
817
818 /* break cycles */
819 break_cycles(output(), visited, on_stack);
820 for (ShaderNode *node : nodes) {
821 if (node->special_type == SHADER_SPECIAL_TYPE_OUTPUT_AOV) {
822 break_cycles(node, visited, on_stack);
823 }
824 }
825
826 /* disconnect unused nodes */
827 for (ShaderNode *node : nodes) {
828 if (!visited[node->id]) {
829 for (ShaderInput *to : node->inputs) {
830 ShaderOutput *from = to->link;
831
832 if (from) {
833 to->link = nullptr;
834 from->links.erase(remove(from->links.begin(), from->links.end(), to), from->links.end());
835 }
836 }
837 }
838 }
839
840 /* remove unused nodes */
842
843 for (size_t i = 0; i < nodes.size(); i++) {
845 if (visited[node->id]) {
846 newnodes.push_back(std::move(node));
847 }
848 }
849
850 nodes = std::move(newnodes);
851}
852
854{
855 /* Call expand on all nodes, to generate additional nodes.
856 * No range based for loop because we modify the vector, and want to expand
857 * newly generated nodes too. */
858 for (size_t i = 0; i < nodes.size(); i++) {
859 ShaderNode *node = nodes[i];
860 node->expand(this);
861 }
862}
863
865{
866 /* nodes can specify default texture coordinates, for now we give
867 * everything the position by default, except for the sky texture */
868
869 GeometryNode *geom = nullptr;
870 TextureCoordinateNode *texco = nullptr;
871 VectorTransformNode *normal_transform = nullptr;
872
873 for (size_t i = 0; i < nodes.size(); i++) {
874 ShaderNode *node = nodes[i];
875
876 for (ShaderInput *input : node->inputs) {
877 if (!input->link && (!(input->flags() & SocketType::OSL_INTERNAL) || do_osl)) {
879 if (!texco) {
881 }
882
883 connect(texco->output("Generated"), input);
884 }
885 if (input->flags() & SocketType::LINK_TEXTURE_NORMAL) {
886 if (!texco) {
888 }
889
890 connect(texco->output("Normal"), input);
891 }
892 else if (input->flags() & SocketType::LINK_TEXTURE_UV) {
893 if (!texco) {
895 }
896
897 connect(texco->output("UV"), input);
898 }
899 else if (input->flags() & SocketType::LINK_TEXTURE_INCOMING) {
900 if (!geom) {
902 }
903 if (!normal_transform) {
904 normal_transform = create_node<VectorTransformNode>();
905 normal_transform->set_transform_type(NODE_VECTOR_TRANSFORM_TYPE_NORMAL);
906 normal_transform->set_convert_from(NODE_VECTOR_TRANSFORM_CONVERT_SPACE_WORLD);
907 normal_transform->set_convert_to(NODE_VECTOR_TRANSFORM_CONVERT_SPACE_OBJECT);
908 connect(geom->output("Incoming"), normal_transform->input("Vector"));
909 }
910
911 connect(normal_transform->output("Vector"), input);
912 }
913 else if (input->flags() & SocketType::LINK_INCOMING) {
914 if (!geom) {
916 }
917
918 connect(geom->output("Incoming"), input);
919 }
920 else if (input->flags() & SocketType::LINK_NORMAL) {
921 if (!geom) {
923 }
924
925 connect(geom->output("Normal"), input);
926 }
927 else if (input->flags() & SocketType::LINK_POSITION) {
928 if (!geom) {
930 }
931
932 connect(geom->output("Position"), input);
933 }
934 else if (input->flags() & SocketType::LINK_TANGENT) {
935 if (!geom) {
937 }
938
939 connect(geom->output("Tangent"), input);
940 }
941 }
942 }
943 }
944}
945
947{
948 /* We transverse the node graph looking for bump nodes, when we find them,
949 * like in bump_from_displacement(), we copy the sub-graph defined from "bump"
950 * input to the inputs "center","dx" and "dy" What is in "bump" input is moved
951 * to "center" input. */
952
953 /* No range based for loop because we modify the vector. */
954 for (int i = 0; i < nodes.size(); i++) {
955 ShaderNode *node = nodes[i];
956
957 if (node->special_type == SHADER_SPECIAL_TYPE_BUMP && node->input("Height")->link) {
958 BumpNode *bump = static_cast<BumpNode *>(node);
959 ShaderInput *bump_input = node->input("Height");
960 ShaderNodeSet nodes_bump;
961
962 /* Make 2 extra copies of the subgraph defined in Bump input. */
963 ShaderNodeMap nodes_dx;
964 ShaderNodeMap nodes_dy;
965
966 /* Find dependencies for the given input. */
967 find_dependencies(nodes_bump, bump_input);
968
969 copy_nodes(nodes_bump, nodes_dx);
970 copy_nodes(nodes_bump, nodes_dy);
971
972 /* Mark nodes to indicate they are use for bump computation, so
973 * that any texture coordinates are shifted by dx/dy when sampling. */
974 for (ShaderNode *node : nodes_bump) {
975 node->bump = SHADER_BUMP_CENTER;
976 node->bump_filter_width = bump->get_filter_width();
977 }
978 for (const NodePair &pair : nodes_dx) {
979 pair.second->bump = SHADER_BUMP_DX;
980 pair.second->bump_filter_width = bump->get_filter_width();
981 }
982 for (const NodePair &pair : nodes_dy) {
983 pair.second->bump = SHADER_BUMP_DY;
984 pair.second->bump_filter_width = bump->get_filter_width();
985 }
986
987 ShaderOutput *out = bump_input->link;
988 ShaderOutput *out_dx = nodes_dx[out->parent]->output(out->name());
989 ShaderOutput *out_dy = nodes_dy[out->parent]->output(out->name());
990
991 connect(out_dx, node->input("SampleX"));
992 connect(out_dy, node->input("SampleY"));
993
994 /* Connect what is connected is bump to sample-center input. */
995 connect(out, node->input("SampleCenter"));
996
997 /* Bump input is just for connectivity purpose for the graph input,
998 * we re-connected this input to sample-center, so lets disconnect it
999 * from bump input. */
1000 disconnect(bump_input);
1001 }
1002 }
1003}
1004
1005void ShaderGraph::bump_from_displacement(bool use_object_space)
1006{
1007 /* generate bump mapping automatically from displacement. bump mapping is
1008 * done using a 3-tap filter, computing the displacement at the center,
1009 * and two other positions shifted by ray differentials.
1010 *
1011 * since the input to displacement is a node graph, we need to ensure that
1012 * all texture coordinates use are shift by the ray differentials. for this
1013 * reason we make 3 copies of the node subgraph defining the displacement,
1014 * with each different geometry and texture coordinate nodes that generate
1015 * different shifted coordinates.
1016 *
1017 * these 3 displacement values are then fed into the bump node, which will
1018 * output the perturbed normal. */
1019
1020 ShaderInput *displacement_in = output()->input("Displacement");
1021
1022 if (!displacement_in->link) {
1023 return;
1024 }
1025
1026 /* find dependencies for the given input */
1027 ShaderNodeSet nodes_displace;
1028 find_dependencies(nodes_displace, displacement_in);
1029
1030 /* Add bump node. */
1032 bump->set_use_object_space(use_object_space);
1033 bump->set_distance(1.0f);
1034
1035 /* copy nodes for 3 bump samples */
1036 ShaderNodeMap nodes_center;
1037 ShaderNodeMap nodes_dx;
1038 ShaderNodeMap nodes_dy;
1039
1040 copy_nodes(nodes_displace, nodes_center);
1041 copy_nodes(nodes_displace, nodes_dx);
1042 copy_nodes(nodes_displace, nodes_dy);
1043
1044 /* mark nodes to indicate they are use for bump computation, so
1045 * that any texture coordinates are shifted by dx/dy when sampling */
1046 for (const NodePair &pair : nodes_center) {
1047 pair.second->bump = SHADER_BUMP_CENTER;
1048 pair.second->bump_filter_width = bump->get_filter_width();
1049 }
1050 for (const NodePair &pair : nodes_dx) {
1051 pair.second->bump = SHADER_BUMP_DX;
1052 pair.second->bump_filter_width = bump->get_filter_width();
1053 }
1054 for (const NodePair &pair : nodes_dy) {
1055 pair.second->bump = SHADER_BUMP_DY;
1056 pair.second->bump_filter_width = bump->get_filter_width();
1057 }
1058
1059 /* add set normal node and connect the bump normal output to the set normal
1060 * output, so it can finally set the shader normal, note we are only doing
1061 * this for bump from displacement, this will be the only bump allowed to
1062 * overwrite the shader normal */
1063 ShaderNode *set_normal = create_node<SetNormalNode>();
1064
1065 /* Connect copied graphs to bump node. */
1066 ShaderOutput *out = displacement_in->link;
1067 ShaderOutput *out_center = nodes_center[out->parent]->output(out->name());
1068 ShaderOutput *out_dx = nodes_dx[out->parent]->output(out->name());
1069 ShaderOutput *out_dy = nodes_dy[out->parent]->output(out->name());
1070
1071 /* convert displacement vector to height */
1075
1076 dot_center->set_math_type(NODE_VECTOR_MATH_DOT_PRODUCT);
1077 dot_dx->set_math_type(NODE_VECTOR_MATH_DOT_PRODUCT);
1078 dot_dy->set_math_type(NODE_VECTOR_MATH_DOT_PRODUCT);
1079
1081 connect(geom->output("Normal"), bump->input("Normal"));
1082 connect(geom->output("Normal"), dot_center->input("Vector2"));
1083 connect(geom->output("Normal"), dot_dx->input("Vector2"));
1084 connect(geom->output("Normal"), dot_dy->input("Vector2"));
1085
1086 connect(out_center, dot_center->input("Vector1"));
1087 connect(out_dx, dot_dx->input("Vector1"));
1088 connect(out_dy, dot_dy->input("Vector1"));
1089
1090 connect(dot_center->output("Value"), bump->input("SampleCenter"));
1091 connect(dot_dx->output("Value"), bump->input("SampleX"));
1092 connect(dot_dy->output("Value"), bump->input("SampleY"));
1093
1094 /* connect the bump out to the set normal in: */
1095 connect(bump->output("Normal"), set_normal->input("Direction"));
1096
1097 /* connect to output node */
1098 connect(set_normal->output("Normal"), output()->input("Normal"));
1099}
1100
1102{
1103 /* for SVM in multi closure mode, this transforms the shader mix/add part of
1104 * the graph into nodes that feed weights into closure nodes. this is too
1105 * avoid building a closure tree and then flattening it, and instead write it
1106 * directly to an array */
1107
1108 if (node->special_type == SHADER_SPECIAL_TYPE_COMBINE_CLOSURE) {
1109 ShaderInput *fin = node->input("Fac");
1110 ShaderInput *cl1in = node->input("Closure1");
1111 ShaderInput *cl2in = node->input("Closure2");
1112 ShaderOutput *weight1_out;
1113 ShaderOutput *weight2_out;
1114
1115 if (fin) {
1116 /* mix closure: add node to mix closure weights */
1118 ShaderInput *fac_in = mix_node->input("Fac");
1119 ShaderInput *weight_in = mix_node->input("Weight");
1120
1121 if (fin->link) {
1122 connect(fin->link, fac_in);
1123 }
1124 else {
1125 mix_node->set_fac(node->get_float(fin->socket_type));
1126 }
1127
1128 if (weight_out) {
1129 connect(weight_out, weight_in);
1130 }
1131
1132 weight1_out = mix_node->output("Weight1");
1133 weight2_out = mix_node->output("Weight2");
1134 }
1135 else {
1136 /* add closure: just pass on any weights */
1137 weight1_out = weight_out;
1138 weight2_out = weight_out;
1139 }
1140
1141 if (cl1in->link) {
1142 transform_multi_closure(cl1in->link->parent, weight1_out, volume);
1143 }
1144 if (cl2in->link) {
1145 transform_multi_closure(cl2in->link->parent, weight2_out, volume);
1146 }
1147 }
1148 else {
1149 ShaderInput *weight_in = node->input((volume) ? "VolumeMixWeight" : "SurfaceMixWeight");
1150
1151 /* not a closure node? */
1152 if (!weight_in) {
1153 return;
1154 }
1155
1156 /* already has a weight connected to it? add weights */
1157 const float weight_value = node->get_float(weight_in->socket_type);
1158 if (weight_in->link || weight_value != 0.0f) {
1159 MathNode *math_node = create_node<MathNode>();
1160
1161 if (weight_in->link) {
1162 connect(weight_in->link, math_node->input("Value1"));
1163 }
1164 else {
1165 math_node->set_value1(weight_value);
1166 }
1167
1168 if (weight_out) {
1169 connect(weight_out, math_node->input("Value2"));
1170 }
1171 else {
1172 math_node->set_value2(1.0f);
1173 }
1174
1175 weight_out = math_node->output("Value");
1176 if (weight_in->link) {
1177 disconnect(weight_in);
1178 }
1179 }
1180
1181 /* connected to closure mix weight */
1182 if (weight_out) {
1183 connect(weight_out, weight_in);
1184 }
1185 else {
1186 node->set(weight_in->socket_type, weight_value + 1.0f);
1187 }
1188 }
1189}
1190
1192{
1193 int num_closures = 0;
1194 for (ShaderNode *node : nodes) {
1195 const ClosureType closure_type = node->get_closure_type();
1196 if (closure_type == CLOSURE_NONE_ID) {
1197 continue;
1198 }
1199 if (CLOSURE_IS_BSSRDF(closure_type)) {
1200 num_closures += 3;
1201 }
1202 else if (CLOSURE_IS_BSDF_MULTISCATTER(closure_type)) {
1203 num_closures += 2;
1204 }
1205 else if (CLOSURE_IS_PRINCIPLED(closure_type)) {
1206 num_closures += 12;
1207 }
1208 else if (CLOSURE_IS_VOLUME(closure_type)) {
1209 /* TODO(sergey): Verify this is still needed, since we have special minimized volume
1210 * storage for the volume steps. */
1211 num_closures += MAX_VOLUME_STACK_SIZE;
1212 }
1213 else if (closure_type == CLOSURE_BSDF_PHYSICAL_CONDUCTOR ||
1214 closure_type == CLOSURE_BSDF_F82_CONDUCTOR ||
1216 closure_type == CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID ||
1217 closure_type == CLOSURE_BSDF_HAIR_CHIANG_ID ||
1218 closure_type == CLOSURE_BSDF_HAIR_HUANG_ID)
1219 {
1220 num_closures += 2;
1221 }
1222 else {
1223 ++num_closures;
1224 }
1225 }
1226 return num_closures;
1227}
1228
1229void ShaderGraph::dump_graph(const char *filename)
1230{
1231 FILE *fd = fopen(filename, "w");
1232
1233 if (fd == nullptr) {
1234 LOG_ERROR << "Error opening file for dumping the graph: " << filename;
1235 return;
1236 }
1237
1238 fprintf(fd, "digraph shader_graph {\n");
1239 fprintf(fd, "ranksep=1.5\n");
1240 fprintf(fd, "rankdir=LR\n");
1241 fprintf(fd, "splines=false\n");
1242
1243 for (ShaderNode *node : nodes) {
1244 fprintf(fd, "// NODE: %p\n", node);
1245 fprintf(fd, "\"%p\" [shape=record,label=\"{", node);
1246 if (!node->inputs.empty()) {
1247 fprintf(fd, "{");
1248 for (ShaderInput *socket : node->inputs) {
1249 if (socket != node->inputs[0]) {
1250 fprintf(fd, "|");
1251 }
1252 fprintf(fd, "<IN_%p>%s", socket, socket->name().c_str());
1253 }
1254 fprintf(fd, "}|");
1255 }
1256 fprintf(fd, "%s", node->name.c_str());
1257 if (node->bump == SHADER_BUMP_CENTER) {
1258 fprintf(fd, " (bump:center)");
1259 }
1260 else if (node->bump == SHADER_BUMP_DX) {
1261 fprintf(fd, " (bump:dx)");
1262 }
1263 else if (node->bump == SHADER_BUMP_DY) {
1264 fprintf(fd, " (bump:dy)");
1265 }
1266 if (!node->outputs.empty()) {
1267 fprintf(fd, "|{");
1268 for (ShaderOutput *socket : node->outputs) {
1269 if (socket != node->outputs[0]) {
1270 fprintf(fd, "|");
1271 }
1272 fprintf(fd, "<OUT_%p>%s", socket, socket->name().c_str());
1273 }
1274 fprintf(fd, "}");
1275 }
1276 fprintf(fd, "}\"]");
1277 }
1278
1279 for (ShaderNode *node : nodes) {
1280 for (ShaderOutput *output : node->outputs) {
1281 for (ShaderInput *input : output->links) {
1282 fprintf(fd,
1283 "// CONNECTION: OUT_%p->IN_%p (%s:%s)\n",
1284 output,
1285 input,
1286 output->name().c_str(),
1287 input->name().c_str());
1288 fprintf(fd,
1289 "\"%p\":\"OUT_%p\":e -> \"%p\":\"IN_%p\":w [label=\"\"]\n",
1290 output->parent,
1291 output,
1292 input->parent,
1293 input);
1294 }
1295 }
1296 }
1297
1298 fprintf(fd, "}\n");
1299 fclose(fd);
1300}
1301
void add(ustring name)
bool from_auto_conversion
Definition md5.h:19
void append(const uint8_t *data, const int nbytes)
Definition md5.cpp:268
string get_hex()
Definition md5.cpp:367
string bytecode_hash
Definition scene.h:133
unique_ptr< ShaderManager > shader_manager
Definition scene.h:169
void find_dependencies(ShaderNodeSet &dependencies, ShaderInput *input)
string displacement_hash
OutputNode * output()
unique_ptr_vector< ShaderNode > nodes
void simplify(Scene *scene)
T * create_node(Args &&...args)
void add_node(unique_ptr< ShaderNode > &&node)
void disconnect(ShaderOutput *from)
size_t num_node_ids
void break_cycles(ShaderNode *node, vector< bool > &visited, vector< bool > &on_stack)
void copy_nodes(ShaderNodeSet &nodes, ShaderNodeMap &nnodemap)
void clean(Scene *scene)
void finalize(Scene *scene, bool do_bump=false, bool bump_in_object_space=false)
void compute_displacement_hash()
void default_inputs(bool do_osl)
void connect(ShaderOutput *from, ShaderInput *to)
void relink(ShaderInput *from, ShaderInput *to)
void optimize_volume_output()
void constant_fold(Scene *scene)
void transform_multi_closure(ShaderNode *node, ShaderOutput *weight_out, bool volume)
void deduplicate_nodes()
void remove_proxy_nodes()
void simplify_settings(Scene *scene)
void bump_from_displacement(bool use_object_space)
~ShaderGraph() override
pair< ShaderNode *const, ShaderNode * > NodePair
void refine_bump_nodes()
void dump_graph(const char *filename)
ustring name() const
const SocketType & socket_type
ShaderNode * parent
SocketType::Type type() const
void disconnect() override
ShaderOutput * link
int flags() const
ShaderInput * input(const char *name)
void remove_input(ShaderInput *input)
ShaderNodeSpecialType special_type
virtual void global_attributes(Shader *shader, AttributeRequestSet *attributes)
virtual bool equals(const ShaderNode &other)
void disconnect_unused_input(const char *name)
ShaderNode(const NodeType *type)
void create_inputs_outputs(const NodeType *type)
unique_ptr_vector< ShaderInput > inputs
ShaderBump bump
ShaderOutput * output(const char *name)
virtual void attributes(Shader *shader, AttributeRequestSet *attributes)
unique_ptr_vector< ShaderOutput > outputs
void disconnect() override
vector< ShaderInput * > links
bool has_surface_link() const
bool has_volume
void push_back(unique_ptr< T > &&value)
void erase(const T *value)
size_t size() const
#define CLOSURE_IS_VOLUME(type)
#define MAX_VOLUME_STACK_SIZE
#define CLOSURE_IS_PRINCIPLED(type)
#define CLOSURE_IS_BSSRDF(type)
#define CLOSURE_IS_BSDF_MULTISCATTER(type)
#define CCL_NAMESPACE_END
#define assert(assertion)
@ NODE_VECTOR_TRANSFORM_TYPE_NORMAL
ClosureType
@ CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID
@ CLOSURE_NONE_ID
@ CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID
@ CLOSURE_BSDF_PHYSICAL_CONDUCTOR
@ CLOSURE_BSDF_HAIR_HUANG_ID
@ CLOSURE_BSDF_F82_CONDUCTOR
@ CLOSURE_BSDF_HAIR_CHIANG_ID
@ NODE_VECTOR_MATH_DOT_PRODUCT
@ NODE_VECTOR_TRANSFORM_CONVERT_SPACE_OBJECT
@ NODE_VECTOR_TRANSFORM_CONVERT_SPACE_WORLD
@ ATTR_STD_GENERATED_TRANSFORM
@ ATTR_STD_UV
@ ATTR_STD_GENERATED
#define LOG_IS_ON(level)
Definition log.h:113
@ LOG_LEVEL_TRACE
Definition log.h:27
#define LOG_ERROR
Definition log.h:101
#define LOG_WARNING
Definition log.h:103
#define LOG_TRACE
Definition log.h:108
ccl_device_inline float3 one_float3()
Definition math_float3.h:26
bool check_node_inputs_traversed(const ShaderNode *node, const ShaderNodeSet &done)
bool check_node_inputs_has_links(const ShaderNode *node)
@ SHADER_SPECIAL_TYPE_PROXY
@ SHADER_SPECIAL_TYPE_OUTPUT_AOV
@ SHADER_SPECIAL_TYPE_COMBINE_CLOSURE
@ SHADER_SPECIAL_TYPE_BUMP
@ SHADER_SPECIAL_TYPE_AUTOCONVERT
@ SHADER_SPECIAL_TYPE_OSL
set< ShaderNode *, ShaderNodeIDComparator > ShaderNodeSet
map< ShaderNode *, ShaderNode *, ShaderNodeIDComparator > ShaderNodeMap
@ SHADER_BUMP_CENTER
@ SHADER_BUMP_DX
@ SHADER_BUMP_DY
vector< SocketType, std::allocator< SocketType > > inputs
Definition node_type.h:131
vector< SocketType, std::allocator< SocketType > > outputs
Definition node_type.h:132
const NodeType * type
Definition graph/node.h:179
void set_value(const SocketType &socket, const Node &other, const SocketType &other_socket)
ustring name
Definition graph/node.h:178
void copy_value(const SocketType &socket, const Node &other, const SocketType &other_socket)
bool equals_value(const Node &other, const SocketType &socket) const
Node(const NodeType *type, ustring name=ustring())
@ LINK_TEXTURE_UV
Definition node_type.h:73
@ LINK_TEXTURE_GENERATED
Definition node_type.h:71
@ LINK_INCOMING
Definition node_type.h:75
@ LINK_TEXTURE_INCOMING
Definition node_type.h:74
@ LINK_TEXTURE_NORMAL
Definition node_type.h:72
@ DEFAULT_LINK_MASK
Definition node_type.h:80
@ LINK_POSITION
Definition node_type.h:77