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