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