Camera UI: tweaking panels, move clipping back because it's not part of the
[blender-staging.git] / source / blender / blenkernel / intern / node.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Bob Holcomb.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/node.c
29  *  \ingroup bke
30  */
31
32
33 #if 0 /* pynodes commented for now */
34 #  ifdef WITH_PYTHON
35 #    include <Python.h>
36 #  endif
37 #endif
38
39 #include "MEM_guardedalloc.h"
40
41 #include <stdlib.h>
42 #include <stddef.h>
43 #include <string.h>
44 #include <limits.h>
45
46 #include "DNA_action_types.h"
47 #include "DNA_anim_types.h"
48 #include "DNA_node_types.h"
49 #include "DNA_node_types.h"
50 #include "DNA_scene_types.h"
51
52 #include "BLI_string.h"
53 #include "BLI_math.h"
54 #include "BLI_listbase.h"
55 #include "BLI_path_util.h"
56 #include "BLI_utildefines.h"
57
58 #include "BKE_animsys.h"
59 #include "BKE_action.h"
60 #include "BKE_fcurve.h"
61 #include "BKE_global.h"
62 #include "BKE_image.h"
63 #include "BKE_library.h"
64 #include "BKE_main.h"
65 #include "BKE_node.h"
66 #include "BKE_utildefines.h"
67 #include "BKE_utildefines.h"
68
69 #include "BLI_listbase.h"
70
71 #include "RNA_access.h"
72
73 #include "NOD_socket.h"
74 #include "NOD_composite.h"
75 #include "NOD_shader.h"
76 #include "NOD_texture.h"
77
78
79 bNodeTreeType *ntreeGetType(int type)
80 {
81         static bNodeTreeType *types[NUM_NTREE_TYPES];
82         static int types_init = 1;
83         if (types_init) {
84                 types[NTREE_SHADER] = &ntreeType_Shader;
85                 types[NTREE_COMPOSIT] = &ntreeType_Composite;
86                 types[NTREE_TEXTURE] = &ntreeType_Texture;
87                 types_init = 0;
88         }
89         
90         if(type >= 0 && type < NUM_NTREE_TYPES) {
91                 return types[type];
92         }
93         else {
94                 return NULL;
95         }
96 }
97
98 static bNodeType *node_get_type(bNodeTree *ntree, int type)
99 {
100         bNodeType *ntype = ntreeGetType(ntree->type)->node_types.first;
101         for(; ntype; ntype= ntype->next)
102                 if(ntype->type==type)
103                         return ntype;
104         
105         return NULL;
106 }
107
108 bNodeType *ntreeGetNodeType(bNodeTree *ntree)
109 {
110         return node_get_type(ntree, ntree->nodetype);
111 }
112
113 bNodeSocketType *ntreeGetSocketType(int type)
114 {
115         static bNodeSocketType *types[NUM_SOCKET_TYPES]= {NULL};
116         static int types_init = 1;
117
118         if (types_init) {
119                 node_socket_type_init(types);
120                 types_init= 0;
121         }
122
123         if(type < NUM_SOCKET_TYPES) {
124                 return types[type];
125         }
126         else {
127                 return NULL;
128         }
129 }
130
131 void ntreeInitTypes(bNodeTree *ntree)
132 {
133         bNode *node, *next;
134         
135         for(node= ntree->nodes.first; node; node= next) {
136                 next= node->next;
137                 
138                 node->typeinfo= node_get_type(ntree, node->type);
139                 
140                 if(node->type==NODE_DYNAMIC) {
141                         /* needed info if the pynode script fails now: */
142                         node->storage= ntree;
143                         if(node->id!=NULL) { /* not an empty script node */
144                                 node->custom1= 0;
145                                 node->custom1= BSET(node->custom1,NODE_DYNAMIC_ADDEXIST);
146                         }
147 //                      if(node->typeinfo)
148 //                              node->typeinfo->initfunc(node);
149                 }
150
151                 if(node->typeinfo==NULL) {
152                         printf("Error: Node type %s doesn't exist anymore, removed\n", node->name);
153                         nodeFreeNode(ntree, node);
154                 }
155         }
156                         
157         ntree->init |= NTREE_TYPE_INIT;
158 }
159
160 static bNodeSocket *make_socket(bNodeTree *UNUSED(ntree), int in_out, const char *name, int type)
161 {
162         bNodeSocketType *stype= ntreeGetSocketType(type);
163         bNodeSocket *sock;
164         
165         sock= MEM_callocN(sizeof(bNodeSocket), "sock");
166         
167         BLI_strncpy(sock->name, name, NODE_MAXSTR);
168         sock->limit = (in_out==SOCK_IN ? 1 : 0xFFF);
169         sock->type= type;
170         sock->storage = NULL;
171         
172         if (stype->value_structsize > 0)
173                 sock->default_value = MEM_callocN(stype->value_structsize, "default socket value");
174         
175         return sock;
176 }
177
178 bNodeSocket *nodeAddSocket(bNodeTree *ntree, bNode *node, int in_out, const char *name, int type)
179 {
180         bNodeSocket *sock = make_socket(ntree, in_out, name, type);
181         if (in_out==SOCK_IN)
182                 BLI_addtail(&node->inputs, sock);
183         else if (in_out==SOCK_OUT)
184                 BLI_addtail(&node->outputs, sock);
185         
186         node->update |= NODE_UPDATE;
187         
188         return sock;
189 }
190
191 bNodeSocket *nodeInsertSocket(bNodeTree *ntree, bNode *node, int in_out, bNodeSocket *next_sock, const char *name, int type)
192 {
193         bNodeSocket *sock = make_socket(ntree, in_out, name, type);
194         if (in_out==SOCK_IN)
195                 BLI_insertlinkbefore(&node->inputs, next_sock, sock);
196         else if (in_out==SOCK_OUT)
197                 BLI_insertlinkbefore(&node->outputs, next_sock, sock);
198         
199         node->update |= NODE_UPDATE;
200         
201         return sock;
202 }
203
204 void nodeRemoveSocket(bNodeTree *ntree, bNode *node, bNodeSocket *sock)
205 {
206         bNodeLink *link, *next;
207         
208         for(link= ntree->links.first; link; link= next) {
209                 next= link->next;
210                 if(link->fromsock==sock || link->tosock==sock) {
211                         nodeRemLink(ntree, link);
212                 }
213         }
214         
215         /* this is fast, this way we don't need an in_out argument */
216         BLI_remlink(&node->inputs, sock);
217         BLI_remlink(&node->outputs, sock);
218         
219         if (sock->default_value)
220                 MEM_freeN(sock->default_value);
221         MEM_freeN(sock);
222         
223         node->update |= NODE_UPDATE;
224 }
225
226 void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node)
227 {
228         bNodeSocket *sock;
229         bNodeLink *link, *next;
230         
231         for(link= ntree->links.first; link; link= next) {
232                 next= link->next;
233                 if(link->fromnode==node || link->tonode==node) {
234                         nodeRemLink(ntree, link);
235                 }
236         }
237         
238         for (sock=node->inputs.first; sock; sock=sock->next)
239                 if (sock->default_value)
240                         MEM_freeN(sock->default_value);
241         BLI_freelistN(&node->inputs);
242         for (sock=node->outputs.first; sock; sock=sock->next)
243                 if (sock->default_value)
244                         MEM_freeN(sock->default_value);
245         
246         BLI_freelistN(&node->outputs);
247         
248         node->update |= NODE_UPDATE;
249 }
250
251 /* finds a node based on its name */
252 bNode *nodeFindNodebyName(bNodeTree *ntree, const char *name)
253 {
254         return BLI_findstring(&ntree->nodes, name, offsetof(bNode, name));
255 }
256
257 /* finds a node based on given socket */
258 int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockindex, int *in_out)
259 {
260         bNode *node;
261         bNodeSocket *tsock;
262         int index= 0;
263         
264         for(node= ntree->nodes.first; node; node= node->next) {
265                 for(index=0, tsock= node->inputs.first; tsock; tsock= tsock->next, index++) {
266                         if(tsock==sock) {
267                                 if (in_out) *in_out= SOCK_IN;
268                                 break;
269                         }
270                 }
271                 if(tsock)
272                         break;
273                 for(index=0, tsock= node->outputs.first; tsock; tsock= tsock->next, index++) {
274                         if(tsock==sock) {
275                                 if (in_out) *in_out= SOCK_OUT;
276                                 break;
277                         }
278                 }
279                 if(tsock)
280                         break;
281         }
282
283         if(node) {
284                 *nodep= node;
285                 if(sockindex) *sockindex= index;
286                 return 1;
287         }
288         
289         *nodep= NULL;
290         return 0;
291 }
292
293 /* ************** Add stuff ********** */
294 static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType *ntype)
295 {
296         bNodeSocketTemplate *sockdef;
297         /* bNodeSocket *sock; */ /* UNUSED */
298
299         if(ntype->inputs) {
300                 sockdef= ntype->inputs;
301                 while(sockdef->type != -1) {
302                         /* sock = */ node_add_input_from_template(ntree, node, sockdef);
303                         
304                         sockdef++;
305                 }
306         }
307         if(ntype->outputs) {
308                 sockdef= ntype->outputs;
309                 while(sockdef->type != -1) {
310                         /* sock = */ node_add_output_from_template(ntree, node, sockdef);
311                         
312                         sockdef++;
313                 }
314         }
315 }
316
317 /* Find the first available, non-duplicate name for a given node */
318 void nodeUniqueName(bNodeTree *ntree, bNode *node)
319 {
320         BLI_uniquename(&ntree->nodes, node, "Node", '.', offsetof(bNode, name), sizeof(node->name));
321 }
322
323 bNode *nodeAddNode(bNodeTree *ntree, struct bNodeTemplate *ntemp)
324 {
325         bNode *node;
326         bNodeType *ntype;
327         
328         ntype= node_get_type(ntree, ntemp->type);
329         if(ntype == NULL) {
330                 printf("nodeAddNodeType() error: '%d' type invalid\n", ntemp->type);
331                 return NULL;
332         }
333         /* validity check */
334         if (!nodeValid(ntree, ntemp))
335                 return NULL;
336         
337         node= MEM_callocN(sizeof(bNode), "new node");
338         node->type= ntype->type;
339         node->typeinfo= ntype;
340         node->flag= NODE_SELECT|ntype->flag;
341         node->width= ntype->width;
342         node->miniwidth= 42.0f;
343         node->height= ntype->height;
344         
345         node_add_sockets_from_type(ntree, node, ntype);
346         
347         if(ntype->initfunc!=NULL)
348                 ntype->initfunc(ntree, node, ntemp);
349         
350         /* initialize the node name with the node label */
351         BLI_strncpy(node->name, nodeLabel(node), NODE_MAXSTR);
352         nodeUniqueName(ntree, node);
353         
354         BLI_addtail(&ntree->nodes, node);
355         
356         ntree->update |= NTREE_UPDATE_NODES;
357         
358         return node;
359 }
360
361 void nodeMakeDynamicType(bNode *node)
362 {
363         /* find SH_DYNAMIC_NODE ntype */
364         bNodeType *ntype= ntreeGetType(NTREE_SHADER)->node_types.first;
365         while(ntype) {
366                 if(ntype->type==NODE_DYNAMIC)
367                         break;
368                 ntype= ntype->next;
369         }
370
371         /* make own type struct to fill */
372         if(ntype) {
373                 /*node->typeinfo= MEM_dupallocN(ntype);*/
374                 bNodeType *newtype= MEM_callocN(sizeof(bNodeType), "dynamic bNodeType");
375                 *newtype= *ntype;
376                 BLI_strncpy(newtype->name, ntype->name, sizeof(newtype->name));
377                 node->typeinfo= newtype;
378         }
379 }
380
381 /* keep socket listorder identical, for copying links */
382 /* ntree is the target tree */
383 bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
384 {
385         bNode *nnode= MEM_callocN(sizeof(bNode), "dupli node");
386         bNodeSocket *sock, *oldsock;
387
388         *nnode= *node;
389         nodeUniqueName(ntree, nnode);
390         
391         BLI_addtail(&ntree->nodes, nnode);
392
393         BLI_duplicatelist(&nnode->inputs, &node->inputs);
394         oldsock= node->inputs.first;
395         for(sock= nnode->inputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
396                 oldsock->new_sock= sock;
397                 sock->stack_index= 0;
398                 
399                 sock->default_value = (oldsock->default_value ? MEM_dupallocN(oldsock->default_value) : NULL);
400                 
401                 /* XXX some compositor node (e.g. image, render layers) still store
402                  * some persistent buffer data here, need to clear this to avoid dangling pointers.
403                  */
404                 sock->cache = NULL;
405         }
406         
407         BLI_duplicatelist(&nnode->outputs, &node->outputs);
408         oldsock= node->outputs.first;
409         for(sock= nnode->outputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
410                 oldsock->new_sock= sock;
411                 sock->stack_index= 0;
412                 
413                 sock->default_value = (oldsock->default_value ? MEM_dupallocN(oldsock->default_value) : NULL);
414                 
415                 /* XXX some compositor node (e.g. image, render layers) still store
416                  * some persistent buffer data here, need to clear this to avoid dangling pointers.
417                  */
418                 sock->cache = NULL;
419         }
420         
421         /* don't increase node->id users, freenode doesn't decrement either */
422         
423         if(node->typeinfo->copystoragefunc)
424                 node->typeinfo->copystoragefunc(node, nnode);
425         
426         node->new_node= nnode;
427         nnode->new_node= NULL;
428         nnode->preview= NULL;
429         
430         ntree->update |= NTREE_UPDATE_NODES;
431         
432         return nnode;
433 }
434
435 /* also used via rna api, so we check for proper input output direction */
436 bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, bNode *tonode, bNodeSocket *tosock)
437 {
438         bNodeSocket *sock;
439         bNodeLink *link= NULL; 
440         int from= 0, to= 0;
441         
442         if(fromnode) {
443                 /* test valid input */
444                 for(sock= fromnode->outputs.first; sock; sock= sock->next)
445                         if(sock==fromsock)
446                                 break;
447                 if(sock)
448                         from= 1; /* OK */
449                 else {
450                         for(sock= fromnode->inputs.first; sock; sock= sock->next)
451                                 if(sock==fromsock)
452                                         break;
453                         if(sock)
454                                 from= -1; /* OK but flip */
455                 }
456         }
457         else {
458                 /* check tree sockets */
459                 for(sock= ntree->inputs.first; sock; sock= sock->next)
460                         if(sock==fromsock)
461                                 break;
462                 if(sock)
463                         from= 1; /* OK */
464                 else {
465                         for(sock= ntree->outputs.first; sock; sock= sock->next)
466                                 if(sock==fromsock)
467                                         break;
468                         if(sock)
469                                 from= -1; /* OK but flip */
470                 }
471         }
472         if(tonode) {
473                 for(sock= tonode->inputs.first; sock; sock= sock->next)
474                         if(sock==tosock)
475                                 break;
476                 if(sock)
477                         to= 1; /* OK */
478                 else {
479                         for(sock= tonode->outputs.first; sock; sock= sock->next)
480                                 if(sock==tosock)
481                                         break;
482                         if(sock)
483                                 to= -1; /* OK but flip */
484                 }
485         }
486         else {
487                 /* check tree sockets */
488                 for(sock= ntree->outputs.first; sock; sock= sock->next)
489                         if(sock==tosock)
490                                 break;
491                 if(sock)
492                         to= 1; /* OK */
493                 else {
494                         for(sock= ntree->inputs.first; sock; sock= sock->next)
495                                 if(sock==tosock)
496                                         break;
497                         if(sock)
498                                 to= -1; /* OK but flip */
499                 }
500         }
501         
502         if(from >= 0 && to >= 0) {
503                 link= MEM_callocN(sizeof(bNodeLink), "link");
504                 BLI_addtail(&ntree->links, link);
505                 link->fromnode= fromnode;
506                 link->fromsock= fromsock;
507                 link->tonode= tonode;
508                 link->tosock= tosock;
509         }
510         else if(from <= 0 && to <= 0) {
511                 link= MEM_callocN(sizeof(bNodeLink), "link");
512                 BLI_addtail(&ntree->links, link);
513                 link->fromnode= tonode;
514                 link->fromsock= tosock;
515                 link->tonode= fromnode;
516                 link->tosock= fromsock;
517         }
518         
519         ntree->update |= NTREE_UPDATE_LINKS;
520         
521         return link;
522 }
523
524 void nodeRemLink(bNodeTree *ntree, bNodeLink *link)
525 {
526         BLI_remlink(&ntree->links, link);
527         if(link->tosock)
528                 link->tosock->link= NULL;
529         MEM_freeN(link);
530         
531         ntree->update |= NTREE_UPDATE_LINKS;
532 }
533
534 void nodeRemSocketLinks(bNodeTree *ntree, bNodeSocket *sock)
535 {
536         bNodeLink *link, *next;
537         
538         for(link= ntree->links.first; link; link= next) {
539                 next= link->next;
540                 if(link->fromsock==sock || link->tosock==sock) {
541                         nodeRemLink(ntree, link);
542                 }
543         }
544         
545         ntree->update |= NTREE_UPDATE_LINKS;
546 }
547
548 /* transforms node location to area coords */
549 void nodeSpaceCoords(bNode *node, float *locx, float *locy)
550 {
551         if (node->parent) {
552                 nodeSpaceCoords(node->parent, locx, locy);
553                 *locx += node->locx;
554                 *locy += node->locy;
555         }
556         else {
557                 *locx = node->locx;
558                 *locy = node->locy;
559         }
560 }
561
562 void nodeAttachNode(bNode *node, bNode *parent)
563 {
564         float parentx, parenty;
565         
566         node->parent = parent;
567         /* transform to parent space */
568         nodeSpaceCoords(parent, &parentx, &parenty);
569         node->locx -= parentx;
570         node->locy -= parenty;
571 }
572
573 void nodeDetachNode(struct bNode *node)
574 {
575         float parentx, parenty;
576         
577         if (node->parent) {
578                 /* transform to "global" (area) space */
579                 nodeSpaceCoords(node->parent, &parentx, &parenty);
580                 node->locx += parentx;
581                 node->locy += parenty;
582                 node->parent = NULL;
583         }
584 }
585
586 bNodeTree *ntreeAddTree(const char *name, int type, int nodetype)
587 {
588         bNodeTree *ntree;
589         bNodeType *ntype;
590         
591         /* trees are created as local trees if they of compositor, material or texture type,
592          * node groups and other tree types are created as library data.
593          */
594         if (ELEM3(type, NTREE_COMPOSIT, NTREE_SHADER, NTREE_TEXTURE) && nodetype==0) {
595                 ntree= MEM_callocN(sizeof(bNodeTree), "new node tree");
596                 *( (short *)ntree->id.name )= ID_NT; /* not "type", as that is ntree->type */
597                 BLI_strncpy(ntree->id.name+2, name, sizeof(ntree->id.name));
598         }
599         else
600                 ntree= alloc_libblock(&G.main->nodetree, ID_NT, name);
601         
602         ntree->type= type;
603         ntree->nodetype = nodetype;
604         
605         ntreeInitTypes(ntree);
606         
607         ntype = node_get_type(ntree, ntree->nodetype);
608         if (ntype && ntype->inittreefunc)
609                 ntype->inittreefunc(ntree);
610         
611         return ntree;
612 }
613
614 /* Warning: this function gets called during some rather unexpected times
615  *      - this gets called when executing compositing updates (for threaded previews)
616  *      - when the nodetree datablock needs to be copied (i.e. when users get copied)
617  *      - for scene duplication use ntreeSwapID() after so we dont have stale pointers.
618  */
619 bNodeTree *ntreeCopyTree(bNodeTree *ntree)
620 {
621         bNodeTree *newtree;
622         bNode *node /*, *nnode */ /* UNUSED */, *last;
623         bNodeLink *link;
624         bNodeSocket *gsock, *oldgsock;
625         
626         if(ntree==NULL) return NULL;
627         
628         /* is ntree part of library? */
629         for(newtree=G.main->nodetree.first; newtree; newtree= newtree->id.next)
630                 if(newtree==ntree) break;
631         if(newtree) {
632                 newtree= copy_libblock(ntree);
633         } else {
634                 newtree= MEM_dupallocN(ntree);
635                 copy_libblock_data(&newtree->id, &ntree->id, TRUE); /* copy animdata and ID props */
636         }
637
638         id_us_plus((ID *)newtree->gpd);
639
640         /* in case a running nodetree is copied */
641         newtree->execdata= NULL;
642         
643         newtree->nodes.first= newtree->nodes.last= NULL;
644         newtree->links.first= newtree->links.last= NULL;
645         
646         last = ntree->nodes.last;
647         for(node= ntree->nodes.first; node; node= node->next) {
648                 node->new_node= NULL;
649                 /* nnode= */ nodeCopyNode(newtree, node);       /* sets node->new */
650                 
651                 /* make sure we don't copy new nodes again! */
652                 if (node==last)
653                         break;
654         }
655         
656         /* socket definition for group usage */
657         BLI_duplicatelist(&newtree->inputs, &ntree->inputs);
658         for(gsock= newtree->inputs.first, oldgsock= ntree->inputs.first; gsock; gsock=gsock->next, oldgsock=oldgsock->next) {
659                 oldgsock->new_sock= gsock;
660                 gsock->groupsock = (oldgsock->groupsock ? oldgsock->groupsock->new_sock : NULL);
661                 gsock->default_value = (oldgsock->default_value ? MEM_dupallocN(oldgsock->default_value) : NULL);
662         }
663         BLI_duplicatelist(&newtree->outputs, &ntree->outputs);
664         for(gsock= newtree->outputs.first, oldgsock= ntree->outputs.first; gsock; gsock=gsock->next, oldgsock=oldgsock->next) {
665                 oldgsock->new_sock= gsock;
666                 gsock->groupsock = (oldgsock->groupsock ? oldgsock->groupsock->new_sock : NULL);
667                 gsock->default_value = (oldgsock->default_value ? MEM_dupallocN(oldgsock->default_value) : NULL);
668         }
669         
670         /* copy links */
671         BLI_duplicatelist(&newtree->links, &ntree->links);
672         for(link= newtree->links.first; link; link= link->next) {
673                 link->fromnode = (link->fromnode ? link->fromnode->new_node : NULL);
674                 link->fromsock = (link->fromsock ? link->fromsock->new_sock : NULL);
675                 link->tonode = (link->tonode ? link->tonode->new_node : NULL);
676                 link->tosock = (link->tosock ? link->tosock->new_sock : NULL);
677                 /* update the link socket's pointer */
678                 if (link->tosock)
679                         link->tosock->link = link;
680         }
681         
682         /* update node->parent pointers */
683         for (node=newtree->nodes.first; node; node=node->next) {
684                 if (node->parent)
685                         node->parent = node->parent->new_node;
686         }
687         
688         return newtree;
689 }
690
691 /* use when duplicating scenes */
692 void ntreeSwitchID(bNodeTree *ntree, ID *id_from, ID *id_to)
693 {
694         bNode *node;
695         /* for scene duplication only */
696         for(node= ntree->nodes.first; node; node= node->next) {
697                 if(node->id==id_from) {
698                         node->id= id_to;
699                 }
700         }
701 }
702
703 /* *************** preview *********** */
704 /* if node->preview, then we assume the rect to exist */
705
706 void nodeFreePreview(bNode *node)
707 {
708         if(node->preview) {
709                 if(node->preview->rect)
710                         MEM_freeN(node->preview->rect);
711                 MEM_freeN(node->preview);
712                 node->preview= NULL;
713         }       
714 }
715
716 static void node_init_preview(bNode *node, int xsize, int ysize)
717 {
718         
719         if(node->preview==NULL) {
720                 node->preview= MEM_callocN(sizeof(bNodePreview), "node preview");
721                 //              printf("added preview %s\n", node->name);
722         }
723         
724         /* node previews can get added with variable size this way */
725         if(xsize==0 || ysize==0)
726                 return;
727         
728         /* sanity checks & initialize */
729         if(node->preview->rect) {
730                 if(node->preview->xsize!=xsize && node->preview->ysize!=ysize) {
731                         MEM_freeN(node->preview->rect);
732                         node->preview->rect= NULL;
733                 }
734         }
735         
736         if(node->preview->rect==NULL) {
737                 node->preview->rect= MEM_callocN(4*xsize + xsize*ysize*sizeof(char)*4, "node preview rect");
738                 node->preview->xsize= xsize;
739                 node->preview->ysize= ysize;
740         }
741         /* no clear, makes nicer previews */
742 }
743
744 void ntreeInitPreview(bNodeTree *ntree, int xsize, int ysize)
745 {
746         bNode *node;
747         
748         if(ntree==NULL)
749                 return;
750         
751         for(node= ntree->nodes.first; node; node= node->next) {
752                 if(node->typeinfo->flag & NODE_PREVIEW) /* hrms, check for closed nodes? */
753                         node_init_preview(node, xsize, ysize);
754                 if(node->type==NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
755                         ntreeInitPreview((bNodeTree *)node->id, xsize, ysize);
756         }               
757 }
758
759 static void nodeClearPreview(bNode *node)
760 {
761         if(node->preview && node->preview->rect)
762                 memset(node->preview->rect, 0, MEM_allocN_len(node->preview->rect));
763 }
764
765 /* use it to enforce clear */
766 void ntreeClearPreview(bNodeTree *ntree)
767 {
768         bNode *node;
769         
770         if(ntree==NULL)
771                 return;
772         
773         for(node= ntree->nodes.first; node; node= node->next) {
774                 if(node->typeinfo->flag & NODE_PREVIEW)
775                         nodeClearPreview(node);
776                 if(node->type==NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
777                         ntreeClearPreview((bNodeTree *)node->id);
778         }               
779 }
780
781 /* hack warning! this function is only used for shader previews, and 
782 since it gets called multiple times per pixel for Ztransp we only
783 add the color once. Preview gets cleared before it starts render though */
784 void nodeAddToPreview(bNode *node, float *col, int x, int y, int do_manage)
785 {
786         bNodePreview *preview= node->preview;
787         if(preview) {
788                 if(x>=0 && y>=0) {
789                         if(x<preview->xsize && y<preview->ysize) {
790                                 unsigned char *tar= preview->rect+ 4*((preview->xsize*y) + x);
791                                 
792                                 if(do_manage) {
793                                         tar[0]= FTOCHAR(linearrgb_to_srgb(col[0]));
794                                         tar[1]= FTOCHAR(linearrgb_to_srgb(col[1]));
795                                         tar[2]= FTOCHAR(linearrgb_to_srgb(col[2]));
796                                 }
797                                 else {
798                                         tar[0]= FTOCHAR(col[0]);
799                                         tar[1]= FTOCHAR(col[1]);
800                                         tar[2]= FTOCHAR(col[2]);
801                                 }
802                                 tar[3]= FTOCHAR(col[3]);
803                         }
804                         //else printf("prv out bound x y %d %d\n", x, y);
805                 }
806                 //else printf("prv out bound x y %d %d\n", x, y);
807         }
808 }
809
810 /* ************** Free stuff ********** */
811
812 /* goes over entire tree */
813 void nodeUnlinkNode(bNodeTree *ntree, bNode *node)
814 {
815         bNodeLink *link, *next;
816         bNodeSocket *sock;
817         ListBase *lb;
818         
819         for(link= ntree->links.first; link; link= next) {
820                 next= link->next;
821                 
822                 if(link->fromnode==node) {
823                         lb= &node->outputs;
824                         if (link->tonode)
825                                 link->tonode->update |= NODE_UPDATE;
826                 }
827                 else if(link->tonode==node)
828                         lb= &node->inputs;
829                 else
830                         lb= NULL;
831
832                 if(lb) {
833                         for(sock= lb->first; sock; sock= sock->next) {
834                                 if(link->fromsock==sock || link->tosock==sock)
835                                         break;
836                         }
837                         if(sock) {
838                                 nodeRemLink(ntree, link);
839                         }
840                 }
841         }
842 }
843
844 static void node_unlink_attached(bNodeTree *ntree, bNode *parent)
845 {
846         bNode *node;
847         for (node=ntree->nodes.first; node; node=node->next) {
848                 if (node->parent == parent)
849                         nodeDetachNode(node);
850         }
851 }
852
853 void nodeFreeNode(bNodeTree *ntree, bNode *node)
854 {
855         bNodeTreeType *treetype= ntreeGetType(ntree->type);
856         bNodeSocket *sock, *nextsock;
857         
858         /* remove all references to this node */
859         nodeUnlinkNode(ntree, node);
860         node_unlink_attached(ntree, node);
861         
862         BLI_remlink(&ntree->nodes, node);
863
864         /* since it is called while free database, node->id is undefined */
865         
866         if (treetype->free_node_cache)
867                 treetype->free_node_cache(ntree, node);
868         
869         for (sock=node->inputs.first; sock; sock = nextsock) {
870                 nextsock = sock->next;
871                 if (sock->default_value)
872                         MEM_freeN(sock->default_value);
873                 MEM_freeN(sock);
874         }
875         for (sock=node->outputs.first; sock; sock = nextsock) {
876                 nextsock = sock->next;
877                 if (sock->default_value)
878                         MEM_freeN(sock->default_value);
879                 MEM_freeN(sock);
880         }
881
882         nodeFreePreview(node);
883
884         if(node->typeinfo && node->typeinfo->freestoragefunc) {
885                 node->typeinfo->freestoragefunc(node);
886         }
887
888         MEM_freeN(node);
889         
890         ntree->update |= NTREE_UPDATE_NODES;
891 }
892
893 /* do not free ntree itself here, free_libblock calls this function too */
894 void ntreeFreeTree(bNodeTree *ntree)
895 {
896         bNode *node, *next;
897         bNodeSocket *sock;
898         
899         if(ntree==NULL) return;
900         
901         /* XXX hack! node trees should not store execution graphs at all.
902          * This should be removed when old tree types no longer require it.
903          * Currently the execution data for texture nodes remains in the tree
904          * after execution, until the node tree is updated or freed.
905          */
906         if (ntree->execdata) {
907                 switch (ntree->type) {
908                 case NTREE_COMPOSIT:
909                         ntreeCompositEndExecTree(ntree->execdata, 1);
910                         break;
911                 case NTREE_SHADER:
912                         ntreeShaderEndExecTree(ntree->execdata, 1);
913                         break;
914                 case NTREE_TEXTURE:
915                         ntreeTexEndExecTree(ntree->execdata, 1);
916                         break;
917                 }
918         }
919         
920         BKE_free_animdata((ID *)ntree);
921         
922         id_us_min((ID *)ntree->gpd);
923
924         BLI_freelistN(&ntree->links);   /* do first, then unlink_node goes fast */
925         
926         for(node= ntree->nodes.first; node; node= next) {
927                 next= node->next;
928                 nodeFreeNode(ntree, node);
929         }
930         
931         for (sock=ntree->inputs.first; sock; sock=sock->next)
932                 if (sock->default_value)
933                         MEM_freeN(sock->default_value);
934         BLI_freelistN(&ntree->inputs);
935         for (sock=ntree->outputs.first; sock; sock=sock->next)
936                 if (sock->default_value)
937                         MEM_freeN(sock->default_value);
938         BLI_freelistN(&ntree->outputs);
939 }
940
941 void ntreeFreeCache(bNodeTree *ntree)
942 {
943         bNodeTreeType *treetype;
944         
945         if(ntree==NULL) return;
946         
947         treetype= ntreeGetType(ntree->type);
948         if (treetype->free_cache)
949                 treetype->free_cache(ntree);
950 }
951
952 void ntreeSetOutput(bNodeTree *ntree)
953 {
954         bNode *node;
955
956         /* find the active outputs, might become tree type dependant handler */
957         for(node= ntree->nodes.first; node; node= node->next) {
958                 if(node->typeinfo->nclass==NODE_CLASS_OUTPUT) {
959                         bNode *tnode;
960                         int output= 0;
961                         
962                         /* we need a check for which output node should be tagged like this, below an exception */
963                         if(node->type==CMP_NODE_OUTPUT_FILE)
964                            continue;
965                            
966                         /* there is more types having output class, each one is checked */
967                         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next) {
968                                 if(tnode->typeinfo->nclass==NODE_CLASS_OUTPUT) {
969                                         
970                                         if(ntree->type==NTREE_COMPOSIT) {
971                                                         
972                                                 /* same type, exception for viewer */
973                                                 if(tnode->type==node->type ||
974                                                    (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER) &&
975                                                         ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))) {
976                                                         if(tnode->flag & NODE_DO_OUTPUT) {
977                                                                 output++;
978                                                                 if(output>1)
979                                                                         tnode->flag &= ~NODE_DO_OUTPUT;
980                                                         }
981                                                 }
982                                         }
983                                         else {
984                                                 /* same type */
985                                                 if(tnode->type==node->type) {
986                                                         if(tnode->flag & NODE_DO_OUTPUT) {
987                                                                 output++;
988                                                                 if(output>1)
989                                                                         tnode->flag &= ~NODE_DO_OUTPUT;
990                                                         }
991                                                 }
992                                         }
993                                 }
994                         }
995                         if(output==0)
996                                 node->flag |= NODE_DO_OUTPUT;
997                 }
998         }
999         
1000         /* here we could recursively set which nodes have to be done,
1001                 might be different for editor or for "real" use... */
1002 }
1003
1004 typedef struct MakeLocalCallData {
1005         ID *group_id;
1006         ID *new_id;
1007         int lib, local;
1008 } MakeLocalCallData;
1009
1010 static void ntreeMakeLocal_CheckLocal(void *calldata, ID *owner_id, bNodeTree *ntree)
1011 {
1012         MakeLocalCallData *cd= (MakeLocalCallData*)calldata;
1013         bNode *node;
1014         
1015         /* find if group is in tree */
1016         for(node= ntree->nodes.first; node; node= node->next) {
1017                 if(node->id == cd->group_id) {
1018                         if(owner_id->lib) cd->lib= 1;
1019                         else cd->local= 1;
1020                 }
1021         }
1022 }
1023
1024 static void ntreeMakeLocal_LinkNew(void *calldata, ID *owner_id, bNodeTree *ntree)
1025 {
1026         MakeLocalCallData *cd= (MakeLocalCallData*)calldata;
1027         bNode *node;
1028         
1029         /* find if group is in tree */
1030         for(node= ntree->nodes.first; node; node= node->next) {
1031                 if(node->id == cd->group_id) {
1032                         if(owner_id->lib==NULL) {
1033                                 node->id= cd->new_id;
1034                                 cd->new_id->us++;
1035                                 cd->group_id->us--;
1036                         }
1037                 }
1038         }
1039 }
1040
1041 void ntreeMakeLocal(bNodeTree *ntree)
1042 {
1043         Main *bmain= G.main;
1044         bNodeTreeType *treetype= ntreeGetType(ntree->type);
1045         MakeLocalCallData cd;
1046         
1047         /* - only lib users: do nothing
1048                 * - only local users: set flag
1049                 * - mixed: make copy
1050                 */
1051         
1052         if(ntree->id.lib==NULL) return;
1053         if(ntree->id.us==1) {
1054                 id_clear_lib_data(bmain, (ID *)ntree);
1055                 return;
1056         }
1057         
1058         /* now check users of groups... again typedepending, callback... */
1059         cd.group_id = &ntree->id;
1060         cd.new_id = NULL;
1061         cd.local = 0;
1062         cd.lib = 0;
1063         
1064         treetype->foreach_nodetree(G.main, &cd, &ntreeMakeLocal_CheckLocal);
1065         
1066         /* if all users are local, we simply make tree local */
1067         if(cd.local && cd.lib==0) {
1068                 id_clear_lib_data(bmain, (ID *)ntree);
1069         }
1070         else if(cd.local && cd.lib) {
1071                 /* this is the mixed case, we copy the tree and assign it to local users */
1072                 bNodeTree *newtree= ntreeCopyTree(ntree);
1073                 
1074                 newtree->id.us= 0;
1075                 
1076
1077                 cd.new_id = &newtree->id;
1078                 treetype->foreach_nodetree(G.main, &cd, &ntreeMakeLocal_LinkNew);
1079         }
1080 }
1081
1082 int ntreeNodeExists(bNodeTree *ntree, bNode *testnode)
1083 {
1084         bNode *node= ntree->nodes.first;
1085         for(; node; node= node->next)
1086                 if(node==testnode)
1087                         return 1;
1088         return 0;
1089 }
1090
1091 int ntreeOutputExists(bNode *node, bNodeSocket *testsock)
1092 {
1093         bNodeSocket *sock= node->outputs.first;
1094         for(; sock; sock= sock->next)
1095                 if(sock==testsock)
1096                         return 1;
1097         return 0;
1098 }
1099
1100 /* returns localized tree for execution in threads */
1101 bNodeTree *ntreeLocalize(bNodeTree *ntree)
1102 {
1103         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1104
1105         bNodeTree *ltree;
1106         bNode *node;
1107         
1108         bAction *action_backup= NULL, *tmpact_backup= NULL;
1109         
1110         /* Workaround for copying an action on each render!
1111          * set action to NULL so animdata actions dont get copied */
1112         AnimData *adt= BKE_animdata_from_id(&ntree->id);
1113
1114         if(adt) {
1115                 action_backup= adt->action;
1116                 tmpact_backup= adt->tmpact;
1117
1118                 adt->action= NULL;
1119                 adt->tmpact= NULL;
1120         }
1121
1122         /* node copy func */
1123         ltree= ntreeCopyTree(ntree);
1124
1125         if(adt) {
1126                 AnimData *ladt= BKE_animdata_from_id(&ltree->id);
1127
1128                 adt->action= ladt->action= action_backup;
1129                 adt->tmpact= ladt->tmpact= tmpact_backup;
1130
1131                 if(action_backup) action_backup->id.us++;
1132                 if(tmpact_backup) tmpact_backup->id.us++;
1133                 
1134         }
1135         /* end animdata uglyness */
1136
1137         /* ensures only a single output node is enabled */
1138         ntreeSetOutput(ntree);
1139
1140         for(node= ntree->nodes.first; node; node= node->next) {
1141                 /* store new_node pointer to original */
1142                 node->new_node->new_node= node;
1143         }
1144
1145         if (ntreetype->localize)
1146                 ntreetype->localize(ltree, ntree);
1147
1148         return ltree;
1149 }
1150
1151 /* sync local composite with real tree */
1152 /* local tree is supposed to be running, be careful moving previews! */
1153 /* is called by jobs manager, outside threads, so it doesnt happen during draw */
1154 void ntreeLocalSync(bNodeTree *localtree, bNodeTree *ntree)
1155 {
1156         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1157
1158         if (ntreetype->local_sync)
1159                 ntreetype->local_sync(localtree, ntree);
1160 }
1161
1162 /* merge local tree results back, and free local tree */
1163 /* we have to assume the editor already changed completely */
1164 void ntreeLocalMerge(bNodeTree *localtree, bNodeTree *ntree)
1165 {
1166         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1167         bNode *lnode;
1168         
1169         /* move over the compbufs and previews */
1170         for(lnode= localtree->nodes.first; lnode; lnode= lnode->next) {
1171                 if(ntreeNodeExists(ntree, lnode->new_node)) {
1172                         if(lnode->preview && lnode->preview->rect) {
1173                                 nodeFreePreview(lnode->new_node);
1174                                 lnode->new_node->preview= lnode->preview;
1175                                 lnode->preview= NULL;
1176                         }
1177                 }
1178         }
1179
1180         if (ntreetype->local_merge)
1181                 ntreetype->local_merge(localtree, ntree);
1182
1183         ntreeFreeTree(localtree);
1184         MEM_freeN(localtree);
1185 }
1186
1187 /* ************ find stuff *************** */
1188
1189 int ntreeHasType(bNodeTree *ntree, int type)
1190 {
1191         bNode *node;
1192         
1193         if(ntree)
1194                 for(node= ntree->nodes.first; node; node= node->next)
1195                         if(node->type == type)
1196                                 return 1;
1197         return 0;
1198 }
1199
1200 bNodeLink *nodeFindLink(bNodeTree *ntree, bNodeSocket *from, bNodeSocket *to)
1201 {
1202         bNodeLink *link;
1203         
1204         for(link= ntree->links.first; link; link= link->next) {
1205                 if(link->fromsock==from && link->tosock==to)
1206                         return link;
1207                 if(link->fromsock==to && link->tosock==from)    /* hrms? */
1208                         return link;
1209         }
1210         return NULL;
1211 }
1212
1213 int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock)
1214 {
1215         bNodeLink *link;
1216         int tot= 0;
1217         
1218         for(link= ntree->links.first; link; link= link->next) {
1219                 if(link->fromsock==sock || link->tosock==sock)
1220                         tot++;
1221         }
1222         return tot;
1223 }
1224
1225 bNode *nodeGetActive(bNodeTree *ntree)
1226 {
1227         bNode *node;
1228         
1229         if(ntree==NULL) return NULL;
1230         
1231         for(node= ntree->nodes.first; node; node= node->next)
1232                 if(node->flag & NODE_ACTIVE)
1233                         break;
1234         return node;
1235 }
1236
1237 /* two active flags, ID nodes have special flag for buttons display */
1238 bNode *nodeGetActiveID(bNodeTree *ntree, short idtype)
1239 {
1240         bNode *node;
1241         
1242         if(ntree==NULL) return NULL;
1243
1244         /* check for group edit */
1245         for(node= ntree->nodes.first; node; node= node->next)
1246                 if(node->flag & NODE_GROUP_EDIT)
1247                         break;
1248
1249         if(node)
1250                 ntree= (bNodeTree*)node->id;
1251         
1252         /* now find active node with this id */
1253         for(node= ntree->nodes.first; node; node= node->next)
1254                 if(node->id && GS(node->id->name)==idtype)
1255                         if(node->flag & NODE_ACTIVE_ID)
1256                                 break;
1257
1258         return node;
1259 }
1260
1261 int nodeSetActiveID(bNodeTree *ntree, short idtype, ID *id)
1262 {
1263         bNode *node;
1264         int ok= FALSE;
1265
1266         if(ntree==NULL) return ok;
1267
1268         /* check for group edit */
1269         for(node= ntree->nodes.first; node; node= node->next)
1270                 if(node->flag & NODE_GROUP_EDIT)
1271                         break;
1272
1273         if(node)
1274                 ntree= (bNodeTree*)node->id;
1275
1276         /* now find active node with this id */
1277         for(node= ntree->nodes.first; node; node= node->next) {
1278                 if(node->id && GS(node->id->name)==idtype) {
1279                         if(id && ok==FALSE && node->id==id) {
1280                                 node->flag |= NODE_ACTIVE_ID;
1281                                 ok= TRUE;
1282                         } else {
1283                                 node->flag &= ~NODE_ACTIVE_ID;
1284                         }
1285                 }
1286         }
1287
1288         return ok;
1289 }
1290
1291
1292 /* two active flags, ID nodes have special flag for buttons display */
1293 void nodeClearActiveID(bNodeTree *ntree, short idtype)
1294 {
1295         bNode *node;
1296         
1297         if(ntree==NULL) return;
1298         
1299         for(node= ntree->nodes.first; node; node= node->next)
1300                 if(node->id && GS(node->id->name)==idtype)
1301                         node->flag &= ~NODE_ACTIVE_ID;
1302 }
1303
1304 /* two active flags, ID nodes have special flag for buttons display */
1305 void nodeSetActive(bNodeTree *ntree, bNode *node)
1306 {
1307         bNode *tnode;
1308         
1309         /* make sure only one node is active, and only one per ID type */
1310         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next) {
1311                 tnode->flag &= ~NODE_ACTIVE;
1312                 
1313                 if(node->id && tnode->id) {
1314                         if(GS(node->id->name) == GS(tnode->id->name))
1315                                 tnode->flag &= ~NODE_ACTIVE_ID;
1316                 }
1317         }
1318         
1319         node->flag |= NODE_ACTIVE;
1320         if(node->id)
1321                 node->flag |= NODE_ACTIVE_ID;
1322 }
1323
1324 /* use flags are not persistent yet, groups might need different tagging, so we do it each time
1325    when we need to get this info */
1326 void ntreeSocketUseFlags(bNodeTree *ntree)
1327 {
1328         bNode *node;
1329         bNodeSocket *sock;
1330         bNodeLink *link;
1331         
1332         /* clear flags */
1333         for(node= ntree->nodes.first; node; node= node->next) {
1334                 for(sock= node->inputs.first; sock; sock= sock->next)
1335                         sock->flag &= ~SOCK_IN_USE;
1336                 for(sock= node->outputs.first; sock; sock= sock->next)
1337                         sock->flag &= ~SOCK_IN_USE;
1338         }
1339         
1340         /* tag all thats in use */
1341         for(link= ntree->links.first; link; link= link->next) {
1342         
1343                 if(link->fromsock) // FIXME, see below
1344                         link->fromsock->flag |= SOCK_IN_USE;
1345                 if(link->tosock) // FIXME This can be NULL, when dragging a new link in the UI, should probably copy the node tree for preview render - campbell
1346                         link->tosock->flag |= SOCK_IN_USE;
1347         }
1348 }
1349
1350 /* ************** dependency stuff *********** */
1351
1352 /* node is guaranteed to be not checked before */
1353 static int node_get_deplist_recurs(bNode *node, bNode ***nsort)
1354 {
1355         bNode *fromnode;
1356         bNodeSocket *sock;
1357         int level = 0xFFF;
1358         
1359         node->done= 1;
1360         
1361         /* check linked nodes */
1362         for(sock= node->inputs.first; sock; sock= sock->next) {
1363                 if(sock->link) {
1364                         fromnode= sock->link->fromnode;
1365                         if(fromnode) {
1366                                 if (fromnode->done==0)
1367                                         fromnode->level= node_get_deplist_recurs(fromnode, nsort);
1368                                 if (fromnode->level <= level)
1369                                         level = fromnode->level - 1;
1370                         }
1371                 }
1372         }
1373         
1374         /* check parent node */
1375         if (node->parent) {
1376                 if (node->parent->done==0)
1377                         node->parent->level= node_get_deplist_recurs(node->parent, nsort);
1378                 if (node->parent->level <= level)
1379                         level = node->parent->level - 1;
1380         }
1381         
1382         if (nsort) {
1383                 **nsort= node;
1384                 (*nsort)++;
1385         }
1386         
1387         return level;
1388 }
1389
1390 void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, int *totnodes)
1391 {
1392         bNode *node, **nsort;
1393         
1394         *totnodes=0;
1395         
1396         /* first clear data */
1397         for(node= ntree->nodes.first; node; node= node->next) {
1398                 node->done= 0;
1399                 (*totnodes)++;
1400         }
1401         if(*totnodes==0) {
1402                 *deplist = NULL;
1403                 return;
1404         }
1405         
1406         nsort= *deplist= MEM_callocN((*totnodes)*sizeof(bNode*), "sorted node array");
1407         
1408         /* recursive check */
1409         for(node= ntree->nodes.first; node; node= node->next) {
1410                 if(node->done==0) {
1411                         node->level= node_get_deplist_recurs(node, &nsort);
1412                 }
1413         }
1414 }
1415
1416 static void ntree_update_link_pointers(bNodeTree *ntree)
1417 {
1418         bNode *node;
1419         bNodeSocket *sock;
1420         bNodeLink *link;
1421         
1422         /* first clear data */
1423         for(node= ntree->nodes.first; node; node= node->next) {
1424                 for(sock= node->inputs.first; sock; sock= sock->next)
1425                         sock->link= NULL;
1426         }
1427         /* clear socket links */
1428         for(sock= ntree->outputs.first; sock; sock= sock->next)
1429                 sock->link= NULL;
1430
1431         for(link= ntree->links.first; link; link= link->next) {
1432                 if (link->tosock)
1433                         link->tosock->link= link;
1434         }
1435 }
1436
1437 static void ntree_validate_links(bNodeTree *ntree)
1438 {
1439         bNodeTreeType *ntreetype = ntreeGetType(ntree->type);
1440         bNodeLink *link;
1441         
1442         for (link = ntree->links.first; link; link = link->next) {
1443                 link->flag |= NODE_LINK_VALID;
1444                 if (link->fromnode && link->tonode && link->fromnode->level <= link->tonode->level)
1445                         link->flag &= ~NODE_LINK_VALID;
1446                 else if (ntreetype->validate_link) {
1447                         if (!ntreetype->validate_link(ntree, link))
1448                                 link->flag &= ~NODE_LINK_VALID;
1449                 }
1450         }
1451 }
1452
1453 static void ntree_verify_nodes_cb(void *calldata, struct ID *UNUSED(owner_id), struct bNodeTree *ntree)
1454 {
1455         ID *id= (ID*)calldata;
1456         bNode *node;
1457         
1458         for (node=ntree->nodes.first; node; node=node->next)
1459                 if (node->typeinfo->verifyfunc)
1460                         node->typeinfo->verifyfunc(ntree, node, id);
1461 }
1462
1463 void ntreeVerifyNodes(struct Main *main, struct ID *id)
1464 {
1465         bNodeTreeType *ntreetype;
1466         bNodeTree *ntree;
1467         int n;
1468         
1469         for (n=0; n < NUM_NTREE_TYPES; ++n) {
1470                 ntreetype= ntreeGetType(n);
1471                 if (ntreetype && ntreetype->foreach_nodetree)
1472                         ntreetype->foreach_nodetree(main, id, ntree_verify_nodes_cb);
1473         }
1474         for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
1475                 ntree_verify_nodes_cb(id, NULL, ntree);
1476 }
1477
1478 void ntreeUpdateTree(bNodeTree *ntree)
1479 {
1480         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1481         bNode *node;
1482         bNode **deplist;
1483         int totnodes, n;
1484         
1485         ntree_update_link_pointers(ntree);
1486         
1487         /* also updates the node level! */
1488         ntreeGetDependencyList(ntree, &deplist, &totnodes);
1489         
1490         if (deplist) {
1491                 /* update individual nodes */
1492                 for (n=0; n < totnodes; ++n) {
1493                         node = deplist[n];
1494                         
1495                         /* node tree update tags override individual node update flags */
1496                         if ((node->update & NODE_UPDATE) || (ntree->update & NTREE_UPDATE)) {
1497                                 if (ntreetype->update_node)
1498                                         ntreetype->update_node(ntree, node);
1499                                 else if (node->typeinfo->updatefunc)
1500                                         node->typeinfo->updatefunc(ntree, node);
1501                         }
1502                         /* clear update flag */
1503                         node->update = 0;
1504                 }
1505                 
1506                 MEM_freeN(deplist);
1507         }
1508         
1509         /* general tree updates */
1510         if (ntree->update & (NTREE_UPDATE_LINKS|NTREE_UPDATE_NODES)) {
1511                 ntree_validate_links(ntree);
1512         }
1513         
1514         /* update tree */
1515         if (ntreetype->update)
1516                 ntreetype->update(ntree);
1517         else {
1518                 /* Trees can be associated with a specific node type (i.e. group nodes),
1519                  * in that case a tree update function may be defined by that node type.
1520                  */
1521                 bNodeType *ntype= node_get_type(ntree, ntree->nodetype);
1522                 if (ntype && ntype->updatetreefunc)
1523                         ntype->updatetreefunc(ntree);
1524         }
1525         
1526         /* XXX hack, should be done by depsgraph!! */
1527         ntreeVerifyNodes(G.main, &ntree->id);
1528         
1529         /* clear the update flag */
1530         ntree->update = 0;
1531 }
1532
1533 void nodeUpdate(bNodeTree *ntree, bNode *node)
1534 {
1535         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1536         
1537         if (ntreetype->update_node)
1538                 ntreetype->update_node(ntree, node);
1539         else if (node->typeinfo->updatefunc)
1540                 node->typeinfo->updatefunc(ntree, node);
1541         /* clear update flag */
1542         node->update = 0;
1543 }
1544
1545 int nodeUpdateID(bNodeTree *ntree, ID *id)
1546 {
1547         bNodeTreeType *ntreetype;
1548         bNode *node;
1549         int change = FALSE;
1550         
1551         if(ELEM(NULL, id, ntree))
1552                 return change;
1553         
1554         ntreetype = ntreeGetType(ntree->type);
1555         
1556         if (ntreetype->update_node) {
1557                 for(node= ntree->nodes.first; node; node= node->next) {
1558                         if(node->id==id) {
1559                                 change = TRUE;
1560                                 ntreetype->update_node(ntree, node);
1561                                 /* clear update flag */
1562                                 node->update = 0;
1563                         }
1564                 }
1565         }
1566         else {
1567                 for(node= ntree->nodes.first; node; node= node->next) {
1568                         if(node->id==id) {
1569                                 change = TRUE;
1570                                 if (node->typeinfo->updatefunc)
1571                                         node->typeinfo->updatefunc(ntree, node);
1572                                 /* clear update flag */
1573                                 node->update = 0;
1574                         }
1575                 }
1576         }
1577         
1578         return change;
1579 }
1580
1581
1582 /* ************* node type access ********** */
1583
1584 int nodeValid(bNodeTree *ntree, bNodeTemplate *ntemp)
1585 {
1586         bNodeType *ntype= node_get_type(ntree, ntemp->type);
1587         if (ntype) {
1588                 if (ntype->validfunc)
1589                         return ntype->validfunc(ntree, ntemp);
1590                 else
1591                         return 1;
1592         }
1593         else
1594                 return 0;
1595 }
1596
1597 const char* nodeLabel(bNode *node)
1598 {
1599         if (node->label[0]!='\0')
1600                 return node->label;
1601         else if (node->typeinfo->labelfunc)
1602                 return node->typeinfo->labelfunc(node);
1603         else
1604                 return node->typeinfo->name;
1605 }
1606
1607 struct bNodeTree *nodeGroupEditGet(struct bNode *node)
1608 {
1609         if (node->typeinfo->group_edit_get)
1610                 return node->typeinfo->group_edit_get(node);
1611         else
1612                 return NULL;
1613 }
1614
1615 struct bNodeTree *nodeGroupEditSet(struct bNode *node, int edit)
1616 {
1617         if (node->typeinfo->group_edit_set)
1618                 return node->typeinfo->group_edit_set(node, edit);
1619         else if (node->typeinfo->group_edit_get)
1620                 return node->typeinfo->group_edit_get(node);
1621         else
1622                 return NULL;
1623 }
1624
1625 void nodeGroupEditClear(struct bNode *node)
1626 {
1627         if (node->typeinfo->group_edit_clear)
1628                 node->typeinfo->group_edit_clear(node);
1629 }
1630
1631 struct bNodeTemplate nodeMakeTemplate(struct bNode *node)
1632 {
1633         bNodeTemplate ntemp;
1634         if (node->typeinfo->templatefunc)
1635                 return node->typeinfo->templatefunc(node);
1636         else {
1637                 ntemp.type = node->type;
1638                 return ntemp;
1639         }
1640 }
1641
1642 void node_type_base(bNodeType *ntype, int type, const char *name, short nclass, short flag)
1643 {
1644         memset(ntype, 0, sizeof(bNodeType));
1645         
1646         ntype->type = type;
1647         BLI_strncpy(ntype->name, name, sizeof(ntype->name));
1648         ntype->nclass = nclass;
1649         ntype->flag = flag;
1650         
1651         /* default size values */
1652         ntype->width = 140;
1653         ntype->minwidth = 100;
1654         ntype->maxwidth = 320;
1655         ntype->height = 100;
1656         ntype->minheight = 30;
1657         ntype->maxheight = FLT_MAX;
1658 }
1659
1660 void node_type_socket_templates(struct bNodeType *ntype, struct bNodeSocketTemplate *inputs, struct bNodeSocketTemplate *outputs)
1661 {
1662         ntype->inputs = inputs;
1663         ntype->outputs = outputs;
1664 }
1665
1666 void node_type_init(struct bNodeType *ntype, void (*initfunc)(struct bNodeTree *ntree, struct bNode *node, struct bNodeTemplate *ntemp))
1667 {
1668         ntype->initfunc = initfunc;
1669 }
1670
1671 void node_type_valid(struct bNodeType *ntype, int (*validfunc)(struct bNodeTree *ntree, struct bNodeTemplate *ntemp))
1672 {
1673         ntype->validfunc = validfunc;
1674 }
1675
1676 void node_type_size(struct bNodeType *ntype, int width, int minwidth, int maxwidth)
1677 {
1678         ntype->width = width;
1679         ntype->minwidth = minwidth;
1680         if (maxwidth <= minwidth)
1681                 ntype->maxwidth = FLT_MAX;
1682         else
1683                 ntype->maxwidth = maxwidth;
1684 }
1685
1686 void node_type_storage(bNodeType *ntype, const char *storagename, void (*freestoragefunc)(struct bNode *), void (*copystoragefunc)(struct bNode *, struct bNode *))
1687 {
1688         if (storagename)
1689                 BLI_strncpy(ntype->storagename, storagename, sizeof(ntype->storagename));
1690         else
1691                 ntype->storagename[0] = '\0';
1692         ntype->copystoragefunc = copystoragefunc;
1693         ntype->freestoragefunc = freestoragefunc;
1694 }
1695
1696 void node_type_label(struct bNodeType *ntype, const char *(*labelfunc)(struct bNode *))
1697 {
1698         ntype->labelfunc = labelfunc;
1699 }
1700
1701 void node_type_template(struct bNodeType *ntype, struct bNodeTemplate (*templatefunc)(struct bNode *))
1702 {
1703         ntype->templatefunc = templatefunc;
1704 }
1705
1706 void node_type_update(struct bNodeType *ntype,
1707                                           void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node),
1708                                           void (*verifyfunc)(struct bNodeTree *ntree, struct bNode *node, struct ID *id))
1709 {
1710         ntype->updatefunc = updatefunc;
1711         ntype->verifyfunc = verifyfunc;
1712 }
1713
1714 void node_type_tree(struct bNodeType *ntype, void (*inittreefunc)(struct bNodeTree *), void (*updatetreefunc)(struct bNodeTree *))
1715 {
1716         ntype->inittreefunc = inittreefunc;
1717         ntype->updatetreefunc = updatetreefunc;
1718 }
1719
1720 void node_type_group_edit(struct bNodeType *ntype,
1721                                                   struct bNodeTree *(*group_edit_get)(struct bNode *node),
1722                                                   struct bNodeTree *(*group_edit_set)(struct bNode *node, int edit),
1723                                                   void (*group_edit_clear)(struct bNode *node))
1724 {
1725         ntype->group_edit_get = group_edit_get;
1726         ntype->group_edit_set = group_edit_set;
1727         ntype->group_edit_clear = group_edit_clear;
1728 }
1729
1730 void node_type_exec(struct bNodeType *ntype, void (*execfunc)(void *data, struct bNode *, struct bNodeStack **, struct bNodeStack **))
1731 {
1732         ntype->execfunc = execfunc;
1733 }
1734
1735 void node_type_exec_new(struct bNodeType *ntype,
1736                                                 void *(*initexecfunc)(struct bNode *node),
1737                                                 void (*freeexecfunc)(struct bNode *node, void *nodedata),
1738                                                 void (*newexecfunc)(void *data, int thread, struct bNode *, void *nodedata, struct bNodeStack **, struct bNodeStack **))
1739 {
1740         ntype->initexecfunc = initexecfunc;
1741         ntype->freeexecfunc = freeexecfunc;
1742         ntype->newexecfunc = newexecfunc;
1743 }
1744
1745 void node_type_gpu(struct bNodeType *ntype, int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out))
1746 {
1747         ntype->gpufunc = gpufunc;
1748 }
1749
1750 void node_type_gpu_ext(struct bNodeType *ntype, int (*gpuextfunc)(struct GPUMaterial *mat, struct bNode *node, void *nodedata, struct GPUNodeStack *in, struct GPUNodeStack *out))
1751 {
1752         ntype->gpuextfunc = gpuextfunc;
1753 }
1754
1755 void node_type_compatibility(struct bNodeType *ntype, short compatibility)
1756 {
1757         ntype->compatibility = compatibility;
1758 }
1759
1760 static bNodeType *is_nodetype_registered(ListBase *typelist, int type) 
1761 {
1762         bNodeType *ntype= typelist->first;
1763         
1764         for(;ntype; ntype= ntype->next )
1765                 if(ntype->type==type)
1766                         return ntype;
1767         
1768         return NULL;
1769 }
1770
1771 void nodeRegisterType(ListBase *typelist, bNodeType *ntype) 
1772 {
1773         bNodeType *found= is_nodetype_registered(typelist, ntype->type);
1774         
1775         if(found==NULL)
1776                 BLI_addtail(typelist, ntype);
1777 }
1778
1779 static void registerCompositNodes(ListBase *ntypelist)
1780 {
1781         register_node_type_frame(ntypelist);
1782         
1783         register_node_type_cmp_group(ntypelist);
1784 //      register_node_type_cmp_forloop(ntypelist);
1785 //      register_node_type_cmp_whileloop(ntypelist);
1786         
1787         register_node_type_cmp_rlayers(ntypelist);
1788         register_node_type_cmp_image(ntypelist);
1789         register_node_type_cmp_texture(ntypelist);
1790         register_node_type_cmp_value(ntypelist);
1791         register_node_type_cmp_rgb(ntypelist);
1792         register_node_type_cmp_curve_time(ntypelist);
1793         
1794         register_node_type_cmp_composite(ntypelist);
1795         register_node_type_cmp_viewer(ntypelist);
1796         register_node_type_cmp_splitviewer(ntypelist);
1797         register_node_type_cmp_output_file(ntypelist);
1798         register_node_type_cmp_view_levels(ntypelist);
1799         
1800         register_node_type_cmp_curve_rgb(ntypelist);
1801         register_node_type_cmp_mix_rgb(ntypelist);
1802         register_node_type_cmp_hue_sat(ntypelist);
1803         register_node_type_cmp_brightcontrast(ntypelist);
1804         register_node_type_cmp_gamma(ntypelist);
1805         register_node_type_cmp_invert(ntypelist);
1806         register_node_type_cmp_alphaover(ntypelist);
1807         register_node_type_cmp_zcombine(ntypelist);
1808         register_node_type_cmp_colorbalance(ntypelist);
1809         register_node_type_cmp_huecorrect(ntypelist);
1810         
1811         register_node_type_cmp_normal(ntypelist);
1812         register_node_type_cmp_curve_vec(ntypelist);
1813         register_node_type_cmp_map_value(ntypelist);
1814         register_node_type_cmp_normalize(ntypelist);
1815         
1816         register_node_type_cmp_filter(ntypelist);
1817         register_node_type_cmp_blur(ntypelist);
1818         register_node_type_cmp_dblur(ntypelist);
1819         register_node_type_cmp_bilateralblur(ntypelist);
1820         register_node_type_cmp_vecblur(ntypelist);
1821         register_node_type_cmp_dilateerode(ntypelist);
1822         register_node_type_cmp_defocus(ntypelist);
1823         
1824         register_node_type_cmp_valtorgb(ntypelist);
1825         register_node_type_cmp_rgbtobw(ntypelist);
1826         register_node_type_cmp_setalpha(ntypelist);
1827         register_node_type_cmp_idmask(ntypelist);
1828         register_node_type_cmp_math(ntypelist);
1829         register_node_type_cmp_seprgba(ntypelist);
1830         register_node_type_cmp_combrgba(ntypelist);
1831         register_node_type_cmp_sephsva(ntypelist);
1832         register_node_type_cmp_combhsva(ntypelist);
1833         register_node_type_cmp_sepyuva(ntypelist);
1834         register_node_type_cmp_combyuva(ntypelist);
1835         register_node_type_cmp_sepycca(ntypelist);
1836         register_node_type_cmp_combycca(ntypelist);
1837         register_node_type_cmp_premulkey(ntypelist);
1838         
1839         register_node_type_cmp_diff_matte(ntypelist);
1840         register_node_type_cmp_distance_matte(ntypelist);
1841         register_node_type_cmp_chroma_matte(ntypelist);
1842         register_node_type_cmp_color_matte(ntypelist);
1843         register_node_type_cmp_channel_matte(ntypelist);
1844         register_node_type_cmp_color_spill(ntypelist);
1845         register_node_type_cmp_luma_matte(ntypelist);
1846         
1847         register_node_type_cmp_translate(ntypelist);
1848         register_node_type_cmp_rotate(ntypelist);
1849         register_node_type_cmp_scale(ntypelist);
1850         register_node_type_cmp_flip(ntypelist);
1851         register_node_type_cmp_crop(ntypelist);
1852         register_node_type_cmp_displace(ntypelist);
1853         register_node_type_cmp_mapuv(ntypelist);
1854         register_node_type_cmp_glare(ntypelist);
1855         register_node_type_cmp_tonemap(ntypelist);
1856         register_node_type_cmp_lensdist(ntypelist);
1857 }
1858
1859 static void registerShaderNodes(ListBase *ntypelist) 
1860 {
1861         register_node_type_frame(ntypelist);
1862         
1863         register_node_type_sh_group(ntypelist);
1864 //      register_node_type_sh_forloop(ntypelist);
1865 //      register_node_type_sh_whileloop(ntypelist);
1866         
1867         register_node_type_sh_output(ntypelist);
1868         register_node_type_sh_mix_rgb(ntypelist);
1869         register_node_type_sh_valtorgb(ntypelist);
1870         register_node_type_sh_rgbtobw(ntypelist);
1871         register_node_type_sh_normal(ntypelist);
1872         register_node_type_sh_geom(ntypelist);
1873         register_node_type_sh_mapping(ntypelist);
1874         register_node_type_sh_curve_vec(ntypelist);
1875         register_node_type_sh_curve_rgb(ntypelist);
1876         register_node_type_sh_math(ntypelist);
1877         register_node_type_sh_vect_math(ntypelist);
1878         register_node_type_sh_squeeze(ntypelist);
1879         register_node_type_sh_camera(ntypelist);
1880         register_node_type_sh_material(ntypelist);
1881         register_node_type_sh_material_ext(ntypelist);
1882         register_node_type_sh_value(ntypelist);
1883         register_node_type_sh_rgb(ntypelist);
1884         register_node_type_sh_texture(ntypelist);
1885 //      register_node_type_sh_dynamic(ntypelist);
1886         register_node_type_sh_invert(ntypelist);
1887         register_node_type_sh_seprgb(ntypelist);
1888         register_node_type_sh_combrgb(ntypelist);
1889         register_node_type_sh_hue_sat(ntypelist);
1890 }
1891
1892 static void registerTextureNodes(ListBase *ntypelist)
1893 {
1894         register_node_type_frame(ntypelist);
1895         
1896         register_node_type_tex_group(ntypelist);
1897 //      register_node_type_tex_forloop(ntypelist);
1898 //      register_node_type_tex_whileloop(ntypelist);
1899         
1900         register_node_type_tex_math(ntypelist);
1901         register_node_type_tex_mix_rgb(ntypelist);
1902         register_node_type_tex_valtorgb(ntypelist);
1903         register_node_type_tex_rgbtobw(ntypelist);
1904         register_node_type_tex_valtonor(ntypelist);
1905         register_node_type_tex_curve_rgb(ntypelist);
1906         register_node_type_tex_curve_time(ntypelist);
1907         register_node_type_tex_invert(ntypelist);
1908         register_node_type_tex_hue_sat(ntypelist);
1909         register_node_type_tex_coord(ntypelist);
1910         register_node_type_tex_distance(ntypelist);
1911         register_node_type_tex_compose(ntypelist);
1912         register_node_type_tex_decompose(ntypelist);
1913         
1914         register_node_type_tex_output(ntypelist);
1915         register_node_type_tex_viewer(ntypelist);
1916         
1917         register_node_type_tex_checker(ntypelist);
1918         register_node_type_tex_texture(ntypelist);
1919         register_node_type_tex_bricks(ntypelist);
1920         register_node_type_tex_image(ntypelist);
1921         
1922         register_node_type_tex_rotate(ntypelist);
1923         register_node_type_tex_translate(ntypelist);
1924         register_node_type_tex_scale(ntypelist);
1925         register_node_type_tex_at(ntypelist);
1926         
1927         register_node_type_tex_proc_voronoi(ntypelist);
1928         register_node_type_tex_proc_blend(ntypelist);
1929         register_node_type_tex_proc_magic(ntypelist);
1930         register_node_type_tex_proc_marble(ntypelist);
1931         register_node_type_tex_proc_clouds(ntypelist);
1932         register_node_type_tex_proc_wood(ntypelist);
1933         register_node_type_tex_proc_musgrave(ntypelist);
1934         register_node_type_tex_proc_noise(ntypelist);
1935         register_node_type_tex_proc_stucci(ntypelist);
1936         register_node_type_tex_proc_distnoise(ntypelist);
1937 }
1938
1939 static void free_dynamic_typeinfo(bNodeType *ntype)
1940 {
1941         if(ntype->type==NODE_DYNAMIC) {
1942                 if(ntype->inputs) {
1943                         MEM_freeN(ntype->inputs);
1944                 }
1945                 if(ntype->outputs) {
1946                         MEM_freeN(ntype->outputs);
1947                 }
1948                 if(ntype->name) {
1949                         MEM_freeN((void *)ntype->name);
1950                 }
1951         }
1952 }
1953
1954 static void free_typeinfos(ListBase *list)
1955 {
1956         bNodeType *ntype, *next;
1957         for(ntype=list->first; ntype; ntype=next) {
1958                 next = ntype->next;
1959                 
1960                 if(ntype->type==NODE_DYNAMIC)
1961                         free_dynamic_typeinfo(ntype);
1962                 
1963                 if(ntype->needs_free)
1964                         MEM_freeN(ntype);
1965         }
1966 }
1967
1968 void init_nodesystem(void) 
1969 {
1970         registerCompositNodes(&ntreeGetType(NTREE_COMPOSIT)->node_types);
1971         registerShaderNodes(&ntreeGetType(NTREE_SHADER)->node_types);
1972         registerTextureNodes(&ntreeGetType(NTREE_TEXTURE)->node_types);
1973 }
1974
1975 void free_nodesystem(void) 
1976 {
1977         free_typeinfos(&ntreeGetType(NTREE_COMPOSIT)->node_types);
1978         free_typeinfos(&ntreeGetType(NTREE_SHADER)->node_types);
1979         free_typeinfos(&ntreeGetType(NTREE_TEXTURE)->node_types);
1980 }
1981
1982 /* called from unlink_scene, when deleting a scene goes over all scenes
1983  * other than the input, checks if they have render layer nodes referencing
1984  * the to-be-deleted scene, and resets them to NULL. */
1985
1986 /* XXX needs to get current scene then! */
1987 void clear_scene_in_nodes(Main *bmain, Scene *sce)
1988 {
1989         Scene *sce1;
1990         bNode *node;
1991
1992         for(sce1= bmain->scene.first; sce1; sce1=sce1->id.next) {
1993                 if(sce1!=sce) {
1994                         if(sce1->nodetree) {
1995                                 for(node= sce1->nodetree->nodes.first; node; node= node->next) {
1996                                         if(node->type==CMP_NODE_R_LAYERS) {
1997                                                 Scene *nodesce= (Scene *)node->id;
1998                                                 
1999                                                 if (nodesce==sce) node->id = NULL;
2000                                         }
2001                                 }
2002                         }
2003                 }
2004         }
2005 }
2006