41e7e0205b00eae45e5209a8efa68cf6d2313c2c
[blender.git] / intern / cycles / render / graph.cpp
1 /*
2  * Copyright 2011-2016 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "render/attribute.h"
18 #include "render/graph.h"
19 #include "render/nodes.h"
20 #include "render/scene.h"
21 #include "render/shader.h"
22 #include "render/constant_fold.h"
23
24 #include "util/util_algorithm.h"
25 #include "util/util_debug.h"
26 #include "util/util_foreach.h"
27 #include "util/util_queue.h"
28 #include "util/util_logging.h"
29
30 CCL_NAMESPACE_BEGIN
31
32 namespace {
33
34 bool check_node_inputs_has_links(const ShaderNode *node)
35 {
36         foreach(const ShaderInput *in, node->inputs) {
37                 if(in->link) {
38                         return true;
39                 }
40         }
41         return false;
42 }
43
44 bool check_node_inputs_traversed(const ShaderNode *node,
45                                  const ShaderNodeSet& done)
46 {
47         foreach(const ShaderInput *in, node->inputs) {
48                 if(in->link) {
49                         if(done.find(in->link->parent) == done.end()) {
50                                 return false;
51                         }
52                 }
53         }
54         return true;
55 }
56
57 }  /* namespace */
58
59 /* Node */
60
61 ShaderNode::ShaderNode(const NodeType *type)
62 : Node(type)
63 {
64         name = type->name;
65         id = -1;
66         bump = SHADER_BUMP_NONE;
67         special_type = SHADER_SPECIAL_TYPE_NONE;
68
69         create_inputs_outputs(type);
70 }
71
72 ShaderNode::~ShaderNode()
73 {
74         foreach(ShaderInput *socket, inputs)
75                 delete socket;
76
77         foreach(ShaderOutput *socket, outputs)
78                 delete socket;
79 }
80
81 void ShaderNode::create_inputs_outputs(const NodeType *type)
82 {
83         foreach(const SocketType& socket, type->inputs) {
84                 if(socket.flags & SocketType::LINKABLE) {
85                         inputs.push_back(new ShaderInput(socket, this));
86                 }
87         }
88
89         foreach(const SocketType& socket, type->outputs) {
90                 outputs.push_back(new ShaderOutput(socket, this));
91         }
92 }
93
94 ShaderInput *ShaderNode::input(const char *name)
95 {
96         foreach(ShaderInput *socket, inputs) {
97                 if(socket->name() == name)
98                         return socket;
99         }
100
101         return NULL;
102 }
103
104 ShaderOutput *ShaderNode::output(const char *name)
105 {
106         foreach(ShaderOutput *socket, outputs)
107                 if(socket->name() == name)
108                         return socket;
109
110         return NULL;
111 }
112
113 ShaderInput *ShaderNode::input(ustring name)
114 {
115         foreach(ShaderInput *socket, inputs) {
116                 if(socket->name() == name)
117                         return socket;
118         }
119
120         return NULL;
121 }
122
123 ShaderOutput *ShaderNode::output(ustring name)
124 {
125         foreach(ShaderOutput *socket, outputs)
126                 if(socket->name() == name)
127                         return socket;
128
129         return NULL;
130 }
131
132 void ShaderNode::attributes(Shader *shader, AttributeRequestSet *attributes)
133 {
134         foreach(ShaderInput *input, inputs) {
135                 if(!input->link) {
136                         if(input->flags() & SocketType::LINK_TEXTURE_GENERATED) {
137                                 if(shader->has_surface)
138                                         attributes->add(ATTR_STD_GENERATED);
139                                 if(shader->has_volume)
140                                         attributes->add(ATTR_STD_GENERATED_TRANSFORM);
141                         }
142                         else if(input->flags() & SocketType::LINK_TEXTURE_UV) {
143                                 if(shader->has_surface)
144                                         attributes->add(ATTR_STD_UV);
145                         }
146                 }
147         }
148 }
149
150 bool ShaderNode::equals(const ShaderNode& other)
151 {
152         if(type != other.type || bump != other.bump) {
153                 return false;
154         }
155
156         assert(inputs.size() == other.inputs.size());
157
158         /* Compare unlinkable sockets */
159         foreach(const SocketType& socket, type->inputs) {
160                 if(!(socket.flags & SocketType::LINKABLE)) {
161                         if(!Node::equals_value(other, socket)) {
162                                 return false;
163                         }
164                 }
165         }
166
167         /* Compare linkable input sockets */
168         for(int i = 0; i < inputs.size(); ++i) {
169                 ShaderInput *input_a = inputs[i],
170                             *input_b = other.inputs[i];
171                 if(input_a->link == NULL && input_b->link == NULL) {
172                         /* Unconnected inputs are expected to have the same value. */
173                         if(!Node::equals_value(other, input_a->socket_type)) {
174                                 return false;
175                         }
176                 }
177                 else if(input_a->link != NULL && input_b->link != NULL) {
178                         /* Expect links are to come from the same exact socket. */
179                         if(input_a->link != input_b->link) {
180                                 return false;
181                         }
182                 }
183                 else {
184                         /* One socket has a link and another has not, inputs can't be
185                          * considered equal.
186                          */
187                         return false;
188                 }
189         }
190
191         return true;
192 }
193
194 /* Graph */
195
196 ShaderGraph::ShaderGraph()
197 {
198         finalized = false;
199         simplified = false;
200         num_node_ids = 0;
201         add(new OutputNode());
202 }
203
204 ShaderGraph::~ShaderGraph()
205 {
206         clear_nodes();
207 }
208
209 ShaderNode *ShaderGraph::add(ShaderNode *node)
210 {
211         assert(!finalized);
212         simplified = false;
213
214         node->id = num_node_ids++;
215         nodes.push_back(node);
216         return node;
217 }
218
219 OutputNode *ShaderGraph::output()
220 {
221         return (OutputNode*)nodes.front();
222 }
223
224 void ShaderGraph::connect(ShaderOutput *from, ShaderInput *to)
225 {
226         assert(!finalized);
227         assert(from && to);
228
229         if(to->link) {
230                 fprintf(stderr, "Cycles shader graph connect: input already connected.\n");
231                 return;
232         }
233
234         if(from->type() != to->type()) {
235                 /* for closures we can't do automatic conversion */
236                 if(from->type() == SocketType::CLOSURE || to->type() == SocketType::CLOSURE) {
237                         fprintf(stderr, "Cycles shader graph connect: can only connect closure to closure "
238                                 "(%s.%s to %s.%s).\n",
239                                 from->parent->name.c_str(), from->name().c_str(),
240                                 to->parent->name.c_str(), to->name().c_str());
241                         return;
242                 }
243
244                 /* add automatic conversion node in case of type mismatch */
245                 ShaderNode *convert = add(new ConvertNode(from->type(), to->type(), true));
246
247                 connect(from, convert->inputs[0]);
248                 connect(convert->outputs[0], to);
249         }
250         else {
251                 /* types match, just connect */
252                 to->link = from;
253                 from->links.push_back(to);
254         }
255 }
256
257 void ShaderGraph::disconnect(ShaderOutput *from)
258 {
259         assert(!finalized);
260         simplified = false;
261
262         foreach(ShaderInput *sock, from->links) {
263                 sock->link = NULL;
264         }
265
266         from->links.clear();
267 }
268
269 void ShaderGraph::disconnect(ShaderInput *to)
270 {
271         assert(!finalized);
272         assert(to->link);
273         simplified = false;
274
275         ShaderOutput *from = to->link;
276
277         to->link = NULL;
278         from->links.erase(remove(from->links.begin(), from->links.end(), to), from->links.end());
279 }
280
281 void ShaderGraph::relink(ShaderNode *node, ShaderOutput *from, ShaderOutput *to)
282 {
283         simplified = false;
284
285         /* Copy because disconnect modifies this list */
286         vector<ShaderInput*> outputs = from->links;
287
288         /* Bypass node by moving all links from "from" to "to" */
289         foreach(ShaderInput *sock, node->inputs) {
290                 if(sock->link)
291                         disconnect(sock);
292         }
293
294         foreach(ShaderInput *sock, outputs) {
295                 disconnect(sock);
296                 if(to)
297                         connect(to, sock);
298         }
299 }
300
301 void ShaderGraph::simplify(Scene *scene)
302 {
303         if(!simplified) {
304                 default_inputs(scene->shader_manager->use_osl());
305                 clean(scene);
306                 refine_bump_nodes();
307
308                 simplified = true;
309         }
310 }
311
312 void ShaderGraph::finalize(Scene *scene,
313                            bool do_bump,
314                            bool do_simplify,
315                            bool bump_in_object_space)
316 {
317         /* before compiling, the shader graph may undergo a number of modifications.
318          * currently we set default geometry shader inputs, and create automatic bump
319          * from displacement. a graph can be finalized only once, and should not be
320          * modified afterwards. */
321
322         if(!finalized) {
323                 simplify(scene);
324
325                 if(do_bump)
326                         bump_from_displacement(bump_in_object_space);
327
328                 ShaderInput *surface_in = output()->input("Surface");
329                 ShaderInput *volume_in = output()->input("Volume");
330
331                 /* todo: make this work when surface and volume closures are tangled up */
332
333                 if(surface_in->link)
334                         transform_multi_closure(surface_in->link->parent, NULL, false);
335                 if(volume_in->link)
336                         transform_multi_closure(volume_in->link->parent, NULL, true);
337
338                 finalized = true;
339         }
340         else if(do_simplify) {
341                 simplify_settings(scene);
342         }
343 }
344
345 void ShaderGraph::find_dependencies(ShaderNodeSet& dependencies, ShaderInput *input)
346 {
347         /* find all nodes that this input depends on directly and indirectly */
348         ShaderNode *node = (input->link)? input->link->parent: NULL;
349
350         if(node != NULL && dependencies.find(node) == dependencies.end()) {
351                 foreach(ShaderInput *in, node->inputs)
352                         find_dependencies(dependencies, in);
353
354                 dependencies.insert(node);
355         }
356 }
357
358 void ShaderGraph::clear_nodes()
359 {
360         foreach(ShaderNode *node, nodes) {
361                 delete node;
362         }
363         nodes.clear();
364 }
365
366 void ShaderGraph::copy_nodes(ShaderNodeSet& nodes, ShaderNodeMap& nnodemap)
367 {
368         /* copy a set of nodes, and the links between them. the assumption is
369          * made that all nodes that inputs are linked to are in the set too. */
370
371         /* copy nodes */
372         foreach(ShaderNode *node, nodes) {
373                 ShaderNode *nnode = node->clone();
374                 nnodemap[node] = nnode;
375
376                 /* create new inputs and outputs to recreate links and ensure
377                  * that we still point to valid SocketType if the NodeType
378                  * changed in cloning, as it does for OSL nodes */
379                 nnode->inputs.clear();
380                 nnode->outputs.clear();
381                 nnode->create_inputs_outputs(nnode->type);
382         }
383
384         /* recreate links */
385         foreach(ShaderNode *node, nodes) {
386                 foreach(ShaderInput *input, node->inputs) {
387                         if(input->link) {
388                                 /* find new input and output */
389                                 ShaderNode *nfrom = nnodemap[input->link->parent];
390                                 ShaderNode *nto = nnodemap[input->parent];
391                                 ShaderOutput *noutput = nfrom->output(input->link->name());
392                                 ShaderInput *ninput = nto->input(input->name());
393
394                                 /* connect */
395                                 connect(noutput, ninput);
396                         }
397                 }
398         }
399 }
400
401 /* Graph simplification */
402 /* ******************** */
403
404 /* Remove proxy nodes.
405  *
406  * These only exists temporarily when exporting groups, and we must remove them
407  * early so that node->attributes() and default links do not see them.
408  */
409 void ShaderGraph::remove_proxy_nodes()
410 {
411         vector<bool> removed(num_node_ids, false);
412         bool any_node_removed = false;
413
414         foreach(ShaderNode *node, nodes) {
415                 if(node->special_type == SHADER_SPECIAL_TYPE_PROXY) {
416                         ConvertNode *proxy = static_cast<ConvertNode*>(node);
417                         ShaderInput *input = proxy->inputs[0];
418                         ShaderOutput *output = proxy->outputs[0];
419
420                         /* bypass the proxy node */
421                         if(input->link) {
422                                 relink(proxy, output, input->link);
423                         }
424                         else {
425                                 /* Copy because disconnect modifies this list */
426                                 vector<ShaderInput*> links(output->links);
427
428                                 foreach(ShaderInput *to, links) {
429                                         /* remove any autoconvert nodes too if they lead to
430                                          * sockets with an automatically set default value */
431                                         ShaderNode *tonode = to->parent;
432
433                                         if(tonode->special_type == SHADER_SPECIAL_TYPE_AUTOCONVERT) {
434                                                 bool all_links_removed = true;
435                                                 vector<ShaderInput*> links = tonode->outputs[0]->links;
436
437                                                 foreach(ShaderInput *autoin, links) {
438                                                         if(autoin->flags() & SocketType::DEFAULT_LINK_MASK)
439                                                                 disconnect(autoin);
440                                                         else
441                                                                 all_links_removed = false;
442                                                 }
443
444                                                 if(all_links_removed)
445                                                         removed[tonode->id] = true;
446                                         }
447
448                                         disconnect(to);
449
450                                         /* transfer the default input value to the target socket */
451                                         tonode->copy_value(to->socket_type, *proxy, input->socket_type);
452                                 }
453                         }
454
455                         removed[proxy->id] = true;
456                         any_node_removed = true;
457                 }
458         }
459
460         /* remove nodes */
461         if(any_node_removed) {
462                 list<ShaderNode*> newnodes;
463
464                 foreach(ShaderNode *node, nodes) {
465                         if(!removed[node->id])
466                                 newnodes.push_back(node);
467                         else
468                                 delete node;
469                 }
470
471                 nodes = newnodes;
472         }
473 }
474
475 /* Constant folding.
476  *
477  * Try to constant fold some nodes, and pipe result directly to
478  * the input socket of connected nodes.
479  */
480 void ShaderGraph::constant_fold()
481 {
482         ShaderNodeSet done, scheduled;
483         queue<ShaderNode*> traverse_queue;
484
485         bool has_displacement = (output()->input("Displacement")->link != NULL);
486
487         /* Schedule nodes which doesn't have any dependencies. */
488         foreach(ShaderNode *node, nodes) {
489                 if(!check_node_inputs_has_links(node)) {
490                         traverse_queue.push(node);
491                         scheduled.insert(node);
492                 }
493         }
494
495         while(!traverse_queue.empty()) {
496                 ShaderNode *node = traverse_queue.front();
497                 traverse_queue.pop();
498                 done.insert(node);
499                 foreach(ShaderOutput *output, node->outputs) {
500                         if(output->links.size() == 0) {
501                                 continue;
502                         }
503                         /* Schedule node which was depending on the value,
504                          * when possible. Do it before disconnect.
505                          */
506                         foreach(ShaderInput *input, output->links) {
507                                 if(scheduled.find(input->parent) != scheduled.end()) {
508                                         /* Node might not be optimized yet but scheduled already
509                                          * by other dependencies. No need to re-schedule it.
510                                          */
511                                         continue;
512                                 }
513                                 /* Schedule node if its inputs are fully done. */
514                                 if(check_node_inputs_traversed(input->parent, done)) {
515                                         traverse_queue.push(input->parent);
516                                         scheduled.insert(input->parent);
517                                 }
518                         }
519                         /* Optimize current node. */
520                         ConstantFolder folder(this, node, output);
521                         node->constant_fold(folder);
522                 }
523         }
524
525         /* Folding might have removed all nodes connected to the displacement output
526          * even tho there is displacement to be applied, so add in a value node if
527          * that happens to ensure there is still a valid graph for displacement.
528          */
529         if(has_displacement && !output()->input("Displacement")->link) {
530                 ValueNode *value = (ValueNode*)add(new ValueNode());
531                 value->value = output()->displacement;
532
533                 connect(value->output("Value"), output()->input("Displacement"));
534         }
535 }
536
537 /* Simplification. */
538 void ShaderGraph::simplify_settings(Scene *scene)
539 {
540         foreach(ShaderNode *node, nodes) {
541                 node->simplify_settings(scene);
542         }
543 }
544
545 /* Deduplicate nodes with same settings. */
546 void ShaderGraph::deduplicate_nodes()
547 {
548         /* NOTES:
549          * - Deduplication happens for nodes which has same exact settings and same
550          *   exact input links configuration (either connected to same output or has
551          *   the same exact default value).
552          * - Deduplication happens in the bottom-top manner, so we know for fact that
553          *   all traversed nodes are either can not be deduplicated at all or were
554          *   already deduplicated.
555          */
556
557         ShaderNodeSet scheduled, done;
558         map<ustring, ShaderNodeSet> candidates;
559         queue<ShaderNode*> traverse_queue;
560         int num_deduplicated = 0;
561
562         /* Schedule nodes which doesn't have any dependencies. */
563         foreach(ShaderNode *node, nodes) {
564                 if(!check_node_inputs_has_links(node)) {
565                         traverse_queue.push(node);
566                         scheduled.insert(node);
567                 }
568         }
569
570         while(!traverse_queue.empty()) {
571                 ShaderNode *node = traverse_queue.front();
572                 traverse_queue.pop();
573                 done.insert(node);
574                 /* Schedule the nodes which were depending on the current node. */
575                 bool has_output_links = false;
576                 foreach(ShaderOutput *output, node->outputs) {
577                         foreach(ShaderInput *input, output->links) {
578                                 has_output_links = true;
579                                 if(scheduled.find(input->parent) != scheduled.end()) {
580                                         /* Node might not be optimized yet but scheduled already
581                                          * by other dependencies. No need to re-schedule it.
582                                          */
583                                         continue;
584                                 }
585                                 /* Schedule node if its inputs are fully done. */
586                                 if(check_node_inputs_traversed(input->parent, done)) {
587                                         traverse_queue.push(input->parent);
588                                         scheduled.insert(input->parent);
589                                 }
590                         }
591                 }
592                 /* Only need to care about nodes that are actually used */
593                 if(!has_output_links) {
594                         continue;
595                 }
596                 /* Try to merge this node with another one. */
597                 ShaderNode *merge_with = NULL;
598                 foreach(ShaderNode *other_node, candidates[node->type->name]) {
599                         if(node != other_node && node->equals(*other_node)) {
600                                 merge_with = other_node;
601                                 break;
602                         }
603                 }
604                 /* If found an equivalent, merge; otherwise keep node for later merges */
605                 if(merge_with != NULL) {
606                         for(int i = 0; i < node->outputs.size(); ++i) {
607                                 relink(node, node->outputs[i], merge_with->outputs[i]);
608                         }
609                         num_deduplicated++;
610                 }
611                 else {
612                         candidates[node->type->name].insert(node);
613                 }
614         }
615
616         if(num_deduplicated > 0) {
617                 VLOG(1) << "Deduplicated " << num_deduplicated << " nodes.";
618         }
619 }
620
621 /* Check whether volume output has meaningful nodes, otherwise
622  * disconnect the output.
623  */
624 void ShaderGraph::verify_volume_output()
625 {
626         /* Check whether we can optimize the whole volume graph out. */
627         ShaderInput *volume_in = output()->input("Volume");
628         if(volume_in->link == NULL) {
629                 return;
630         }
631         bool has_valid_volume = false;
632         ShaderNodeSet scheduled;
633         queue<ShaderNode*> traverse_queue;
634         /* Schedule volume output. */
635         traverse_queue.push(volume_in->link->parent);
636         scheduled.insert(volume_in->link->parent);
637         /* Traverse down the tree. */
638         while(!traverse_queue.empty()) {
639                 ShaderNode *node = traverse_queue.front();
640                 traverse_queue.pop();
641                 /* Node is fully valid for volume, can't optimize anything out. */
642                 if(node->has_volume_support()) {
643                         has_valid_volume = true;
644                         break;
645                 }
646                 foreach(ShaderInput *input, node->inputs) {
647                         if(input->link == NULL) {
648                                 continue;
649                         }
650                         if(scheduled.find(input->link->parent) != scheduled.end()) {
651                                 continue;
652                         }
653                         traverse_queue.push(input->link->parent);
654                         scheduled.insert(input->link->parent);
655                 }
656         }
657         if(!has_valid_volume) {
658                 VLOG(1) << "Disconnect meaningless volume output.";
659                 disconnect(volume_in->link);
660         }
661 }
662
663 void ShaderGraph::break_cycles(ShaderNode *node, vector<bool>& visited, vector<bool>& on_stack)
664 {
665         visited[node->id] = true;
666         on_stack[node->id] = true;
667
668         foreach(ShaderInput *input, node->inputs) {
669                 if(input->link) {
670                         ShaderNode *depnode = input->link->parent;
671
672                         if(on_stack[depnode->id]) {
673                                 /* break cycle */
674                                 disconnect(input);
675                                 fprintf(stderr, "Cycles shader graph: detected cycle in graph, connection removed.\n");
676                         }
677                         else if(!visited[depnode->id]) {
678                                 /* visit dependencies */
679                                 break_cycles(depnode, visited, on_stack);
680                         }
681                 }
682         }
683
684         on_stack[node->id] = false;
685 }
686
687 void ShaderGraph::clean(Scene *scene)
688 {
689         /* Graph simplification */
690
691         /* NOTE: Remove proxy nodes was already done. */
692         constant_fold();
693         simplify_settings(scene);
694         deduplicate_nodes();
695         verify_volume_output();
696
697         /* we do two things here: find cycles and break them, and remove unused
698          * nodes that don't feed into the output. how cycles are broken is
699          * undefined, they are invalid input, the important thing is to not crash */
700
701         vector<bool> visited(num_node_ids, false);
702         vector<bool> on_stack(num_node_ids, false);
703         
704         /* break cycles */
705         break_cycles(output(), visited, on_stack);
706
707         /* disconnect unused nodes */
708         foreach(ShaderNode *node, nodes) {
709                 if(!visited[node->id]) {
710                         foreach(ShaderInput *to, node->inputs) {
711                                 ShaderOutput *from = to->link;
712
713                                 if(from) {
714                                         to->link = NULL;
715                                         from->links.erase(remove(from->links.begin(), from->links.end(), to), from->links.end());
716                                 }
717                         }
718                 }
719         }
720
721         /* remove unused nodes */
722         list<ShaderNode*> newnodes;
723
724         foreach(ShaderNode *node, nodes) {
725                 if(visited[node->id])
726                         newnodes.push_back(node);
727                 else
728                         delete node;
729         }
730
731         nodes = newnodes;
732 }
733
734 void ShaderGraph::default_inputs(bool do_osl)
735 {
736         /* nodes can specify default texture coordinates, for now we give
737          * everything the position by default, except for the sky texture */
738
739         ShaderNode *geom = NULL;
740         ShaderNode *texco = NULL;
741
742         foreach(ShaderNode *node, nodes) {
743                 foreach(ShaderInput *input, node->inputs) {
744                         if(!input->link && (!(input->flags() & SocketType::OSL_INTERNAL) || do_osl)) {
745                                 if(input->flags() & SocketType::LINK_TEXTURE_GENERATED) {
746                                         if(!texco)
747                                                 texco = new TextureCoordinateNode();
748
749                                         connect(texco->output("Generated"), input);
750                                 }
751                                 else if(input->flags() & SocketType::LINK_TEXTURE_UV) {
752                                         if(!texco)
753                                                 texco = new TextureCoordinateNode();
754
755                                         connect(texco->output("UV"), input);
756                                 }
757                                 else if(input->flags() & SocketType::LINK_INCOMING) {
758                                         if(!geom)
759                                                 geom = new GeometryNode();
760
761                                         connect(geom->output("Incoming"), input);
762                                 }
763                                 else if(input->flags() & SocketType::LINK_NORMAL) {
764                                         if(!geom)
765                                                 geom = new GeometryNode();
766
767                                         connect(geom->output("Normal"), input);
768                                 }
769                                 else if(input->flags() & SocketType::LINK_POSITION) {
770                                         if(!geom)
771                                                 geom = new GeometryNode();
772
773                                         connect(geom->output("Position"), input);
774                                 }
775                                 else if(input->flags() & SocketType::LINK_TANGENT) {
776                                         if(!geom)
777                                                 geom = new GeometryNode();
778
779                                         connect(geom->output("Tangent"), input);
780                                 }
781                         }
782                 }
783         }
784
785         if(geom)
786                 add(geom);
787         if(texco)
788                 add(texco);
789 }
790
791 void ShaderGraph::refine_bump_nodes()
792 {
793         /* we transverse the node graph looking for bump nodes, when we find them,
794          * like in bump_from_displacement(), we copy the sub-graph defined from "bump"
795          * input to the inputs "center","dx" and "dy" What is in "bump" input is moved
796          * to "center" input. */
797
798         foreach(ShaderNode *node, nodes) {
799                 if(node->special_type == SHADER_SPECIAL_TYPE_BUMP && node->input("Height")->link) {
800                         ShaderInput *bump_input = node->input("Height");
801                         ShaderNodeSet nodes_bump;
802
803                         /* make 2 extra copies of the subgraph defined in Bump input */
804                         ShaderNodeMap nodes_dx;
805                         ShaderNodeMap nodes_dy;
806
807                         /* find dependencies for the given input */
808                         find_dependencies(nodes_bump, bump_input);
809
810                         copy_nodes(nodes_bump, nodes_dx);
811                         copy_nodes(nodes_bump, nodes_dy);
812         
813                         /* mark nodes to indicate they are use for bump computation, so
814                            that any texture coordinates are shifted by dx/dy when sampling */
815                         foreach(ShaderNode *node, nodes_bump)
816                                 node->bump = SHADER_BUMP_CENTER;
817                         foreach(NodePair& pair, nodes_dx)
818                                 pair.second->bump = SHADER_BUMP_DX;
819                         foreach(NodePair& pair, nodes_dy)
820                                 pair.second->bump = SHADER_BUMP_DY;
821
822                         ShaderOutput *out = bump_input->link;
823                         ShaderOutput *out_dx = nodes_dx[out->parent]->output(out->name());
824                         ShaderOutput *out_dy = nodes_dy[out->parent]->output(out->name());
825
826                         connect(out_dx, node->input("SampleX"));
827                         connect(out_dy, node->input("SampleY"));
828                         
829                         /* add generated nodes */
830                         foreach(NodePair& pair, nodes_dx)
831                                 add(pair.second);
832                         foreach(NodePair& pair, nodes_dy)
833                                 add(pair.second);
834                         
835                         /* connect what is connected is bump to samplecenter input*/
836                         connect(out , node->input("SampleCenter"));
837
838                         /* bump input is just for connectivity purpose for the graph input,
839                          * we re-connected this input to samplecenter, so lets disconnect it
840                          * from bump input */
841                         disconnect(bump_input);
842                 }
843         }
844 }
845
846 void ShaderGraph::bump_from_displacement(bool use_object_space)
847 {
848         /* generate bump mapping automatically from displacement. bump mapping is
849          * done using a 3-tap filter, computing the displacement at the center,
850          * and two other positions shifted by ray differentials.
851          *
852          * since the input to displacement is a node graph, we need to ensure that
853          * all texture coordinates use are shift by the ray differentials. for this
854          * reason we make 3 copies of the node subgraph defining the displacement,
855          * with each different geometry and texture coordinate nodes that generate
856          * different shifted coordinates.
857          *
858          * these 3 displacement values are then fed into the bump node, which will
859          * output the perturbed normal. */
860
861         ShaderInput *displacement_in = output()->input("Displacement");
862
863         if(!displacement_in->link)
864                 return;
865         
866         /* find dependencies for the given input */
867         ShaderNodeSet nodes_displace;
868         find_dependencies(nodes_displace, displacement_in);
869
870         /* copy nodes for 3 bump samples */
871         ShaderNodeMap nodes_center;
872         ShaderNodeMap nodes_dx;
873         ShaderNodeMap nodes_dy;
874
875         copy_nodes(nodes_displace, nodes_center);
876         copy_nodes(nodes_displace, nodes_dx);
877         copy_nodes(nodes_displace, nodes_dy);
878
879         /* mark nodes to indicate they are use for bump computation, so
880          * that any texture coordinates are shifted by dx/dy when sampling */
881         foreach(NodePair& pair, nodes_center)
882                 pair.second->bump = SHADER_BUMP_CENTER;
883         foreach(NodePair& pair, nodes_dx)
884                 pair.second->bump = SHADER_BUMP_DX;
885         foreach(NodePair& pair, nodes_dy)
886                 pair.second->bump = SHADER_BUMP_DY;
887
888         /* add set normal node and connect the bump normal ouput to the set normal
889          * output, so it can finally set the shader normal, note we are only doing
890          * this for bump from displacement, this will be the only bump allowed to
891          * overwrite the shader normal */
892         ShaderNode *set_normal = add(new SetNormalNode());
893         
894         /* add bump node and connect copied graphs to it */
895         BumpNode *bump = (BumpNode*)add(new BumpNode());
896         bump->use_object_space = use_object_space;
897
898         ShaderOutput *out = displacement_in->link;
899         ShaderOutput *out_center = nodes_center[out->parent]->output(out->name());
900         ShaderOutput *out_dx = nodes_dx[out->parent]->output(out->name());
901         ShaderOutput *out_dy = nodes_dy[out->parent]->output(out->name());
902
903         connect(out_center, bump->input("SampleCenter"));
904         connect(out_dx, bump->input("SampleX"));
905         connect(out_dy, bump->input("SampleY"));
906         
907         /* connect the bump out to the set normal in: */
908         connect(bump->output("Normal"), set_normal->input("Direction"));
909
910         /* connect to output node */
911         connect(set_normal->output("Normal"), output()->input("Normal"));
912
913         /* finally, add the copied nodes to the graph. we can't do this earlier
914          * because we would create dependency cycles in the above loop */
915         foreach(NodePair& pair, nodes_center)
916                 add(pair.second);
917         foreach(NodePair& pair, nodes_dx)
918                 add(pair.second);
919         foreach(NodePair& pair, nodes_dy)
920                 add(pair.second);
921 }
922
923 void ShaderGraph::transform_multi_closure(ShaderNode *node, ShaderOutput *weight_out, bool volume)
924 {
925         /* for SVM in multi closure mode, this transforms the shader mix/add part of
926          * the graph into nodes that feed weights into closure nodes. this is too
927          * avoid building a closure tree and then flattening it, and instead write it
928          * directly to an array */
929         
930         if(node->special_type == SHADER_SPECIAL_TYPE_COMBINE_CLOSURE) {
931                 ShaderInput *fin = node->input("Fac");
932                 ShaderInput *cl1in = node->input("Closure1");
933                 ShaderInput *cl2in = node->input("Closure2");
934                 ShaderOutput *weight1_out, *weight2_out;
935
936                 if(fin) {
937                         /* mix closure: add node to mix closure weights */
938                         MixClosureWeightNode *mix_node = new MixClosureWeightNode();
939                         add(mix_node);
940                         ShaderInput *fac_in = mix_node->input("Fac"); 
941                         ShaderInput *weight_in = mix_node->input("Weight"); 
942
943                         if(fin->link)
944                                 connect(fin->link, fac_in);
945                         else
946                                 mix_node->fac = node->get_float(fin->socket_type);
947
948                         if(weight_out)
949                                 connect(weight_out, weight_in);
950
951                         weight1_out = mix_node->output("Weight1");
952                         weight2_out = mix_node->output("Weight2");
953                 }
954                 else {
955                         /* add closure: just pass on any weights */
956                         weight1_out = weight_out;
957                         weight2_out = weight_out;
958                 }
959
960                 if(cl1in->link)
961                         transform_multi_closure(cl1in->link->parent, weight1_out, volume);
962                 if(cl2in->link)
963                         transform_multi_closure(cl2in->link->parent, weight2_out, volume);
964         }
965         else {
966                 ShaderInput *weight_in = node->input((volume)? "VolumeMixWeight": "SurfaceMixWeight");
967
968                 /* not a closure node? */
969                 if(!weight_in)
970                         return;
971
972                 /* already has a weight connected to it? add weights */
973                 float weight_value = node->get_float(weight_in->socket_type);
974                 if(weight_in->link || weight_value != 0.0f) {
975                         MathNode *math_node = new MathNode();
976                         add(math_node);
977
978                         if(weight_in->link)
979                                 connect(weight_in->link, math_node->input("Value1"));
980                         else
981                                 math_node->value1 = weight_value;
982
983                         if(weight_out)
984                                 connect(weight_out, math_node->input("Value2"));
985                         else
986                                 math_node->value2 = 1.0f;
987
988                         weight_out = math_node->output("Value");
989                         if(weight_in->link)
990                                 disconnect(weight_in);
991                 }
992
993                 /* connected to closure mix weight */
994                 if(weight_out)
995                         connect(weight_out, weight_in);
996                 else
997                         node->set(weight_in->socket_type, weight_value + 1.0f);
998         }
999 }
1000
1001 int ShaderGraph::get_num_closures()
1002 {
1003         int num_closures = 0;
1004         foreach(ShaderNode *node, nodes) {
1005                 ClosureType closure_type = node->get_closure_type();
1006                 if(closure_type == CLOSURE_NONE_ID) {
1007                         continue;
1008                 }
1009                 else if(CLOSURE_IS_BSSRDF(closure_type)) {
1010                         num_closures += 3;
1011                 }
1012                 else if(CLOSURE_IS_GLASS(closure_type)) {
1013                         num_closures += 2;
1014                 }
1015                 else if(CLOSURE_IS_BSDF_MULTISCATTER(closure_type)) {
1016                         num_closures += 2;
1017                 }
1018                 else if(CLOSURE_IS_PRINCIPLED(closure_type)) {
1019                         num_closures += 8;
1020                 }
1021                 else {
1022                         ++num_closures;
1023                 }
1024         }
1025         return num_closures;
1026 }
1027
1028 void ShaderGraph::dump_graph(const char *filename)
1029 {
1030         FILE *fd = fopen(filename, "w");
1031
1032         if(fd == NULL) {
1033                 printf("Error opening file for dumping the graph: %s\n", filename);
1034                 return;
1035         }
1036
1037         fprintf(fd, "digraph shader_graph {\n");
1038         fprintf(fd, "ranksep=1.5\n");
1039         fprintf(fd, "rankdir=LR\n");
1040         fprintf(fd, "splines=false\n");
1041
1042         foreach(ShaderNode *node, nodes) {
1043                 fprintf(fd, "// NODE: %p\n", node);
1044                 fprintf(fd, "\"%p\" [shape=record,label=\"{", node);
1045                 if(node->inputs.size()) {
1046                         fprintf(fd, "{");
1047                         foreach(ShaderInput *socket, node->inputs) {
1048                                 if(socket != node->inputs[0]) {
1049                                         fprintf(fd, "|");
1050                                 }
1051                                 fprintf(fd, "<IN_%p>%s", socket, socket->name().c_str());
1052                         }
1053                         fprintf(fd, "}|");
1054                 }
1055                 fprintf(fd, "%s", node->name.c_str());
1056                 if(node->bump == SHADER_BUMP_CENTER) {
1057                         fprintf(fd, " (bump:center)");
1058                 }
1059                 else if(node->bump == SHADER_BUMP_DX) {
1060                         fprintf(fd, " (bump:dx)");
1061                 }
1062                 else if(node->bump == SHADER_BUMP_DY) {
1063                         fprintf(fd, " (bump:dy)");
1064                 }
1065                 if(node->outputs.size()) {
1066                         fprintf(fd, "|{");
1067                         foreach(ShaderOutput *socket, node->outputs) {
1068                                 if(socket != node->outputs[0]) {
1069                                         fprintf(fd, "|");
1070                                 }
1071                                 fprintf(fd, "<OUT_%p>%s", socket, socket->name().c_str());
1072                         }
1073                         fprintf(fd, "}");
1074                 }
1075                 fprintf(fd, "}\"]");
1076         }
1077
1078         foreach(ShaderNode *node, nodes) {
1079                 foreach(ShaderOutput *output, node->outputs) {
1080                         foreach(ShaderInput *input, output->links) {
1081                                 fprintf(fd,
1082                                         "// CONNECTION: OUT_%p->IN_%p (%s:%s)\n",
1083                                         output,
1084                                         input,
1085                                         output->name().c_str(), input->name().c_str());
1086                                 fprintf(fd,
1087                                         "\"%p\":\"OUT_%p\":e -> \"%p\":\"IN_%p\":w [label=\"\"]\n",
1088                                         output->parent,
1089                                         output,
1090                                         input->parent,
1091                                         input);
1092                         }
1093                 }
1094         }
1095
1096         fprintf(fd, "}\n");
1097         fclose(fd);
1098 }
1099
1100 CCL_NAMESPACE_END
1101