1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2007 Blender Foundation.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup nodes
22  */
23 
24 #include <string.h>
25 
26 #include "DNA_light_types.h"
27 #include "DNA_linestyle_types.h"
28 #include "DNA_material_types.h"
29 #include "DNA_node_types.h"
30 #include "DNA_scene_types.h"
31 #include "DNA_space_types.h"
32 #include "DNA_workspace_types.h"
33 #include "DNA_world_types.h"
34 
35 #include "BLI_alloca.h"
36 #include "BLI_linklist.h"
37 #include "BLI_listbase.h"
38 #include "BLI_threads.h"
39 #include "BLI_utildefines.h"
40 
41 #include "BLT_translation.h"
42 
43 #include "BKE_context.h"
44 #include "BKE_lib_id.h"
45 #include "BKE_linestyle.h"
46 #include "BKE_node.h"
47 #include "BKE_scene.h"
48 
49 #include "RNA_access.h"
50 
51 #include "GPU_material.h"
52 
53 #include "RE_shader_ext.h"
54 
55 #include "NOD_common.h"
56 
57 #include "node_common.h"
58 #include "node_exec.h"
59 #include "node_shader_util.h"
60 #include "node_util.h"
61 
62 typedef struct nTreeTags {
63   float ssr_id, sss_id;
64 } nTreeTags;
65 
66 static void ntree_shader_tag_nodes(bNodeTree *ntree, bNode *output_node, nTreeTags *tags);
67 
shader_tree_poll(const bContext * C,bNodeTreeType * UNUSED (treetype))68 static bool shader_tree_poll(const bContext *C, bNodeTreeType *UNUSED(treetype))
69 {
70   Scene *scene = CTX_data_scene(C);
71   const char *engine_id = scene->r.engine;
72 
73   /* Allow empty engine string too,
74    * this is from older versions that didn't have registerable engines yet. */
75   return (engine_id[0] == '\0' || STREQ(engine_id, RE_engine_id_CYCLES) ||
76           !BKE_scene_use_shading_nodes_custom(scene));
77 }
78 
shader_get_from_context(const bContext * C,bNodeTreeType * UNUSED (treetype),bNodeTree ** r_ntree,ID ** r_id,ID ** r_from)79 static void shader_get_from_context(const bContext *C,
80                                     bNodeTreeType *UNUSED(treetype),
81                                     bNodeTree **r_ntree,
82                                     ID **r_id,
83                                     ID **r_from)
84 {
85   SpaceNode *snode = CTX_wm_space_node(C);
86   Scene *scene = CTX_data_scene(C);
87   ViewLayer *view_layer = CTX_data_view_layer(C);
88   Object *ob = OBACT(view_layer);
89 
90   if (snode->shaderfrom == SNODE_SHADER_OBJECT) {
91     if (ob) {
92       *r_from = &ob->id;
93       if (ob->type == OB_LAMP) {
94         *r_id = ob->data;
95         *r_ntree = ((Light *)ob->data)->nodetree;
96       }
97       else {
98         Material *ma = BKE_object_material_get(ob, ob->actcol);
99         if (ma) {
100           *r_id = &ma->id;
101           *r_ntree = ma->nodetree;
102         }
103       }
104     }
105   }
106 #ifdef WITH_FREESTYLE
107   else if (snode->shaderfrom == SNODE_SHADER_LINESTYLE) {
108     FreestyleLineStyle *linestyle = BKE_linestyle_active_from_view_layer(view_layer);
109     if (linestyle) {
110       *r_from = NULL;
111       *r_id = &linestyle->id;
112       *r_ntree = linestyle->nodetree;
113     }
114   }
115 #endif
116   else { /* SNODE_SHADER_WORLD */
117     if (scene->world) {
118       *r_from = NULL;
119       *r_id = &scene->world->id;
120       *r_ntree = scene->world->nodetree;
121     }
122   }
123 }
124 
foreach_nodeclass(Scene * UNUSED (scene),void * calldata,bNodeClassCallback func)125 static void foreach_nodeclass(Scene *UNUSED(scene), void *calldata, bNodeClassCallback func)
126 {
127   func(calldata, NODE_CLASS_INPUT, N_("Input"));
128   func(calldata, NODE_CLASS_OUTPUT, N_("Output"));
129   func(calldata, NODE_CLASS_SHADER, N_("Shader"));
130   func(calldata, NODE_CLASS_TEXTURE, N_("Texture"));
131   func(calldata, NODE_CLASS_OP_COLOR, N_("Color"));
132   func(calldata, NODE_CLASS_OP_VECTOR, N_("Vector"));
133   func(calldata, NODE_CLASS_CONVERTOR, N_("Convertor"));
134   func(calldata, NODE_CLASS_SCRIPT, N_("Script"));
135   func(calldata, NODE_CLASS_GROUP, N_("Group"));
136   func(calldata, NODE_CLASS_INTERFACE, N_("Interface"));
137   func(calldata, NODE_CLASS_LAYOUT, N_("Layout"));
138 }
139 
localize(bNodeTree * localtree,bNodeTree * UNUSED (ntree))140 static void localize(bNodeTree *localtree, bNodeTree *UNUSED(ntree))
141 {
142   bNode *node, *node_next;
143 
144   /* replace muted nodes and reroute nodes by internal links */
145   for (node = localtree->nodes.first; node; node = node_next) {
146     node_next = node->next;
147 
148     if (node->flag & NODE_MUTED || node->type == NODE_REROUTE) {
149       nodeInternalRelink(localtree, node);
150       ntreeFreeLocalNode(localtree, node);
151     }
152   }
153 }
154 
local_sync(bNodeTree * localtree,bNodeTree * ntree)155 static void local_sync(bNodeTree *localtree, bNodeTree *ntree)
156 {
157   BKE_node_preview_sync_tree(ntree, localtree);
158 }
159 
local_merge(Main * UNUSED (bmain),bNodeTree * localtree,bNodeTree * ntree)160 static void local_merge(Main *UNUSED(bmain), bNodeTree *localtree, bNodeTree *ntree)
161 {
162   BKE_node_preview_merge_tree(ntree, localtree, true);
163 }
164 
update(bNodeTree * ntree)165 static void update(bNodeTree *ntree)
166 {
167   ntreeSetOutput(ntree);
168 
169   ntree_update_reroute_nodes(ntree);
170 
171   if (ntree->update & NTREE_UPDATE_NODES) {
172     /* clean up preview cache, in case nodes have been removed */
173     BKE_node_preview_remove_unused(ntree);
174   }
175 }
176 
shader_validate_link(bNodeTree * UNUSED (ntree),bNodeLink * link)177 static bool shader_validate_link(bNodeTree *UNUSED(ntree), bNodeLink *link)
178 {
179   /* Can't connect shader into other socket types, other way around is fine
180    * since it will be interpreted as emission. */
181   if (link->fromsock->type == SOCK_SHADER) {
182     return (link->tosock->type == SOCK_SHADER);
183   }
184   return true;
185 }
186 
187 bNodeTreeType *ntreeType_Shader;
188 
register_node_tree_type_sh(void)189 void register_node_tree_type_sh(void)
190 {
191   bNodeTreeType *tt = ntreeType_Shader = MEM_callocN(sizeof(bNodeTreeType),
192                                                      "shader node tree type");
193 
194   tt->type = NTREE_SHADER;
195   strcpy(tt->idname, "ShaderNodeTree");
196   strcpy(tt->ui_name, N_("Shader Editor"));
197   tt->ui_icon = 0; /* defined in drawnode.c */
198   strcpy(tt->ui_description, N_("Shader nodes"));
199 
200   tt->foreach_nodeclass = foreach_nodeclass;
201   tt->localize = localize;
202   tt->local_sync = local_sync;
203   tt->local_merge = local_merge;
204   tt->update = update;
205   tt->poll = shader_tree_poll;
206   tt->get_from_context = shader_get_from_context;
207   tt->validate_link = shader_validate_link;
208 
209   tt->rna_ext.srna = &RNA_ShaderNodeTree;
210 
211   ntreeTypeAdd(tt);
212 }
213 
214 /* GPU material from shader nodes */
215 
216 /* Find an output node of the shader tree.
217  *
218  * NOTE: it will only return output which is NOT in the group, which isn't how
219  * render engines works but it's how the GPU shader compilation works. This we
220  * can change in the future and make it a generic function, but for now it stays
221  * private here.
222  */
ntreeShaderOutputNode(bNodeTree * ntree,int target)223 bNode *ntreeShaderOutputNode(bNodeTree *ntree, int target)
224 {
225   /* Make sure we only have single node tagged as output. */
226   ntreeSetOutput(ntree);
227 
228   /* Find output node that matches type and target. If there are
229    * multiple, we prefer exact target match and active nodes. */
230   bNode *output_node = NULL;
231 
232   LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
233     if (!ELEM(node->type, SH_NODE_OUTPUT_MATERIAL, SH_NODE_OUTPUT_WORLD, SH_NODE_OUTPUT_LIGHT)) {
234       continue;
235     }
236 
237     if (node->custom1 == SHD_OUTPUT_ALL) {
238       if (output_node == NULL) {
239         output_node = node;
240       }
241       else if (output_node->custom1 == SHD_OUTPUT_ALL) {
242         if ((node->flag & NODE_DO_OUTPUT) && !(output_node->flag & NODE_DO_OUTPUT)) {
243           output_node = node;
244         }
245       }
246     }
247     else if (node->custom1 == target) {
248       if (output_node == NULL) {
249         output_node = node;
250       }
251       else if (output_node->custom1 == SHD_OUTPUT_ALL) {
252         output_node = node;
253       }
254       else if ((node->flag & NODE_DO_OUTPUT) && !(output_node->flag & NODE_DO_OUTPUT)) {
255         output_node = node;
256       }
257     }
258   }
259 
260   return output_node;
261 }
262 
263 /* Find socket with a specified identifier. */
ntree_shader_node_find_socket(ListBase * sockets,const char * identifier)264 static bNodeSocket *ntree_shader_node_find_socket(ListBase *sockets, const char *identifier)
265 {
266   for (bNodeSocket *sock = sockets->first; sock != NULL; sock = sock->next) {
267     if (STREQ(sock->identifier, identifier)) {
268       return sock;
269     }
270   }
271   return NULL;
272 }
273 
274 /* Find input socket with a specified identifier. */
ntree_shader_node_find_input(bNode * node,const char * identifier)275 static bNodeSocket *ntree_shader_node_find_input(bNode *node, const char *identifier)
276 {
277   return ntree_shader_node_find_socket(&node->inputs, identifier);
278 }
279 
280 /* Find output socket with a specified identifier. */
ntree_shader_node_find_output(bNode * node,const char * identifier)281 static bNodeSocket *ntree_shader_node_find_output(bNode *node, const char *identifier)
282 {
283   return ntree_shader_node_find_socket(&node->outputs, identifier);
284 }
285 
286 /* Return true on success. */
ntree_shader_expand_socket_default(bNodeTree * localtree,bNode * node,bNodeSocket * socket)287 static bool ntree_shader_expand_socket_default(bNodeTree *localtree,
288                                                bNode *node,
289                                                bNodeSocket *socket)
290 {
291   bNode *value_node;
292   bNodeSocket *value_socket;
293   bNodeSocketValueVector *src_vector;
294   bNodeSocketValueRGBA *src_rgba, *dst_rgba;
295   bNodeSocketValueFloat *src_float, *dst_float;
296   bNodeSocketValueInt *src_int;
297 
298   switch (socket->type) {
299     case SOCK_VECTOR:
300       value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_RGB);
301       value_socket = ntree_shader_node_find_output(value_node, "Color");
302       BLI_assert(value_socket != NULL);
303       src_vector = socket->default_value;
304       dst_rgba = value_socket->default_value;
305       copy_v3_v3(dst_rgba->value, src_vector->value);
306       dst_rgba->value[3] = 1.0f; /* should never be read */
307       break;
308     case SOCK_RGBA:
309       value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_RGB);
310       value_socket = ntree_shader_node_find_output(value_node, "Color");
311       BLI_assert(value_socket != NULL);
312       src_rgba = socket->default_value;
313       dst_rgba = value_socket->default_value;
314       copy_v4_v4(dst_rgba->value, src_rgba->value);
315       break;
316     case SOCK_INT:
317       /* HACK: Support as float. */
318       value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_VALUE);
319       value_socket = ntree_shader_node_find_output(value_node, "Value");
320       BLI_assert(value_socket != NULL);
321       src_int = socket->default_value;
322       dst_float = value_socket->default_value;
323       dst_float->value = (float)(src_int->value);
324       break;
325     case SOCK_FLOAT:
326       value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_VALUE);
327       value_socket = ntree_shader_node_find_output(value_node, "Value");
328       BLI_assert(value_socket != NULL);
329       src_float = socket->default_value;
330       dst_float = value_socket->default_value;
331       dst_float->value = src_float->value;
332       break;
333     default:
334       return false;
335   }
336   nodeAddLink(localtree, value_node, value_socket, node, socket);
337   return true;
338 }
339 
ntree_shader_unlink_hidden_value_sockets(bNode * group_node,bNodeSocket * isock)340 static void ntree_shader_unlink_hidden_value_sockets(bNode *group_node, bNodeSocket *isock)
341 {
342   bNodeTree *group_ntree = (bNodeTree *)group_node->id;
343   bNode *node;
344   bool removed_link = false;
345 
346   for (node = group_ntree->nodes.first; node; node = node->next) {
347     const bool is_group = ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP) && (node->id != NULL);
348 
349     LISTBASE_FOREACH (bNodeSocket *, sock, &node->inputs) {
350       if (!is_group && (sock->flag & SOCK_HIDE_VALUE) == 0) {
351         continue;
352       }
353       /* If socket is linked to a group input node and sockets id match. */
354       if (sock && sock->link && sock->link->fromnode->type == NODE_GROUP_INPUT) {
355         if (STREQ(isock->identifier, sock->link->fromsock->identifier)) {
356           if (is_group) {
357             /* Recursively unlink sockets within the nested group. */
358             ntree_shader_unlink_hidden_value_sockets(node, sock);
359           }
360           else {
361             nodeRemLink(group_ntree, sock->link);
362             removed_link = true;
363           }
364         }
365       }
366     }
367   }
368 
369   if (removed_link) {
370     ntreeUpdateTree(G.main, group_ntree);
371   }
372 }
373 
374 /* Node groups once expanded looses their input sockets values.
375  * To fix this, link value/rgba nodes into the sockets and copy the group sockets values. */
ntree_shader_groups_expand_inputs(bNodeTree * localtree)376 static void ntree_shader_groups_expand_inputs(bNodeTree *localtree)
377 {
378   bool link_added = false;
379 
380   LISTBASE_FOREACH (bNode *, node, &localtree->nodes) {
381     const bool is_group = ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP) && (node->id != NULL);
382     const bool is_group_output = node->type == NODE_GROUP_OUTPUT && (node->flag & NODE_DO_OUTPUT);
383 
384     if (is_group) {
385       /* Do it recursively. */
386       ntree_shader_groups_expand_inputs((bNodeTree *)node->id);
387     }
388 
389     if (is_group || is_group_output) {
390       LISTBASE_FOREACH (bNodeSocket *, socket, &node->inputs) {
391         if (socket->link != NULL) {
392           bNodeLink *link = socket->link;
393           /* Fix the case where the socket is actually converting the data. (see T71374)
394            * We only do the case of lossy conversion to float.*/
395           if ((socket->type == SOCK_FLOAT) && (link->fromsock->type != link->tosock->type)) {
396             if (link->fromsock->type == SOCK_RGBA) {
397               bNode *tmp = nodeAddStaticNode(NULL, localtree, SH_NODE_RGBTOBW);
398               nodeAddLink(localtree, link->fromnode, link->fromsock, tmp, tmp->inputs.first);
399               nodeAddLink(localtree, tmp, tmp->outputs.first, node, socket);
400             }
401             else if (link->fromsock->type == SOCK_VECTOR) {
402               bNode *tmp = nodeAddStaticNode(NULL, localtree, SH_NODE_VECTOR_MATH);
403               tmp->custom1 = NODE_VECTOR_MATH_DOT_PRODUCT;
404               bNodeSocket *dot_input1 = tmp->inputs.first;
405               bNodeSocket *dot_input2 = dot_input1->next;
406               bNodeSocketValueVector *input2_socket_value = dot_input2->default_value;
407               copy_v3_fl(input2_socket_value->value, 1.0f / 3.0f);
408               nodeAddLink(localtree, link->fromnode, link->fromsock, tmp, dot_input1);
409               nodeAddLink(localtree, tmp, tmp->outputs.last, node, socket);
410             }
411           }
412           continue;
413         }
414 
415         if (is_group) {
416           /* Detect the case where an input is plugged into a hidden value socket.
417            * In this case we should just remove the link to trigger the socket default override. */
418           ntree_shader_unlink_hidden_value_sockets(node, socket);
419         }
420 
421         if (ntree_shader_expand_socket_default(localtree, node, socket)) {
422           link_added = true;
423         }
424       }
425     }
426   }
427 
428   if (link_added) {
429     ntreeUpdateTree(G.main, localtree);
430   }
431 }
432 
flatten_group_do(bNodeTree * ntree,bNode * gnode)433 static void flatten_group_do(bNodeTree *ntree, bNode *gnode)
434 {
435   bNodeLink *link, *linkn, *tlink;
436   bNode *node, *nextnode;
437   bNodeTree *ngroup;
438   LinkNode *group_interface_nodes = NULL;
439 
440   ngroup = (bNodeTree *)gnode->id;
441 
442   /* Add the nodes into the ntree */
443   for (node = ngroup->nodes.first; node; node = nextnode) {
444     nextnode = node->next;
445     /* Remove interface nodes.
446      * This also removes remaining links to and from interface nodes.
447      * We must delay removal since sockets will reference this node. see: T52092 */
448     if (ELEM(node->type, NODE_GROUP_INPUT, NODE_GROUP_OUTPUT)) {
449       BLI_linklist_prepend(&group_interface_nodes, node);
450     }
451     /* migrate node */
452     BLI_remlink(&ngroup->nodes, node);
453     BLI_addtail(&ntree->nodes, node);
454     /* ensure unique node name in the node tree */
455     /* This is very slow and it has no use for GPU nodetree. (see T70609) */
456     // nodeUniqueName(ntree, node);
457   }
458 
459   /* Save first and last link to iterate over flattened group links. */
460   bNodeLink *glinks_first = ntree->links.last;
461 
462   /* Add internal links to the ntree */
463   for (link = ngroup->links.first; link; link = linkn) {
464     linkn = link->next;
465     BLI_remlink(&ngroup->links, link);
466     BLI_addtail(&ntree->links, link);
467   }
468 
469   bNodeLink *glinks_last = ntree->links.last;
470 
471   /* restore external links to and from the gnode */
472   if (glinks_first != NULL) {
473     /* input links */
474     for (link = glinks_first->next; link != glinks_last->next; link = link->next) {
475       if (link->fromnode->type == NODE_GROUP_INPUT) {
476         const char *identifier = link->fromsock->identifier;
477         /* find external links to this input */
478         for (tlink = ntree->links.first; tlink != glinks_first->next; tlink = tlink->next) {
479           if (tlink->tonode == gnode && STREQ(tlink->tosock->identifier, identifier)) {
480             nodeAddLink(ntree, tlink->fromnode, tlink->fromsock, link->tonode, link->tosock);
481           }
482         }
483       }
484     }
485     /* Also iterate over the new links to cover passthrough links. */
486     glinks_last = ntree->links.last;
487     /* output links */
488     for (tlink = ntree->links.first; tlink != glinks_first->next; tlink = tlink->next) {
489       if (tlink->fromnode == gnode) {
490         const char *identifier = tlink->fromsock->identifier;
491         /* find internal links to this output */
492         for (link = glinks_first->next; link != glinks_last->next; link = link->next) {
493           /* only use active output node */
494           if (link->tonode->type == NODE_GROUP_OUTPUT && (link->tonode->flag & NODE_DO_OUTPUT)) {
495             if (STREQ(link->tosock->identifier, identifier)) {
496               nodeAddLink(ntree, link->fromnode, link->fromsock, tlink->tonode, tlink->tosock);
497             }
498           }
499         }
500       }
501     }
502   }
503 
504   while (group_interface_nodes) {
505     node = BLI_linklist_pop(&group_interface_nodes);
506     ntreeFreeLocalNode(ntree, node);
507   }
508 
509   ntree->update |= NTREE_UPDATE_NODES | NTREE_UPDATE_LINKS;
510 }
511 
512 /* Flatten group to only have a simple single tree */
ntree_shader_groups_flatten(bNodeTree * localtree)513 static void ntree_shader_groups_flatten(bNodeTree *localtree)
514 {
515   /* This is effectively recursive as the flattened groups will add
516    * nodes at the end of the list, which will also get evaluated. */
517   for (bNode *node = localtree->nodes.first, *node_next; node; node = node_next) {
518     if (ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP) && node->id != NULL) {
519       flatten_group_do(localtree, node);
520       /* Continue even on new flattened nodes. */
521       node_next = node->next;
522       /* delete the group instance and its localtree. */
523       bNodeTree *ngroup = (bNodeTree *)node->id;
524       ntreeFreeLocalNode(localtree, node);
525       ntreeFreeTree(ngroup);
526       MEM_freeN(ngroup);
527     }
528     else {
529       node_next = node->next;
530     }
531   }
532 
533   ntreeUpdateTree(G.main, localtree);
534 }
535 
536 /* Check whether shader has a displacement.
537  *
538  * Will also return a node and its socket which is connected to a displacement
539  * output. Additionally, link which is attached to the displacement output is
540  * also returned.
541  */
ntree_shader_has_displacement(bNodeTree * ntree,bNode * output_node,bNode ** r_node,bNodeSocket ** r_socket,bNodeLink ** r_link)542 static bool ntree_shader_has_displacement(bNodeTree *ntree,
543                                           bNode *output_node,
544                                           bNode **r_node,
545                                           bNodeSocket **r_socket,
546                                           bNodeLink **r_link)
547 {
548   if (output_node == NULL) {
549     /* We can't have displacement without output node, apparently. */
550     return false;
551   }
552   /* Make sure sockets links pointers are correct. */
553   ntreeUpdateTree(G.main, ntree);
554   bNodeSocket *displacement = ntree_shader_node_find_input(output_node, "Displacement");
555 
556   if (displacement == NULL) {
557     /* Non-cycles node is used as an output. */
558     return false;
559   }
560   if (displacement->link != NULL) {
561     *r_node = displacement->link->fromnode;
562     *r_socket = displacement->link->fromsock;
563     *r_link = displacement->link;
564   }
565   return displacement->link != NULL;
566 }
567 
ntree_shader_relink_node_normal(bNodeTree * ntree,bNode * node,bNode * node_from,bNodeSocket * socket_from)568 static void ntree_shader_relink_node_normal(bNodeTree *ntree,
569                                             bNode *node,
570                                             bNode *node_from,
571                                             bNodeSocket *socket_from)
572 {
573   /* TODO(sergey): Can we do something smarter here than just a name-based
574    * matching?
575    */
576   LISTBASE_FOREACH (bNodeSocket *, sock, &node->inputs) {
577     if (STREQ(sock->identifier, "Normal") && sock->link == NULL) {
578       /* It's a normal input and nothing is connected to it. */
579       nodeAddLink(ntree, node_from, socket_from, node, sock);
580     }
581     else if (sock->link) {
582       bNodeLink *link = sock->link;
583       if (ELEM(link->fromnode->type, SH_NODE_NEW_GEOMETRY, SH_NODE_TEX_COORD) &&
584           STREQ(link->fromsock->identifier, "Normal")) {
585         /* Linked to a geometry node normal output. */
586         nodeAddLink(ntree, node_from, socket_from, node, sock);
587       }
588     }
589   }
590 }
591 
592 /* Use specified node and socket as an input for unconnected normal sockets. */
ntree_shader_link_builtin_normal(bNodeTree * ntree,bNode * node_from,bNodeSocket * socket_from)593 static void ntree_shader_link_builtin_normal(bNodeTree *ntree,
594                                              bNode *node_from,
595                                              bNodeSocket *socket_from)
596 {
597   for (bNode *node = ntree->nodes.first; node != NULL; node = node->next) {
598     if (node == node_from) {
599       /* Don't connect node itself! */
600       continue;
601     }
602     if (node->tmp_flag == -2) {
603       /* This node is used inside the displacement tree. Skip to avoid cycles. */
604       continue;
605     }
606     ntree_shader_relink_node_normal(ntree, node, node_from, socket_from);
607   }
608 }
609 
ntree_shader_bypass_bump_link(bNodeTree * ntree,bNode * bump_node,bNodeLink * bump_link)610 static void ntree_shader_bypass_bump_link(bNodeTree *ntree, bNode *bump_node, bNodeLink *bump_link)
611 {
612   /* Bypass bump nodes. This replicates cycles "implicit" behavior. */
613   bNodeSocket *bump_normal_input = ntree_shader_node_find_input(bump_node, "Normal");
614   bNode *fromnode;
615   bNodeSocket *fromsock;
616   /* Default to builtin normals if there is no link. */
617   if (bump_normal_input->link) {
618     fromsock = bump_normal_input->link->fromsock;
619     fromnode = bump_normal_input->link->fromnode;
620   }
621   else {
622     fromnode = nodeAddStaticNode(NULL, ntree, SH_NODE_NEW_GEOMETRY);
623     fromsock = ntree_shader_node_find_output(fromnode, "Normal");
624   }
625   /* Bypass the bump node by creating a link between the previous and next node. */
626   nodeAddLink(ntree, fromnode, fromsock, bump_link->tonode, bump_link->tosock);
627   nodeRemLink(ntree, bump_link);
628 }
629 
ntree_shader_bypass_tagged_bump_nodes(bNodeTree * ntree)630 static void ntree_shader_bypass_tagged_bump_nodes(bNodeTree *ntree)
631 {
632   /* Bypass bump links inside copied nodes */
633   LISTBASE_FOREACH_MUTABLE (bNodeLink *, link, &ntree->links) {
634     bNode *node = link->fromnode;
635     /* If node is a copy. */
636     if (node->tmp_flag == -2 && node->type == SH_NODE_BUMP) {
637       ntree_shader_bypass_bump_link(ntree, node, link);
638     }
639   }
640   ntreeUpdateTree(G.main, ntree);
641 }
642 
ntree_branch_count_and_tag_nodes(bNode * fromnode,bNode * tonode,void * userdata)643 static bool ntree_branch_count_and_tag_nodes(bNode *fromnode, bNode *tonode, void *userdata)
644 {
645   int *node_count = (int *)userdata;
646   if (fromnode->tmp_flag == -1) {
647     fromnode->tmp_flag = *node_count;
648     (*node_count)++;
649   }
650   if (tonode->tmp_flag == -1) {
651     tonode->tmp_flag = *node_count;
652     (*node_count)++;
653   }
654   return true;
655 }
656 
657 /* Create a copy of a branch starting from a given node.
658  * callback is executed once for every copied node.
659  * Returns input node copy. */
ntree_shader_copy_branch(bNodeTree * ntree,bNode * start_node,void (* callback)(bNode * node,int user_data),int user_data)660 static bNode *ntree_shader_copy_branch(bNodeTree *ntree,
661                                        bNode *start_node,
662                                        void (*callback)(bNode *node, int user_data),
663                                        int user_data)
664 {
665   /* Init tmp flag. */
666   LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
667     node->tmp_flag = -1;
668   }
669   /* Count and tag all nodes inside the displacement branch of the tree. */
670   start_node->tmp_flag = 0;
671   int node_count = 1;
672   nodeChainIterBackwards(ntree, start_node, ntree_branch_count_and_tag_nodes, &node_count, 1);
673   /* Make a full copy of the branch */
674   bNode **nodes_copy = MEM_mallocN(sizeof(bNode *) * node_count, __func__);
675   LISTBASE_FOREACH (bNode *, node, &ntree->nodes) {
676     if (node->tmp_flag >= 0) {
677       int id = node->tmp_flag;
678       nodes_copy[id] = BKE_node_copy_ex(
679           ntree, node, LIB_ID_CREATE_NO_USER_REFCOUNT | LIB_ID_CREATE_NO_MAIN, false);
680       nodes_copy[id]->tmp_flag = -2; /* Copy */
681       /* Make sure to clear all sockets links as they are invalid. */
682       LISTBASE_FOREACH (bNodeSocket *, sock, &nodes_copy[id]->inputs) {
683         sock->link = NULL;
684       }
685       LISTBASE_FOREACH (bNodeSocket *, sock, &nodes_copy[id]->outputs) {
686         sock->link = NULL;
687       }
688     }
689   }
690   /* Recreate links between copied nodes. */
691   LISTBASE_FOREACH (bNodeLink *, link, &ntree->links) {
692     if (link->fromnode->tmp_flag >= 0 && link->tonode->tmp_flag >= 0) {
693       bNode *fromnode = nodes_copy[link->fromnode->tmp_flag];
694       bNode *tonode = nodes_copy[link->tonode->tmp_flag];
695       bNodeSocket *fromsock = ntree_shader_node_find_output(fromnode, link->fromsock->identifier);
696       bNodeSocket *tosock = ntree_shader_node_find_input(tonode, link->tosock->identifier);
697       nodeAddLink(ntree, fromnode, fromsock, tonode, tosock);
698     }
699   }
700   /* Per node callback. */
701   if (callback) {
702     for (int i = 0; i < node_count; i++) {
703       callback(nodes_copy[i], user_data);
704     }
705   }
706   bNode *start_node_copy = nodes_copy[start_node->tmp_flag];
707   MEM_freeN(nodes_copy);
708   return start_node_copy;
709 }
710 
ntree_shader_copy_branch_displacement(bNodeTree * ntree,bNode * displacement_node,bNodeSocket * displacement_socket,bNodeLink * displacement_link)711 static void ntree_shader_copy_branch_displacement(bNodeTree *ntree,
712                                                   bNode *displacement_node,
713                                                   bNodeSocket *displacement_socket,
714                                                   bNodeLink *displacement_link)
715 {
716   /* Replace displacement socket/node/link. */
717   bNode *tonode = displacement_link->tonode;
718   bNodeSocket *tosock = displacement_link->tosock;
719   displacement_node = ntree_shader_copy_branch(ntree, displacement_node, NULL, 0);
720   displacement_socket = ntree_shader_node_find_output(displacement_node,
721                                                       displacement_socket->identifier);
722   nodeRemLink(ntree, displacement_link);
723   nodeAddLink(ntree, displacement_node, displacement_socket, tonode, tosock);
724 
725   ntreeUpdateTree(G.main, ntree);
726 }
727 
728 /* Re-link displacement output to unconnected normal sockets via bump node.
729  * This way material with have proper displacement in the viewport.
730  */
ntree_shader_relink_displacement(bNodeTree * ntree,bNode * output_node)731 static void ntree_shader_relink_displacement(bNodeTree *ntree, bNode *output_node)
732 {
733   bNode *displacement_node;
734   bNodeSocket *displacement_socket;
735   bNodeLink *displacement_link;
736   if (!ntree_shader_has_displacement(
737           ntree, output_node, &displacement_node, &displacement_socket, &displacement_link)) {
738     /* There is no displacement output connected, nothing to re-link. */
739     return;
740   }
741 
742   /* Copy the whole displacement branch to avoid cyclic dependency
743    * and issue when bypassing bump nodes. */
744   ntree_shader_copy_branch_displacement(
745       ntree, displacement_node, displacement_socket, displacement_link);
746   /* Bypass bump nodes inside the copied branch to mimic cycles behavior. */
747   ntree_shader_bypass_tagged_bump_nodes(ntree);
748 
749   /* Displacement Node may have changed because of branch copy and bump bypass. */
750   ntree_shader_has_displacement(
751       ntree, output_node, &displacement_node, &displacement_socket, &displacement_link);
752 
753   /* We have to disconnect displacement output socket, otherwise we'll have
754    * cycles in the Cycles material :)
755    */
756   nodeRemLink(ntree, displacement_link);
757 
758   /* Convert displacement vector to bump height. */
759   bNode *dot_node = nodeAddStaticNode(NULL, ntree, SH_NODE_VECTOR_MATH);
760   bNode *geo_node = nodeAddStaticNode(NULL, ntree, SH_NODE_NEW_GEOMETRY);
761   bNodeSocket *normal_socket = ntree_shader_node_find_output(geo_node, "Normal");
762   bNodeSocket *dot_input1 = dot_node->inputs.first;
763   bNodeSocket *dot_input2 = dot_input1->next;
764   dot_node->custom1 = NODE_VECTOR_MATH_DOT_PRODUCT;
765 
766   nodeAddLink(ntree, displacement_node, displacement_socket, dot_node, dot_input1);
767   nodeAddLink(ntree, geo_node, normal_socket, dot_node, dot_input2);
768   displacement_node = dot_node;
769   displacement_socket = ntree_shader_node_find_output(dot_node, "Value");
770 
771   /* We can't connect displacement to normal directly, use bump node for that
772    * and hope that it gives good enough approximation.
773    */
774   bNode *bump_node = nodeAddStaticNode(NULL, ntree, SH_NODE_BUMP);
775   bNodeSocket *bump_input_socket = ntree_shader_node_find_input(bump_node, "Height");
776   bNodeSocket *bump_output_socket = ntree_shader_node_find_output(bump_node, "Normal");
777   BLI_assert(bump_input_socket != NULL);
778   BLI_assert(bump_output_socket != NULL);
779   /* Connect bump node to where displacement output was originally
780    * connected to.
781    */
782   nodeAddLink(ntree, displacement_node, displacement_socket, bump_node, bump_input_socket);
783 
784   /* Tag as part of the new displacmeent tree. */
785   dot_node->tmp_flag = -2;
786   geo_node->tmp_flag = -2;
787   bump_node->tmp_flag = -2;
788 
789   ntreeUpdateTree(G.main, ntree);
790 
791   /* Connect all free-standing Normal inputs and relink geometry/coordinate nodes. */
792   ntree_shader_link_builtin_normal(ntree, bump_node, bump_output_socket);
793   /* We modified the tree, it needs to be updated now. */
794   ntreeUpdateTree(G.main, ntree);
795 }
796 
node_tag_branch_as_derivative(bNode * node,int dx)797 static void node_tag_branch_as_derivative(bNode *node, int dx)
798 {
799   if (dx) {
800     node->branch_tag = 1;
801   }
802   else {
803     node->branch_tag = 2;
804   }
805 }
806 
ntree_shader_bump_branches(bNode * fromnode,bNode * UNUSED (tonode),void * userdata)807 static bool ntree_shader_bump_branches(bNode *fromnode, bNode *UNUSED(tonode), void *userdata)
808 {
809   bNodeTree *ntree = (bNodeTree *)userdata;
810 
811   if (fromnode->type == SH_NODE_BUMP) {
812     bNodeSocket *height_dx_sock, *height_dy_sock, *bump_socket, *bump_dx_socket, *bump_dy_socket;
813     bNode *bump = fromnode;
814     bump_socket = ntree_shader_node_find_input(bump, "Height");
815     bump_dx_socket = ntree_shader_node_find_input(bump, "Height_dx");
816     bump_dy_socket = ntree_shader_node_find_input(bump, "Height_dy");
817     if (bump_dx_socket->link) {
818       /* Avoid reconnecting the same bump twice. */
819     }
820     else if (bump_socket && bump_socket->link) {
821       bNodeLink *link = bump_socket->link;
822       bNode *height = link->fromnode;
823       bNode *height_dx = ntree_shader_copy_branch(ntree, height, node_tag_branch_as_derivative, 1);
824       bNode *height_dy = ntree_shader_copy_branch(ntree, height, node_tag_branch_as_derivative, 0);
825       height_dx_sock = ntree_shader_node_find_output(height_dx, link->fromsock->identifier);
826       height_dy_sock = ntree_shader_node_find_output(height_dy, link->fromsock->identifier);
827       nodeAddLink(ntree, height_dx, height_dx_sock, bump, bump_dx_socket);
828       nodeAddLink(ntree, height_dy, height_dy_sock, bump, bump_dy_socket);
829       /* We could end iter here, but other bump node could be plugged into other input sockets. */
830     }
831   }
832   return true;
833 }
834 
ntree_tag_bsdf_cb(bNode * fromnode,bNode * UNUSED (tonode),void * userdata)835 static bool ntree_tag_bsdf_cb(bNode *fromnode, bNode *UNUSED(tonode), void *userdata)
836 {
837   switch (fromnode->type) {
838     case SH_NODE_BSDF_ANISOTROPIC:
839     case SH_NODE_EEVEE_SPECULAR:
840     case SH_NODE_BSDF_GLOSSY:
841     case SH_NODE_BSDF_GLASS:
842       fromnode->ssr_id = ((nTreeTags *)userdata)->ssr_id;
843       ((nTreeTags *)userdata)->ssr_id += 1;
844       break;
845     case SH_NODE_SUBSURFACE_SCATTERING:
846       fromnode->sss_id = ((nTreeTags *)userdata)->sss_id;
847       ((nTreeTags *)userdata)->sss_id += 1;
848       break;
849     case SH_NODE_BSDF_PRINCIPLED:
850       fromnode->ssr_id = ((nTreeTags *)userdata)->ssr_id;
851       fromnode->sss_id = ((nTreeTags *)userdata)->sss_id;
852       ((nTreeTags *)userdata)->sss_id += 1;
853       ((nTreeTags *)userdata)->ssr_id += 1;
854       break;
855     default:
856       /* We could return false here but since we
857        * allow the use of Closure as RGBA, we can have
858        * Bsdf nodes linked to other Bsdf nodes. */
859       break;
860   }
861 
862   return true;
863 }
864 
865 /* EEVEE: Scan the ntree to set the Screen Space Reflection
866  * layer id of every specular node AND the Subsurface Scattering id of every SSS node.
867  */
ntree_shader_tag_nodes(bNodeTree * ntree,bNode * output_node,nTreeTags * tags)868 void ntree_shader_tag_nodes(bNodeTree *ntree, bNode *output_node, nTreeTags *tags)
869 {
870   if (output_node == NULL) {
871     return;
872   }
873   /* Make sure sockets links pointers are correct. */
874   ntreeUpdateTree(G.main, ntree);
875 
876   nodeChainIterBackwards(ntree, output_node, ntree_tag_bsdf_cb, tags, 0);
877 }
878 
879 /* This one needs to work on a local tree. */
ntreeGPUMaterialNodes(bNodeTree * localtree,GPUMaterial * mat,bool * has_surface_output,bool * has_volume_output)880 void ntreeGPUMaterialNodes(bNodeTree *localtree,
881                            GPUMaterial *mat,
882                            bool *has_surface_output,
883                            bool *has_volume_output)
884 {
885   bNodeTreeExec *exec;
886 
887   bNode *output = ntreeShaderOutputNode(localtree, SHD_OUTPUT_EEVEE);
888 
889   ntree_shader_groups_expand_inputs(localtree);
890 
891   ntree_shader_groups_flatten(localtree);
892 
893   if (output == NULL) {
894     /* Search again, now including flattened nodes. */
895     output = ntreeShaderOutputNode(localtree, SHD_OUTPUT_EEVEE);
896   }
897 
898   /* Perform all needed modifications on the tree in order to support
899    * displacement/bump mapping.
900    */
901   ntree_shader_relink_displacement(localtree, output);
902 
903   /* Duplicate bump height branches for manual derivatives.
904    */
905   nodeChainIterBackwards(localtree, output, ntree_shader_bump_branches, localtree, 0);
906 
907   /* TODO(fclem): consider moving this to the gpu shader tree evaluation. */
908   nTreeTags tags = {
909       .ssr_id = 1.0,
910       .sss_id = 1.0,
911   };
912   ntree_shader_tag_nodes(localtree, output, &tags);
913 
914   exec = ntreeShaderBeginExecTree(localtree);
915   ntreeExecGPUNodes(exec, mat, output);
916   ntreeShaderEndExecTree(exec);
917 
918   /* EEVEE: Find which material domain was used (volume, surface ...). */
919   *has_surface_output = false;
920   *has_volume_output = false;
921 
922   if (output != NULL) {
923     bNodeSocket *surface_sock = ntree_shader_node_find_input(output, "Surface");
924     bNodeSocket *volume_sock = ntree_shader_node_find_input(output, "Volume");
925 
926     if (surface_sock != NULL) {
927       *has_surface_output = (nodeCountSocketLinks(localtree, surface_sock) > 0);
928     }
929 
930     if (volume_sock != NULL) {
931       *has_volume_output = (nodeCountSocketLinks(localtree, volume_sock) > 0);
932     }
933   }
934 }
935 
ntreeShaderBeginExecTree_internal(bNodeExecContext * context,bNodeTree * ntree,bNodeInstanceKey parent_key)936 bNodeTreeExec *ntreeShaderBeginExecTree_internal(bNodeExecContext *context,
937                                                  bNodeTree *ntree,
938                                                  bNodeInstanceKey parent_key)
939 {
940   bNodeTreeExec *exec;
941   bNode *node;
942 
943   /* ensures only a single output node is enabled */
944   ntreeSetOutput(ntree);
945 
946   /* common base initialization */
947   exec = ntree_exec_begin(context, ntree, parent_key);
948 
949   /* allocate the thread stack listbase array */
950   exec->threadstack = MEM_callocN(BLENDER_MAX_THREADS * sizeof(ListBase), "thread stack array");
951 
952   for (node = exec->nodetree->nodes.first; node; node = node->next) {
953     node->need_exec = 1;
954   }
955 
956   return exec;
957 }
958 
ntreeShaderBeginExecTree(bNodeTree * ntree)959 bNodeTreeExec *ntreeShaderBeginExecTree(bNodeTree *ntree)
960 {
961   bNodeExecContext context;
962   bNodeTreeExec *exec;
963 
964   /* XXX hack: prevent exec data from being generated twice.
965    * this should be handled by the renderer!
966    */
967   if (ntree->execdata) {
968     return ntree->execdata;
969   }
970 
971   context.previews = ntree->previews;
972 
973   exec = ntreeShaderBeginExecTree_internal(&context, ntree, NODE_INSTANCE_KEY_BASE);
974 
975   /* XXX this should not be necessary, but is still used for cmp/sha/tex nodes,
976    * which only store the ntree pointer. Should be fixed at some point!
977    */
978   ntree->execdata = exec;
979 
980   return exec;
981 }
982 
ntreeShaderEndExecTree_internal(bNodeTreeExec * exec)983 void ntreeShaderEndExecTree_internal(bNodeTreeExec *exec)
984 {
985   bNodeThreadStack *nts;
986   int a;
987 
988   if (exec->threadstack) {
989     for (a = 0; a < BLENDER_MAX_THREADS; a++) {
990       for (nts = exec->threadstack[a].first; nts; nts = nts->next) {
991         if (nts->stack) {
992           MEM_freeN(nts->stack);
993         }
994       }
995       BLI_freelistN(&exec->threadstack[a]);
996     }
997 
998     MEM_freeN(exec->threadstack);
999     exec->threadstack = NULL;
1000   }
1001 
1002   ntree_exec_end(exec);
1003 }
1004 
ntreeShaderEndExecTree(bNodeTreeExec * exec)1005 void ntreeShaderEndExecTree(bNodeTreeExec *exec)
1006 {
1007   if (exec) {
1008     /* exec may get freed, so assign ntree */
1009     bNodeTree *ntree = exec->nodetree;
1010     ntreeShaderEndExecTree_internal(exec);
1011 
1012     /* XXX clear nodetree backpointer to exec data, same problem as noted in ntreeBeginExecTree */
1013     ntree->execdata = NULL;
1014   }
1015 }
1016 
1017 /* TODO: left over from Blender Internal, could reuse for new texture nodes. */
ntreeShaderExecTree(bNodeTree * ntree,int thread)1018 bool ntreeShaderExecTree(bNodeTree *ntree, int thread)
1019 {
1020   ShaderCallData scd;
1021   bNodeThreadStack *nts = NULL;
1022   bNodeTreeExec *exec = ntree->execdata;
1023   int compat;
1024 
1025   /* ensure execdata is only initialized once */
1026   if (!exec) {
1027     BLI_thread_lock(LOCK_NODES);
1028     if (!ntree->execdata) {
1029       ntree->execdata = ntreeShaderBeginExecTree(ntree);
1030     }
1031     BLI_thread_unlock(LOCK_NODES);
1032 
1033     exec = ntree->execdata;
1034   }
1035 
1036   nts = ntreeGetThreadStack(exec, thread);
1037   compat = ntreeExecThreadNodes(exec, nts, &scd, thread);
1038   ntreeReleaseThreadStack(nts);
1039 
1040   /* if compat is zero, it has been using non-compatible nodes */
1041   return compat;
1042 }
1043