Camera tracking integration
[blender.git] / source / blender / editors / space_node / node_edit.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): David Millan Escriva, Juho Vepsäläinen, Nathan Letwory
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/space_node/node_edit.c
29  *  \ingroup spnode
30  */
31
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <math.h>
36 #include <string.h>
37 #include <errno.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_ID.h"
42 #include "DNA_lamp_types.h"
43 #include "DNA_material_types.h"
44 #include "DNA_node_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_particle_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_world_types.h"
49
50 #include "BLI_math.h"
51 #include "BLI_blenlib.h"
52 #include "BLI_utildefines.h"
53
54 #include "BKE_context.h"
55 #include "BKE_depsgraph.h"
56 #include "BKE_global.h"
57 #include "BKE_image.h"
58 #include "BKE_library.h"
59 #include "BKE_main.h"
60 #include "BKE_node.h"
61 #include "BKE_material.h"
62 #include "BKE_modifier.h"
63 #include "BKE_paint.h"
64 #include "BKE_screen.h"
65 #include "BKE_texture.h"
66 #include "BKE_report.h"
67
68 #include "RE_pipeline.h"
69
70 #include "IMB_imbuf_types.h"
71
72 #include "ED_node.h"
73 #include "ED_screen.h"
74 #include "ED_space_api.h"
75 #include "ED_render.h"
76
77 #include "RNA_access.h"
78 #include "RNA_define.h"
79 #include "RNA_enum_types.h"
80
81 #include "WM_api.h"
82 #include "WM_types.h"
83
84 #include "UI_interface.h"
85 #include "UI_resources.h"
86 #include "UI_view2d.h"
87
88 #include "IMB_imbuf.h"
89
90 #include "RNA_enum_types.h"
91
92 #include "node_intern.h"
93
94 static EnumPropertyItem socket_in_out_items[] = {
95         { SOCK_IN, "SOCK_IN", 0, "Input", "" },
96         { SOCK_OUT, "SOCK_OUT", 0, "Output", "" },
97         { 0, NULL, 0, NULL, NULL },
98 };
99
100 /* ***************** composite job manager ********************** */
101
102 typedef struct CompoJob {
103         Scene *scene;
104         bNodeTree *ntree;
105         bNodeTree *localtree;
106         short *stop;
107         short *do_update;
108         float *progress;
109 } CompoJob;
110
111 /* called by compo, only to check job 'stop' value */
112 static int compo_breakjob(void *cjv)
113 {
114         CompoJob *cj= cjv;
115         
116         return *(cj->stop);
117 }
118
119 /* called by compo, wmJob sends notifier */
120 static void compo_redrawjob(void *cjv, char *UNUSED(str))
121 {
122         CompoJob *cj= cjv;
123         
124         *(cj->do_update)= 1;
125 }
126
127 static void compo_freejob(void *cjv)
128 {
129         CompoJob *cj= cjv;
130
131         if(cj->localtree) {
132                 ntreeLocalMerge(cj->localtree, cj->ntree);
133         }
134         MEM_freeN(cj);
135 }
136
137 /* only now we copy the nodetree, so adding many jobs while
138    sliding buttons doesn't frustrate */
139 static void compo_initjob(void *cjv)
140 {
141         CompoJob *cj= cjv;
142
143         cj->localtree= ntreeLocalize(cj->ntree);
144 }
145
146 /* called before redraw notifiers, it moves finished previews over */
147 static void compo_updatejob(void *cjv)
148 {
149         CompoJob *cj= cjv;
150         
151         ntreeLocalSync(cj->localtree, cj->ntree);
152 }
153
154 static void compo_progressjob(void *cjv, float progress)
155 {
156         CompoJob *cj= cjv;
157         
158         *(cj->progress) = progress;
159 }
160
161
162 /* only this runs inside thread */
163 static void compo_startjob(void *cjv, short *stop, short *do_update, float *progress)
164 {
165         CompoJob *cj= cjv;
166         bNodeTree *ntree= cj->localtree;
167
168         if(cj->scene->use_nodes==0)
169                 return;
170         
171         cj->stop= stop;
172         cj->do_update= do_update;
173         cj->progress= progress;
174         
175         ntree->test_break= compo_breakjob;
176         ntree->tbh= cj;
177         ntree->stats_draw= compo_redrawjob;
178         ntree->sdh= cj;
179         ntree->progress= compo_progressjob;
180         ntree->prh= cj;
181         
182         // XXX BIF_store_spare();
183         
184         ntreeCompositExecTree(ntree, &cj->scene->r, 1); /* 1 is do_previews */
185         
186         ntree->test_break= NULL;
187         ntree->stats_draw= NULL;
188         ntree->progress= NULL;
189
190 }
191
192 void snode_composite_job(const bContext *C, ScrArea *sa)
193 {
194         SpaceNode *snode= sa->spacedata.first;
195         wmJob *steve;
196         CompoJob *cj;
197
198         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Compositing", WM_JOB_EXCL_RENDER|WM_JOB_PROGRESS);
199         cj= MEM_callocN(sizeof(CompoJob), "compo job");
200         
201         /* customdata for preview thread */
202         cj->scene= CTX_data_scene(C);
203         cj->ntree= snode->nodetree;
204         
205         /* setup job */
206         WM_jobs_customdata(steve, cj, compo_freejob);
207         WM_jobs_timer(steve, 0.1, NC_SCENE, NC_SCENE|ND_COMPO_RESULT);
208         WM_jobs_callbacks(steve, compo_startjob, compo_initjob, compo_updatejob, NULL);
209         
210         WM_jobs_start(CTX_wm_manager(C), steve);
211         
212 }
213
214 /* ***************************************** */
215
216 /* operator poll callback */
217 static int composite_node_active(bContext *C)
218 {
219         if( ED_operator_node_active(C)) {
220                 SpaceNode *snode= CTX_wm_space_node(C);
221                 if(snode->treetype==NTREE_COMPOSIT)
222                         return 1;
223         }
224         return 0;
225 }
226
227 /* also checks for edited groups */
228 static bNode *editnode_get_active(bNodeTree *ntree)
229 {
230         bNode *node;
231         
232         /* check for edited group */
233         for(node= ntree->nodes.first; node; node= node->next)
234                 if(nodeGroupEditGet(node))
235                         break;
236         if(node)
237                 return nodeGetActive((bNodeTree *)node->id);
238         else
239                 return nodeGetActive(ntree);
240 }
241
242 void snode_dag_update(bContext *UNUSED(C), SpaceNode *snode)
243 {
244         DAG_id_tag_update(snode->id, 0);
245 }
246
247 void snode_notify(bContext *C, SpaceNode *snode)
248 {
249         WM_event_add_notifier(C, NC_NODE|NA_EDITED, NULL);
250
251         if(snode->treetype==NTREE_SHADER)
252                 WM_event_add_notifier(C, NC_MATERIAL|ND_NODES, snode->id);
253         else if(snode->treetype==NTREE_COMPOSIT)
254                 WM_event_add_notifier(C, NC_SCENE|ND_NODES, snode->id);
255         else if(snode->treetype==NTREE_TEXTURE)
256                 WM_event_add_notifier(C, NC_TEXTURE|ND_NODES, snode->id);
257 }
258
259 bNode *node_tree_get_editgroup(bNodeTree *nodetree)
260 {
261         bNode *gnode;
262         
263         /* get the groupnode */
264         for(gnode= nodetree->nodes.first; gnode; gnode= gnode->next)
265                 if(nodeGroupEditGet(gnode))
266                         break;
267         return gnode;
268 }
269
270 /* assumes nothing being done in ntree yet, sets the default in/out node */
271 /* called from shading buttons or header */
272 void ED_node_shader_default(Scene *UNUSED(scene), ID *id)
273 {
274         bNode *in, *out;
275         bNodeSocket *fromsock, *tosock;
276         bNodeTree *ntree;
277         bNodeTemplate ntemp;
278         int output_type, shader_type;
279         
280         ntree= ntreeAddTree("Shader Nodetree", NTREE_SHADER, 0);
281
282         switch(GS(id->name)) {
283                 case ID_MA: {
284                         Material *ma= (Material*)id;
285                         ma->nodetree = ntree;
286
287                         output_type = SH_NODE_OUTPUT;
288                         shader_type = SH_NODE_MATERIAL;
289                         break;
290                 }
291                 case ID_WO: {
292                         World *wo= (World*)id;
293                         wo->nodetree = ntree;
294
295                         output_type = SH_NODE_OUTPUT;
296                         shader_type = SH_NODE_MATERIAL;
297                         break;
298                 }
299                 case ID_LA: {
300                         Lamp *la= (Lamp*)id;
301                         la->nodetree = ntree;
302
303                         output_type = SH_NODE_OUTPUT;
304                         shader_type = SH_NODE_MATERIAL;
305                         break;
306                 }
307                 default:
308                         printf("ED_node_shader_default called on wrong ID type.\n");
309                         return;
310         }
311         
312         ntemp.type = output_type;
313         out= nodeAddNode(ntree, &ntemp);
314         out->locx= 300.0f; out->locy= 300.0f;
315         
316         ntemp.type = shader_type;
317         in= nodeAddNode(ntree, &ntemp);
318         in->locx= 10.0f; in->locy= 300.0f;
319         nodeSetActive(ntree, in);
320         
321         /* only a link from color to color */
322         fromsock= in->outputs.first;
323         tosock= out->inputs.first;
324         nodeAddLink(ntree, in, fromsock, out, tosock);
325         
326         ntreeUpdateTree(ntree);
327 }
328
329 /* assumes nothing being done in ntree yet, sets the default in/out node */
330 /* called from shading buttons or header */
331 void ED_node_composit_default(Scene *sce)
332 {
333         bNode *in, *out;
334         bNodeSocket *fromsock, *tosock;
335         bNodeTemplate ntemp;
336         
337         /* but lets check it anyway */
338         if(sce->nodetree) {
339                 if (G.f & G_DEBUG)
340                         printf("error in composite initialize\n");
341                 return;
342         }
343         
344         sce->nodetree= ntreeAddTree("Compositing Nodetree", NTREE_COMPOSIT, 0);
345         
346         ntemp.type = CMP_NODE_COMPOSITE;
347         out= nodeAddNode(sce->nodetree, &ntemp);
348         out->locx= 300.0f; out->locy= 400.0f;
349         out->id= &sce->id;
350         id_us_plus(out->id);
351         
352         ntemp.type = CMP_NODE_R_LAYERS;
353         in= nodeAddNode(sce->nodetree, &ntemp);
354         in->locx= 10.0f; in->locy= 400.0f;
355         in->id= &sce->id;
356         id_us_plus(in->id);
357         nodeSetActive(sce->nodetree, in);
358         
359         /* links from color to color */
360         fromsock= in->outputs.first;
361         tosock= out->inputs.first;
362         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
363         
364         ntreeUpdateTree(sce->nodetree);
365         
366         // XXX ntreeCompositForceHidden(sce->nodetree);
367 }
368
369 /* assumes nothing being done in ntree yet, sets the default in/out node */
370 /* called from shading buttons or header */
371 void ED_node_texture_default(Tex *tx)
372 {
373         bNode *in, *out;
374         bNodeSocket *fromsock, *tosock;
375         bNodeTemplate ntemp;
376         
377         /* but lets check it anyway */
378         if(tx->nodetree) {
379                 if (G.f & G_DEBUG)
380                         printf("error in texture initialize\n");
381                 return;
382         }
383         
384         tx->nodetree= ntreeAddTree("Texture Nodetree", NTREE_TEXTURE, 0);
385         
386         ntemp.type = TEX_NODE_OUTPUT;
387         out= nodeAddNode(tx->nodetree, &ntemp);
388         out->locx= 300.0f; out->locy= 300.0f;
389         
390         ntemp.type = TEX_NODE_CHECKER;
391         in= nodeAddNode(tx->nodetree, &ntemp);
392         in->locx= 10.0f; in->locy= 300.0f;
393         nodeSetActive(tx->nodetree, in);
394         
395         fromsock= in->outputs.first;
396         tosock= out->inputs.first;
397         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
398         
399         ntreeUpdateTree(tx->nodetree);
400 }
401
402 /* id is supposed to contain a node tree */
403 void node_tree_from_ID(ID *id, bNodeTree **ntree, bNodeTree **edittree, int *treetype)
404 {
405         if (id) {
406                 bNode *node= NULL;
407                 short idtype= GS(id->name);
408         
409                 if(idtype == ID_NT) {
410                         *ntree= (bNodeTree*)id;
411                         if(treetype) *treetype= (*ntree)->type;
412                 }
413                 else if(idtype == ID_MA) {
414                         *ntree= ((Material*)id)->nodetree;
415                         if(treetype) *treetype= NTREE_SHADER;
416                 }
417                 else if(idtype == ID_LA) {
418                         *ntree= ((Lamp*)id)->nodetree;
419                         if(treetype) *treetype= NTREE_SHADER;
420                 }
421                 else if(idtype == ID_WO) {
422                         *ntree= ((World*)id)->nodetree;
423                         if(treetype) *treetype= NTREE_SHADER;
424                 }
425                 else if(idtype == ID_SCE) {
426                         *ntree= ((Scene*)id)->nodetree;
427                         if(treetype) *treetype= NTREE_COMPOSIT;
428                 }
429                 else if(idtype == ID_TE) {
430                         *ntree= ((Tex*)id)->nodetree;
431                         if(treetype) *treetype= NTREE_TEXTURE;
432                 }
433                 else {
434                         if(treetype) *treetype= 0;
435                         return;
436                 }
437         
438                 /* find editable group */
439                 if(edittree) {
440                         if(*ntree)
441                                 for(node= (*ntree)->nodes.first; node; node= node->next)
442                                         if(nodeGroupEditGet(node))
443                                                 break;
444                         
445                         if(node && node->id)
446                                 *edittree= (bNodeTree *)node->id;
447                         else
448                                 *edittree= *ntree;
449                 }
450         }
451         else {
452                 *ntree= NULL;
453                 if(treetype) *treetype= 0;
454         }
455 }
456
457 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
458 void snode_set_context(SpaceNode *snode, Scene *scene)
459 {
460         Object *ob= OBACT;
461         
462         snode->id= snode->from= NULL;
463         
464         if(snode->treetype==NTREE_SHADER) {
465                 /* need active object, or we allow pinning... */
466                 if(snode->shaderfrom == SNODE_SHADER_OBJECT) {
467                         if(ob) {
468                                 if(ob->type == OB_LAMP) {
469                                         snode->from= &ob->id;
470                                         snode->id= ob->data;
471                                 }
472                                 else {
473                                         Material *ma= give_current_material(ob, ob->actcol);
474                                         if(ma) {
475                                                 snode->from= &ob->id;
476                                                 snode->id= &ma->id;
477                                         }
478                                 }
479                         }
480                 }
481                 else { /* SNODE_SHADER_WORLD */
482                         if(scene->world) {
483                                 snode->from= NULL;
484                                 snode->id= &scene->world->id;
485                         }
486                 }
487         }
488         else if(snode->treetype==NTREE_COMPOSIT) {
489                 snode->id= &scene->id;
490                 
491                 /* update output sockets based on available layers */
492                 ntreeCompositForceHidden(scene->nodetree, scene);
493         }
494         else if(snode->treetype==NTREE_TEXTURE) {
495                 Tex *tx= NULL;
496
497                 if(snode->texfrom==SNODE_TEX_OBJECT) {
498                         if(ob) {
499                                 tx= give_current_object_texture(ob);
500
501                                 if(ob->type == OB_LAMP)
502                                         snode->from= (ID*)ob->data;
503                                 else
504                                         snode->from= (ID*)give_current_material(ob, ob->actcol);
505
506                                 /* from is not set fully for material nodes, should be ID + Node then */
507                                 snode->id= &tx->id;
508                         }
509                 }
510                 else if(snode->texfrom==SNODE_TEX_WORLD) {
511                         tx= give_current_world_texture(scene->world);
512                         snode->from= (ID *)scene->world;
513                         snode->id= &tx->id;
514                 }
515                 else {
516                         struct Brush *brush= NULL;
517                         
518                         if(ob && (ob->mode & OB_MODE_SCULPT))
519                                 brush= paint_brush(&scene->toolsettings->sculpt->paint);
520                         else
521                                 brush= paint_brush(&scene->toolsettings->imapaint.paint);
522
523                         if (brush) {
524                                 snode->from= (ID *)brush;
525                                 tx= give_current_brush_texture(brush);
526                                 snode->id= &tx->id;
527                         }
528                 }
529         }
530         else {
531                 if (snode->nodetree && snode->nodetree->type == snode->treetype)
532                         snode->id = &snode->nodetree->id;
533                 else
534                         snode->id = NULL;
535         }
536
537         node_tree_from_ID(snode->id, &snode->nodetree, &snode->edittree, NULL);
538 }
539
540 static void snode_update(SpaceNode *snode, bNode *node)
541 {
542         bNode *gnode;
543         
544         if (node)
545                 nodeUpdate(snode->edittree, node);
546         
547         /* if inside group, tag entire group */
548         gnode= node_tree_get_editgroup(snode->nodetree);
549         if(gnode)
550                 nodeUpdateID(snode->nodetree, gnode->id);
551 }
552
553 static int has_nodetree(bNodeTree *ntree, bNodeTree *lookup)
554 {
555         bNode *node;
556         
557         if(ntree == lookup)
558                 return 1;
559         
560         for(node=ntree->nodes.first; node; node=node->next)
561                 if(node->type == NODE_GROUP && node->id)
562                         if(has_nodetree((bNodeTree*)node->id, lookup))
563                                 return 1;
564         
565         return 0;
566 }
567
568 void ED_node_set_active(Main *bmain, bNodeTree *ntree, bNode *node)
569 {
570         nodeSetActive(ntree, node);
571         
572         if(node->type!=NODE_GROUP) {
573                 int was_output= (node->flag & NODE_DO_OUTPUT);
574                 
575                 /* tree specific activate calls */
576                 if(ntree->type==NTREE_SHADER) {
577                         /* when we select a material, active texture is cleared, for buttons */
578                         if(node->id && ELEM3(GS(node->id->name), ID_MA, ID_LA, ID_WO))
579                                 nodeClearActiveID(ntree, ID_TE);
580                         
581                         if(node->type==SH_NODE_OUTPUT) {
582                                 bNode *tnode;
583                                 
584                                 for(tnode= ntree->nodes.first; tnode; tnode= tnode->next)
585                                         if( tnode->type==SH_NODE_OUTPUT)
586                                                 tnode->flag &= ~NODE_DO_OUTPUT;
587                                 
588                                 node->flag |= NODE_DO_OUTPUT;
589                                 if(was_output==0)
590                                         ED_node_generic_update(bmain, ntree, node);
591                         }
592
593                         WM_main_add_notifier(NC_MATERIAL|ND_NODES, node->id);
594                 }
595                 else if(ntree->type==NTREE_COMPOSIT) {
596                         /* make active viewer, currently only 1 supported... */
597                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
598                                 bNode *tnode;
599                                 
600
601                                 for(tnode= ntree->nodes.first; tnode; tnode= tnode->next)
602                                         if( ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
603                                                 tnode->flag &= ~NODE_DO_OUTPUT;
604                                 
605                                 node->flag |= NODE_DO_OUTPUT;
606                                 if(was_output==0)
607                                         ED_node_generic_update(bmain, ntree, node);
608                                 
609                                 /* addnode() doesnt link this yet... */
610                                 node->id= (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
611                         }
612                         else if(node->type==CMP_NODE_R_LAYERS) {
613                                 Scene *scene;
614
615                                 for(scene=bmain->scene.first; scene; scene=scene->id.next) {
616                                         if(scene->nodetree && scene->use_nodes && has_nodetree(scene->nodetree, ntree)) {
617                                                 if(node->id==NULL || node->id==(ID *)scene) {
618                                                         scene->r.actlay= node->custom1;
619                                                 }
620                                         }
621                                 }
622                         }
623                         else if(node->type==CMP_NODE_COMPOSITE) {
624                                 if (was_output==0) {
625                                         bNode *tnode;
626                                         
627                                         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next)
628                                                 if( tnode->type==CMP_NODE_COMPOSITE)
629                                                         tnode->flag &= ~NODE_DO_OUTPUT;
630                                         
631                                         node->flag |= NODE_DO_OUTPUT;
632                                         ED_node_generic_update(bmain, ntree, node);
633                                 }
634                         }
635                 }
636                 else if(ntree->type==NTREE_TEXTURE) {
637                         // XXX
638 #if 0
639                         if(node->id)
640                                 ; // XXX BIF_preview_changed(-1);
641                         // allqueue(REDRAWBUTSSHADING, 1);
642                         // allqueue(REDRAWIPO, 0);
643 #endif
644                 }
645         }
646 }
647
648 static int compare_nodes(bNode *a, bNode *b)
649 {
650         bNode *parent;
651         /* These tell if either the node or any of the parent nodes is selected.
652          * A selected parent means an unselected node is also in foreground!
653          */
654         int a_select=(a->flag & NODE_SELECT), b_select=(b->flag & NODE_SELECT);
655         int a_active=(a->flag & NODE_ACTIVE), b_active=(b->flag & NODE_ACTIVE);
656         
657         /* if one is an ancestor of the other */
658         /* XXX there might be a better sorting algorithm for stable topological sort, this is O(n^2) worst case */
659         for (parent = a->parent; parent; parent=parent->parent) {
660                 /* if b is an ancestor, it is always behind a */
661                 if (parent==b)
662                         return 1;
663                 /* any selected ancestor moves the node forward */
664                 if (parent->flag & NODE_ACTIVE)
665                         a_active = 1;
666                 if (parent->flag & NODE_SELECT)
667                         a_select = 1;
668         }
669         for (parent = b->parent; parent; parent=parent->parent) {
670                 /* if a is an ancestor, it is always behind b */
671                 if (parent==a)
672                         return 0;
673                 /* any selected ancestor moves the node forward */
674                 if (parent->flag & NODE_ACTIVE)
675                         b_active = 1;
676                 if (parent->flag & NODE_SELECT)
677                         b_select = 1;
678         }
679
680         /* if one of the nodes is in the background and the other not */
681         if ((a->flag & NODE_BACKGROUND) && !(b->flag & NODE_BACKGROUND))
682                 return 0;
683         else if (!(a->flag & NODE_BACKGROUND) && (b->flag & NODE_BACKGROUND))
684                 return 1;
685         
686         /* if one has a higher selection state (active > selected > nothing) */
687         if (!b_active && a_active)
688                 return 1;
689         else if (!b_select && (a_active || a_select))
690                 return 1;
691         
692         return 0;
693 }
694 /* Sorts nodes by selection: unselected nodes first, then selected,
695  * then the active node at the very end. Relative order is kept intact!
696  */
697 void node_sort(bNodeTree *ntree)
698 {
699         /* merge sort is the algorithm of choice here */
700         bNode *first_a, *first_b, *node_a, *node_b, *tmp;
701         int totnodes= BLI_countlist(&ntree->nodes);
702         int k, a, b;
703         
704         k = 1;
705         while (k < totnodes) {
706                 first_a = first_b = ntree->nodes.first;
707                 
708                 do {
709                         /* setup first_b pointer */
710                         for (b=0; b < k && first_b; ++b) {
711                                 first_b = first_b->next;
712                         }
713                         /* all batches merged? */
714                         if (first_b==NULL)
715                                 break;
716                         
717                         /* merge batches */
718                         node_a = first_a;
719                         node_b = first_b;
720                         a = b = 0;
721                         while (a < k && b < k && node_b) {
722                                 if (compare_nodes(node_a, node_b)==0) {
723                                         node_a = node_a->next;
724                                         ++a;
725                                 }
726                                 else {
727                                         tmp = node_b;
728                                         node_b = node_b->next;
729                                         ++b;
730                                         BLI_remlink(&ntree->nodes, tmp);
731                                         BLI_insertlinkbefore(&ntree->nodes, node_a, tmp);
732                                 }
733                         }
734
735                         /* setup first pointers for next batch */
736                         first_b = node_b;
737                         for (; b < k; ++b) {
738                                 /* all nodes sorted? */
739                                 if (first_b==NULL)
740                                         break;
741                                 first_b = first_b->next;
742                         }
743                         first_a = first_b;
744                 } while (first_b);
745                 
746                 k = k << 1;
747         }
748 }
749
750 static int inside_rctf(rctf *bounds, rctf *rect)
751 {
752         return (bounds->xmin <= rect->xmin && bounds->xmax >= rect->xmax
753                         && bounds->ymin <= rect->ymin && bounds->ymax >= rect->ymax);
754 }
755
756 static void node_frame_attach_nodes(bNodeTree *UNUSED(ntree), bNode *frame)
757 {
758         bNode *node;
759         
760         /* only check nodes on top of the frame for attaching */
761         for (node=frame->next; node; node=node->next) {
762                 if (node->parent==frame) {
763                         /* detach nodes that went outside the frame */
764                         if (!inside_rctf(&frame->totr, &node->totr))
765                                 nodeDetachNode(node);
766                 }
767                 else if (node->flag & NODE_SELECT && node->parent==NULL) {
768                         /* attach selected, still unparented nodes */
769                         if (inside_rctf(&frame->totr, &node->totr))
770                                 nodeAttachNode(node, frame);
771                 }
772         }
773 }
774
775 void ED_node_update_hierarchy(bContext *UNUSED(C), bNodeTree *ntree)
776 {
777         bNode *node;
778         
779         /* XXX This does not work due to layout functions relying on node->block,
780          * which only exists during actual drawing. Can we rely on valid totr rects?
781          */
782         /* make sure nodes have correct bounding boxes after transform */
783 //      node_update_nodetree(C, ntree, 0.0f, 0.0f);
784         
785         /* all selected nodes are re-parented */
786         for (node=ntree->nodes.last; node; node=node->prev) {
787                 if (node->flag & NODE_SELECT && node->parent)
788                         nodeDetachNode(node);
789         }
790         
791         /* update higher Z-level nodes first */
792         for (node=ntree->nodes.last; node; node=node->prev) {
793                 /* XXX callback? */
794                 if (node->type==NODE_FRAME)
795                         node_frame_attach_nodes(ntree, node);
796         }
797 }
798
799 /* ***************** generic operator functions for nodes ***************** */
800
801 #if 0 /* UNUSED */
802
803 static int edit_node_poll(bContext *C)
804 {
805         return ED_operator_node_active(C);
806 }
807
808 static void edit_node_properties(wmOperatorType *ot)
809 {
810         /* XXX could node be a context pointer? */
811         RNA_def_string(ot->srna, "node", "", 32, "Node", "");
812         RNA_def_int(ot->srna, "socket", 0, 0, MAX_SOCKET, "Socket", "", 0, MAX_SOCKET);
813         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Side", "");
814 }
815
816 static int edit_node_invoke_properties(bContext *C, wmOperator *op)
817 {
818         if (!RNA_property_is_set(op->ptr, "node")) {
819                 bNode *node= CTX_data_pointer_get_type(C, "node", &RNA_Node).data;
820                 if (!node)
821                         return 0;
822                 else
823                         RNA_string_set(op->ptr, "node", node->name);
824         }
825         
826         if (!RNA_property_is_set(op->ptr, "in_out"))
827                 RNA_enum_set(op->ptr, "in_out", SOCK_IN);
828         
829         if (!RNA_property_is_set(op->ptr, "socket"))
830                 RNA_int_set(op->ptr, "socket", 0);
831         
832         return 1;
833 }
834
835 static void edit_node_properties_get(wmOperator *op, bNodeTree *ntree, bNode **rnode, bNodeSocket **rsock, int *rin_out)
836 {
837         bNode *node;
838         bNodeSocket *sock=NULL;
839         char nodename[32];
840         int sockindex;
841         int in_out;
842         
843         RNA_string_get(op->ptr, "node", nodename);
844         node = nodeFindNodebyName(ntree, nodename);
845         
846         in_out = RNA_enum_get(op->ptr, "in_out");
847         
848         sockindex = RNA_int_get(op->ptr, "socket");
849         switch (in_out) {
850         case SOCK_IN:   sock = BLI_findlink(&node->inputs, sockindex);  break;
851         case SOCK_OUT:  sock = BLI_findlink(&node->outputs, sockindex); break;
852         }
853         
854         if (rnode)
855                 *rnode = node;
856         if (rsock)
857                 *rsock = sock;
858         if (rin_out)
859                 *rin_out = in_out;
860 }
861 #endif
862
863 /* ***************** Edit Group operator ************* */
864
865 void snode_make_group_editable(SpaceNode *snode, bNode *gnode)
866 {
867         bNode *node;
868         
869         /* make sure nothing has group editing on */
870         for(node=snode->nodetree->nodes.first; node; node=node->next)
871                 nodeGroupEditClear(node);
872         
873         if(gnode==NULL) {
874                 /* with NULL argument we do a toggle */
875                 if(snode->edittree==snode->nodetree)
876                         gnode= nodeGetActive(snode->nodetree);
877         }
878         
879         if (gnode) {
880                 snode->edittree = nodeGroupEditSet(gnode, 1);
881                 
882                 /* deselect all other nodes, so we can also do grabbing of entire subtree */
883                 for(node= snode->nodetree->nodes.first; node; node= node->next)
884                         node->flag &= ~SELECT;
885                 gnode->flag |= SELECT;
886         }
887         else 
888                 snode->edittree= snode->nodetree;
889 }
890
891 static int node_group_edit_exec(bContext *C, wmOperator *UNUSED(op))
892 {
893         SpaceNode *snode = CTX_wm_space_node(C);
894
895         ED_preview_kill_jobs(C);
896
897         if (snode->nodetree==snode->edittree) {
898                 bNode *gnode= nodeGetActive(snode->nodetree);
899                 snode_make_group_editable(snode, gnode);
900         }
901         else
902                 snode_make_group_editable(snode, NULL);
903
904         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
905
906         return OPERATOR_FINISHED;
907 }
908
909 static int node_group_edit_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
910 {
911         SpaceNode *snode = CTX_wm_space_node(C);
912         bNode *gnode;
913
914         gnode= nodeGetActive(snode->edittree);
915         /* XXX callback? */
916         if(gnode && gnode->id && GS(gnode->id->name)==ID_NT && gnode->id->lib) {
917                 uiPupMenuOkee(C, op->type->idname, "Make group local?");
918                 return OPERATOR_CANCELLED;
919         }
920
921         return node_group_edit_exec(C, op);
922 }
923
924 void NODE_OT_group_edit(wmOperatorType *ot)
925 {
926         /* identifiers */
927         ot->name = "Edit Group";
928         ot->description = "Edit node group";
929         ot->idname = "NODE_OT_group_edit";
930         
931         /* api callbacks */
932         ot->invoke = node_group_edit_invoke;
933         ot->exec = node_group_edit_exec;
934         ot->poll = ED_operator_node_active;
935         
936         /* flags */
937         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
938 }
939
940 /* ***************** Add Group Socket operator ************* */
941
942 static int node_group_socket_add_exec(bContext *C, wmOperator *op)
943 {
944         SpaceNode *snode = CTX_wm_space_node(C);
945         int in_out= -1;
946         char name[32]= "";
947         int type= SOCK_FLOAT;
948         bNodeTree *ngroup= snode->edittree;
949         /* bNodeSocket *sock; */ /* UNUSED */
950         
951         ED_preview_kill_jobs(C);
952         
953         if (RNA_property_is_set(op->ptr, "name"))
954                 RNA_string_get(op->ptr, "name", name);
955         
956         if (RNA_property_is_set(op->ptr, "type"))
957                 type = RNA_enum_get(op->ptr, "type");
958         
959         if (RNA_property_is_set(op->ptr, "in_out"))
960                 in_out = RNA_enum_get(op->ptr, "in_out");
961         else
962                 return OPERATOR_CANCELLED;
963         
964         /* using placeholder subtype first */
965         /* sock = */ /* UNUSED */ node_group_add_socket(ngroup, name, type, in_out);
966         
967         ntreeUpdateTree(ngroup);
968         
969         snode_notify(C, snode);
970         
971         return OPERATOR_FINISHED;
972 }
973
974 void NODE_OT_group_socket_add(wmOperatorType *ot)
975 {
976         /* identifiers */
977         ot->name = "Add Group Socket";
978         ot->description = "Add node group socket";
979         ot->idname = "NODE_OT_group_socket_add";
980         
981         /* api callbacks */
982         ot->exec = node_group_socket_add_exec;
983         ot->poll = ED_operator_node_active;
984         
985         /* flags */
986         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
987         
988         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
989         RNA_def_string(ot->srna, "name", "", 32, "Name", "Group socket name");
990         RNA_def_enum(ot->srna, "type", node_socket_type_items, SOCK_FLOAT, "Type", "Type of the group socket");
991 }
992
993 /* ***************** Remove Group Socket operator ************* */
994
995 static int node_group_socket_remove_exec(bContext *C, wmOperator *op)
996 {
997         SpaceNode *snode = CTX_wm_space_node(C);
998         int index= -1;
999         int in_out= -1;
1000         bNodeTree *ngroup= snode->edittree;
1001         bNodeSocket *sock;
1002         
1003         ED_preview_kill_jobs(C);
1004         
1005         if (RNA_property_is_set(op->ptr, "index"))
1006                 index = RNA_int_get(op->ptr, "index");
1007         else
1008                 return OPERATOR_CANCELLED;
1009         
1010         if (RNA_property_is_set(op->ptr, "in_out"))
1011                 in_out = RNA_enum_get(op->ptr, "in_out");
1012         else
1013                 return OPERATOR_CANCELLED;
1014         
1015         sock = (bNodeSocket*)BLI_findlink(in_out==SOCK_IN ? &ngroup->inputs : &ngroup->outputs, index);
1016         if (sock) {
1017                 node_group_remove_socket(ngroup, sock, in_out);
1018                 ntreeUpdateTree(ngroup);
1019                 
1020                 snode_notify(C, snode);
1021         }
1022         
1023         return OPERATOR_FINISHED;
1024 }
1025
1026 void NODE_OT_group_socket_remove(wmOperatorType *ot)
1027 {
1028         /* identifiers */
1029         ot->name = "Remove Group Socket";
1030         ot->description = "Remove a node group socket";
1031         ot->idname = "NODE_OT_group_socket_remove";
1032         
1033         /* api callbacks */
1034         ot->exec = node_group_socket_remove_exec;
1035         ot->poll = ED_operator_node_active;
1036         
1037         /* flags */
1038         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1039         
1040         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1041         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1042 }
1043
1044 /* ***************** Move Group Socket Up operator ************* */
1045
1046 static int node_group_socket_move_up_exec(bContext *C, wmOperator *op)
1047 {
1048         SpaceNode *snode = CTX_wm_space_node(C);
1049         int index= -1;
1050         int in_out= -1;
1051         bNodeTree *ngroup= snode->edittree;
1052         bNodeSocket *sock, *prev;
1053         
1054         ED_preview_kill_jobs(C);
1055         
1056         if (RNA_property_is_set(op->ptr, "index"))
1057                 index = RNA_int_get(op->ptr, "index");
1058         else
1059                 return OPERATOR_CANCELLED;
1060         
1061         if (RNA_property_is_set(op->ptr, "in_out"))
1062                 in_out = RNA_enum_get(op->ptr, "in_out");
1063         else
1064                 return OPERATOR_CANCELLED;
1065         
1066         /* swap */
1067         if (in_out==SOCK_IN) {
1068                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
1069                 prev = sock->prev;
1070                 /* can't move up the first socket */
1071                 if (!prev)
1072                         return OPERATOR_CANCELLED;
1073                 BLI_remlink(&ngroup->inputs, sock);
1074                 BLI_insertlinkbefore(&ngroup->inputs, prev, sock);
1075                 
1076                 ngroup->update |= NTREE_UPDATE_GROUP_IN;
1077         }
1078         else if (in_out==SOCK_OUT) {
1079                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
1080                 prev = sock->prev;
1081                 /* can't move up the first socket */
1082                 if (!prev)
1083                         return OPERATOR_CANCELLED;
1084                 BLI_remlink(&ngroup->outputs, sock);
1085                 BLI_insertlinkbefore(&ngroup->outputs, prev, sock);
1086                 
1087                 ngroup->update |= NTREE_UPDATE_GROUP_OUT;
1088         }
1089         ntreeUpdateTree(ngroup);
1090         
1091         snode_notify(C, snode);
1092         
1093         return OPERATOR_FINISHED;
1094 }
1095
1096 void NODE_OT_group_socket_move_up(wmOperatorType *ot)
1097 {
1098         /* identifiers */
1099         ot->name = "Move Group Socket Up";
1100         ot->description = "Move up node group socket";
1101         ot->idname = "NODE_OT_group_socket_move_up";
1102         
1103         /* api callbacks */
1104         ot->exec = node_group_socket_move_up_exec;
1105         ot->poll = ED_operator_node_active;
1106         
1107         /* flags */
1108         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1109         
1110         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1111         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1112 }
1113
1114 /* ***************** Move Group Socket Up operator ************* */
1115
1116 static int node_group_socket_move_down_exec(bContext *C, wmOperator *op)
1117 {
1118         SpaceNode *snode = CTX_wm_space_node(C);
1119         int index= -1;
1120         int in_out= -1;
1121         bNodeTree *ngroup= snode->edittree;
1122         bNodeSocket *sock, *next;
1123         
1124         ED_preview_kill_jobs(C);
1125         
1126         if (RNA_property_is_set(op->ptr, "index"))
1127                 index = RNA_int_get(op->ptr, "index");
1128         else
1129                 return OPERATOR_CANCELLED;
1130         
1131         if (RNA_property_is_set(op->ptr, "in_out"))
1132                 in_out = RNA_enum_get(op->ptr, "in_out");
1133         else
1134                 return OPERATOR_CANCELLED;
1135         
1136         /* swap */
1137         if (in_out==SOCK_IN) {
1138                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
1139                 next = sock->next;
1140                 /* can't move down the last socket */
1141                 if (!next)
1142                         return OPERATOR_CANCELLED;
1143                 BLI_remlink(&ngroup->inputs, sock);
1144                 BLI_insertlinkafter(&ngroup->inputs, next, sock);
1145                 
1146                 ngroup->update |= NTREE_UPDATE_GROUP_IN;
1147         }
1148         else if (in_out==SOCK_OUT) {
1149                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
1150                 next = sock->next;
1151                 /* can't move down the last socket */
1152                 if (!next)
1153                         return OPERATOR_CANCELLED;
1154                 BLI_remlink(&ngroup->outputs, sock);
1155                 BLI_insertlinkafter(&ngroup->outputs, next, sock);
1156                 
1157                 ngroup->update |= NTREE_UPDATE_GROUP_OUT;
1158         }
1159         ntreeUpdateTree(ngroup);
1160         
1161         snode_notify(C, snode);
1162         
1163         return OPERATOR_FINISHED;
1164 }
1165
1166 void NODE_OT_group_socket_move_down(wmOperatorType *ot)
1167 {
1168         /* identifiers */
1169         ot->name = "Move Group Socket Down";
1170         ot->description = "Move down node group socket";
1171         ot->idname = "NODE_OT_group_socket_move_down";
1172         
1173         /* api callbacks */
1174         ot->exec = node_group_socket_move_down_exec;
1175         ot->poll = ED_operator_node_active;
1176         
1177         /* flags */
1178         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1179         
1180         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1181         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1182 }
1183
1184 /* ******************** Ungroup operator ********************** */
1185
1186 static int node_group_ungroup_exec(bContext *C, wmOperator *op)
1187 {
1188         SpaceNode *snode = CTX_wm_space_node(C);
1189         bNode *gnode;
1190
1191         ED_preview_kill_jobs(C);
1192
1193         /* are we inside of a group? */
1194         gnode= node_tree_get_editgroup(snode->nodetree);
1195         if(gnode)
1196                 snode_make_group_editable(snode, NULL);
1197         
1198         gnode= nodeGetActive(snode->edittree);
1199         if(gnode==NULL)
1200                 return OPERATOR_CANCELLED;
1201         
1202         if(gnode->type!=NODE_GROUP) {
1203                 BKE_report(op->reports, RPT_WARNING, "Not a group");
1204                 return OPERATOR_CANCELLED;
1205         }
1206         else if(!node_group_ungroup(snode->edittree, gnode)) {
1207                 BKE_report(op->reports, RPT_WARNING, "Can't ungroup");
1208                 return OPERATOR_CANCELLED;
1209         }
1210
1211         snode_notify(C, snode);
1212         snode_dag_update(C, snode);
1213
1214         return OPERATOR_FINISHED;
1215 }
1216
1217 void NODE_OT_group_ungroup(wmOperatorType *ot)
1218 {
1219         /* identifiers */
1220         ot->name = "Ungroup";
1221         ot->description = "Ungroup selected nodes";
1222         ot->idname = "NODE_OT_group_ungroup";
1223         
1224         /* api callbacks */
1225         ot->exec = node_group_ungroup_exec;
1226         ot->poll = ED_operator_node_active;
1227         
1228         /* flags */
1229         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1230 }
1231
1232 /* ************************** Node generic ************** */
1233
1234 /* is rct in visible part of node? */
1235 static bNode *visible_node(SpaceNode *snode, rctf *rct)
1236 {
1237         bNode *node;
1238         
1239         for(node=snode->edittree->nodes.last; node; node=node->prev) {
1240                 if(BLI_isect_rctf(&node->totr, rct, NULL))
1241                         break;
1242         }
1243         return node;
1244 }
1245
1246 /* **************************** */
1247
1248 typedef struct NodeViewMove {
1249         int mvalo[2];
1250         int xmin, ymin, xmax, ymax;
1251 } NodeViewMove;
1252
1253 static int snode_bg_viewmove_modal(bContext *C, wmOperator *op, wmEvent *event)
1254 {
1255         SpaceNode *snode= CTX_wm_space_node(C);
1256         ARegion *ar= CTX_wm_region(C);
1257         NodeViewMove *nvm= op->customdata;
1258
1259         switch (event->type) {
1260                 case MOUSEMOVE:
1261                         
1262                         snode->xof -= (nvm->mvalo[0]-event->mval[0]);
1263                         snode->yof -= (nvm->mvalo[1]-event->mval[1]);
1264                         nvm->mvalo[0]= event->mval[0];
1265                         nvm->mvalo[1]= event->mval[1];
1266                         
1267                         /* prevent dragging image outside of the window and losing it! */
1268                         CLAMP(snode->xof, nvm->xmin, nvm->xmax);
1269                         CLAMP(snode->yof, nvm->ymin, nvm->ymax);
1270                         
1271                         ED_region_tag_redraw(ar);
1272                         
1273                         break;
1274                         
1275                 case LEFTMOUSE:
1276                 case MIDDLEMOUSE:
1277                 case RIGHTMOUSE:
1278                         
1279                         MEM_freeN(nvm);
1280                         op->customdata= NULL;
1281
1282                         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_NODE, NULL);
1283                         
1284                         return OPERATOR_FINISHED;
1285         }
1286         
1287         return OPERATOR_RUNNING_MODAL;
1288 }
1289
1290 static int snode_bg_viewmove_invoke(bContext *C, wmOperator *op, wmEvent *event)
1291 {
1292         ARegion *ar= CTX_wm_region(C);
1293         NodeViewMove *nvm;
1294         Image *ima;
1295         ImBuf *ibuf;
1296         int pad= 10;
1297         void *lock;
1298         
1299         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1300         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1301         
1302         if(ibuf == NULL) {
1303                 BKE_image_release_ibuf(ima, lock);
1304                 return OPERATOR_CANCELLED;
1305         }
1306
1307         nvm= MEM_callocN(sizeof(NodeViewMove), "NodeViewMove struct");
1308         op->customdata= nvm;
1309         nvm->mvalo[0]= event->mval[0];
1310         nvm->mvalo[1]= event->mval[1];
1311
1312         nvm->xmin = -(ar->winx/2) - ibuf->x/2 + pad;
1313         nvm->xmax = ar->winx/2 + ibuf->x/2 - pad;
1314         nvm->ymin = -(ar->winy/2) - ibuf->y/2 + pad;
1315         nvm->ymax = ar->winy/2 + ibuf->y/2 - pad;
1316
1317         BKE_image_release_ibuf(ima, lock);
1318         
1319         /* add modal handler */
1320         WM_event_add_modal_handler(C, op);
1321         
1322         return OPERATOR_RUNNING_MODAL;
1323 }
1324
1325 static int snode_bg_viewmove_cancel(bContext *UNUSED(C), wmOperator *op)
1326 {
1327         MEM_freeN(op->customdata);
1328         op->customdata= NULL;
1329
1330         return OPERATOR_CANCELLED;
1331 }
1332
1333 void NODE_OT_backimage_move(wmOperatorType *ot)
1334 {
1335         /* identifiers */
1336         ot->name= "Background Image Move";
1337         ot->description = "Move Node backdrop";
1338         ot->idname= "NODE_OT_backimage_move";
1339         
1340         /* api callbacks */
1341         ot->invoke= snode_bg_viewmove_invoke;
1342         ot->modal= snode_bg_viewmove_modal;
1343         ot->poll= composite_node_active;
1344         ot->cancel= snode_bg_viewmove_cancel;
1345         
1346         /* flags */
1347         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1348 }
1349
1350 static int backimage_zoom(bContext *C, wmOperator *op)
1351 {
1352         SpaceNode *snode= CTX_wm_space_node(C);
1353         ARegion *ar= CTX_wm_region(C);
1354         float fac= RNA_float_get(op->ptr, "factor");
1355
1356         snode->zoom *= fac;
1357         ED_region_tag_redraw(ar);
1358
1359         return OPERATOR_FINISHED;
1360 }
1361
1362
1363 void NODE_OT_backimage_zoom(wmOperatorType *ot)
1364 {
1365         
1366         /* identifiers */
1367         ot->name= "Background Image Zoom";
1368         ot->idname= "NODE_OT_backimage_zoom";
1369         
1370         /* api callbacks */
1371         ot->exec= backimage_zoom;
1372         ot->poll= composite_node_active;
1373         
1374         /* flags */
1375         ot->flag= OPTYPE_BLOCKING;
1376
1377         /* internal */
1378         RNA_def_float(ot->srna, "factor", 1.2f, 0.0f, 10.0f, "Factor", "", 0.0f, 10.0f);
1379 }
1380
1381 /******************** sample backdrop operator ********************/
1382
1383 typedef struct ImageSampleInfo {
1384         ARegionType *art;
1385         void *draw_handle;
1386         int x, y;
1387         int channels;
1388         int color_manage;
1389
1390         char col[4];
1391         float colf[4];
1392
1393         int draw;
1394 } ImageSampleInfo;
1395
1396 static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
1397 {
1398         ImageSampleInfo *info= arg_info;
1399
1400         draw_nodespace_color_info(ar, (CTX_data_scene(C)->r.color_mgt_flag & R_COLOR_MANAGEMENT), info->channels,
1401                                                           info->x, info->y, info->col, info->colf);
1402 }
1403
1404 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1405 {
1406         SpaceNode *snode= CTX_wm_space_node(C);
1407         ARegion *ar= CTX_wm_region(C);
1408         ImageSampleInfo *info= op->customdata;
1409         void *lock;
1410         Image *ima;
1411         ImBuf *ibuf;
1412         float fx, fy, bufx, bufy;
1413         
1414         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1415         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1416         if(!ibuf)
1417                 return;
1418         
1419         if(!ibuf->rect) {
1420                 if(info->color_manage)
1421                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1422                 else
1423                         ibuf->profile = IB_PROFILE_NONE;
1424                 IMB_rect_from_float(ibuf);
1425         }
1426
1427         /* map the mouse coords to the backdrop image space */
1428         bufx = ibuf->x * snode->zoom;
1429         bufy = ibuf->y * snode->zoom;
1430         fx = (bufx > 0.0f ? ((float)event->mval[0] - 0.5f*ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
1431         fy = (bufy > 0.0f ? ((float)event->mval[1] - 0.5f*ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
1432
1433         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1434                 float *fp;
1435                 char *cp;
1436                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1437
1438                 CLAMP(x, 0, ibuf->x-1);
1439                 CLAMP(y, 0, ibuf->y-1);
1440
1441                 info->x= x;
1442                 info->y= y;
1443                 info->draw= 1;
1444                 info->channels= ibuf->channels;
1445
1446                 if(ibuf->rect) {
1447                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1448
1449                         info->col[0]= cp[0];
1450                         info->col[1]= cp[1];
1451                         info->col[2]= cp[2];
1452                         info->col[3]= cp[3];
1453
1454                         info->colf[0]= (float)cp[0]/255.0f;
1455                         info->colf[1]= (float)cp[1]/255.0f;
1456                         info->colf[2]= (float)cp[2]/255.0f;
1457                         info->colf[3]= (float)cp[3]/255.0f;
1458                 }
1459                 if(ibuf->rect_float) {
1460                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1461
1462                         info->colf[0]= fp[0];
1463                         info->colf[1]= fp[1];
1464                         info->colf[2]= fp[2];
1465                         info->colf[3]= fp[3];
1466                 }
1467         }
1468         else
1469                 info->draw= 0;
1470
1471         BKE_image_release_ibuf(ima, lock);
1472         
1473         ED_area_tag_redraw(CTX_wm_area(C));
1474 }
1475
1476 static void sample_exit(bContext *C, wmOperator *op)
1477 {
1478         ImageSampleInfo *info= op->customdata;
1479
1480         ED_region_draw_cb_exit(info->art, info->draw_handle);
1481         ED_area_tag_redraw(CTX_wm_area(C));
1482         MEM_freeN(info);
1483 }
1484
1485 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1486 {
1487         SpaceNode *snode= CTX_wm_space_node(C);
1488         ARegion *ar= CTX_wm_region(C);
1489         ImageSampleInfo *info;
1490
1491         if(snode->treetype!=NTREE_COMPOSIT || !(snode->flag & SNODE_BACKDRAW))
1492                 return OPERATOR_CANCELLED;
1493         
1494         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1495         info->art= ar->type;
1496         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1497         op->customdata= info;
1498
1499         sample_apply(C, op, event);
1500
1501         WM_event_add_modal_handler(C, op);
1502
1503         return OPERATOR_RUNNING_MODAL;
1504 }
1505
1506 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1507 {
1508         switch(event->type) {
1509                 case LEFTMOUSE:
1510                 case RIGHTMOUSE: // XXX hardcoded
1511                         sample_exit(C, op);
1512                         return OPERATOR_CANCELLED;
1513                 case MOUSEMOVE:
1514                         sample_apply(C, op, event);
1515                         break;
1516         }
1517
1518         return OPERATOR_RUNNING_MODAL;
1519 }
1520
1521 static int sample_cancel(bContext *C, wmOperator *op)
1522 {
1523         sample_exit(C, op);
1524         return OPERATOR_CANCELLED;
1525 }
1526
1527 void NODE_OT_backimage_sample(wmOperatorType *ot)
1528 {
1529         /* identifiers */
1530         ot->name= "Backimage Sample";
1531         ot->idname= "NODE_OT_backimage_sample";
1532         
1533         /* api callbacks */
1534         ot->invoke= sample_invoke;
1535         ot->modal= sample_modal;
1536         ot->cancel= sample_cancel;
1537         ot->poll= ED_operator_node_active;
1538
1539         /* flags */
1540         ot->flag= OPTYPE_BLOCKING;
1541 }
1542
1543 /* ********************** size widget operator ******************** */
1544
1545 typedef struct NodeSizeWidget {
1546         float mxstart, mystart;
1547         float oldwidth, oldheight;
1548         float oldminiwidth;
1549 } NodeSizeWidget;
1550
1551 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1552 {
1553         SpaceNode *snode= CTX_wm_space_node(C);
1554         ARegion *ar= CTX_wm_region(C);
1555         bNode *node= editnode_get_active(snode->edittree);
1556         NodeSizeWidget *nsw= op->customdata;
1557         float mx, my;
1558         
1559         switch (event->type) {
1560                 case MOUSEMOVE:
1561                         
1562                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1563                                                                          &mx, &my);
1564                         
1565                         if (node) {
1566                                 if(node->flag & NODE_HIDDEN) {
1567                                         node->miniwidth= nsw->oldminiwidth + mx - nsw->mxstart;
1568                                         CLAMP(node->miniwidth, 0.0f, 100.0f);
1569                                 }
1570                                 else {
1571                                         node->width= nsw->oldwidth + mx - nsw->mxstart;
1572                                         CLAMP(node->width, UI_DPI_FAC*node->typeinfo->minwidth, UI_DPI_FAC*node->typeinfo->maxwidth);
1573                                 }
1574                                 /* height works the other way round ... */
1575                                 node->height= nsw->oldheight - my + nsw->mystart;
1576                                 CLAMP(node->height, node->typeinfo->minheight, node->typeinfo->maxheight);
1577                         }
1578                                 
1579                         ED_region_tag_redraw(ar);
1580
1581                         break;
1582                         
1583                 case LEFTMOUSE:
1584                 case MIDDLEMOUSE:
1585                 case RIGHTMOUSE:
1586                         
1587                         MEM_freeN(nsw);
1588                         op->customdata= NULL;
1589                         
1590                         ED_node_update_hierarchy(C, snode->edittree);
1591                         
1592                         return OPERATOR_FINISHED;
1593         }
1594         
1595         return OPERATOR_RUNNING_MODAL;
1596 }
1597
1598 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1599 {
1600         SpaceNode *snode= CTX_wm_space_node(C);
1601         ARegion *ar= CTX_wm_region(C);
1602         bNode *node= editnode_get_active(snode->edittree);
1603         
1604         if(node) {
1605                 /* convert mouse coordinates to v2d space */
1606                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1607                                                                  &snode->mx, &snode->my);
1608                 
1609                 if(node->typeinfo->resize_area_func(node, snode->mx, snode->my)) {
1610                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1611                         
1612                         op->customdata= nsw;
1613                         nsw->mxstart= snode->mx;
1614                         nsw->mystart= snode->my;
1615                         
1616                         /* store old */
1617                         nsw->oldwidth= node->width;
1618                         nsw->oldheight= node->height;
1619                         nsw->oldminiwidth= node->miniwidth;
1620                         
1621                         /* add modal handler */
1622                         WM_event_add_modal_handler(C, op);
1623
1624                         return OPERATOR_RUNNING_MODAL;
1625                 }
1626         }
1627         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
1628 }
1629
1630 static int node_resize_cancel(bContext *UNUSED(C), wmOperator *op)
1631 {
1632         MEM_freeN(op->customdata);
1633         op->customdata= NULL;
1634
1635         return OPERATOR_CANCELLED;
1636 }
1637
1638 void NODE_OT_resize(wmOperatorType *ot)
1639 {
1640         /* identifiers */
1641         ot->name= "Resize Node";
1642         ot->idname= "NODE_OT_resize";
1643         
1644         /* api callbacks */
1645         ot->invoke= node_resize_invoke;
1646         ot->modal= node_resize_modal;
1647         ot->poll= ED_operator_node_active;
1648         ot->cancel= node_resize_cancel;
1649         
1650         /* flags */
1651         ot->flag= OPTYPE_BLOCKING;
1652 }
1653
1654 /* ********************** select ******************** */
1655
1656
1657 /* no undo here! */
1658 void node_deselectall(SpaceNode *snode)
1659 {
1660         bNode *node;
1661         
1662         for(node= snode->edittree->nodes.first; node; node= node->next)
1663                 node->flag &= ~SELECT;
1664 }
1665
1666 /* return 1 if we need redraw otherwise zero. */
1667 int node_select_same_type(SpaceNode *snode)
1668 {
1669         bNode *nac, *p;
1670         int redraw;
1671
1672         /* search for the active node. */
1673         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1674                 if (nac->flag & SELECT)
1675                         break;
1676         }
1677
1678         /* no active node, return. */
1679         if (!nac)
1680                 return(0);
1681
1682         redraw= 0;
1683         for (p= snode->edittree->nodes.first; p; p= p->next) {
1684                 if (p->type != nac->type && p->flag & SELECT) {
1685                         /* if it's selected but different type, unselect */
1686                         redraw= 1;
1687                         p->flag &= ~SELECT;
1688                 }
1689                 else if (p->type == nac->type && (!(p->flag & SELECT))) {
1690                         /* if it's the same type and is not selected, select! */
1691                         redraw= 1;
1692                         p->flag |= SELECT;
1693                 }
1694         }
1695         return(redraw);
1696 }
1697
1698 /* return 1 if we need redraw, otherwise zero.
1699  * dir can be 0 == next or 0 != prev.
1700  */
1701 int node_select_same_type_np(SpaceNode *snode, int dir)
1702 {
1703         bNode *nac, *p;
1704
1705         /* search the active one. */
1706         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1707                 if (nac->flag & SELECT)
1708                         break;
1709         }
1710
1711         /* no active node, return. */
1712         if (!nac)
1713                 return(0);
1714
1715         if (dir == 0)
1716                 p= nac->next;
1717         else
1718                 p= nac->prev;
1719
1720         while (p) {
1721                 /* Now search the next with the same type. */
1722                 if (p->type == nac->type)
1723                         break;
1724
1725                 if (dir == 0)
1726                         p= p->next;
1727                 else
1728                         p= p->prev;
1729         }
1730
1731         if (p) {
1732                 node_deselectall(snode);
1733                 p->flag |= SELECT;
1734                 return(1);
1735         }
1736         return(0);
1737 }
1738
1739 int node_has_hidden_sockets(bNode *node)
1740 {
1741         bNodeSocket *sock;
1742         
1743         for(sock= node->inputs.first; sock; sock= sock->next)
1744                 if(sock->flag & SOCK_HIDDEN)
1745                         return 1;
1746         for(sock= node->outputs.first; sock; sock= sock->next)
1747                 if(sock->flag & SOCK_HIDDEN)
1748                         return 1;
1749         return 0;
1750 }
1751
1752 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1753 {
1754         bNode *node;
1755
1756         /* context check */
1757         if(tonode==NULL || tonode->outputs.first==NULL)
1758                 return;
1759         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1760                 return;
1761         
1762         /* get viewer */
1763         for(node= snode->edittree->nodes.first; node; node= node->next)
1764                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1765                         if(node->flag & NODE_DO_OUTPUT)
1766                                 break;
1767         /* no viewer, we make one active */
1768         if(node==NULL) {
1769                 for(node= snode->edittree->nodes.first; node; node= node->next) {
1770                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
1771                                 node->flag |= NODE_DO_OUTPUT;
1772                                 break;
1773                         }
1774                 }
1775         }
1776                 
1777         if(node) {
1778                 bNodeLink *link;
1779                 bNodeSocket *sock= NULL;
1780
1781                 /* try to find an already connected socket to cycle to the next */
1782                 for(link= snode->edittree->links.first; link; link= link->next)
1783                         if(link->tonode==node && link->fromnode==tonode)
1784                                 if(link->tosock==node->inputs.first)
1785                                         break;
1786
1787                 if(link) {
1788                         /* unlink existing connection */
1789                         sock= link->fromsock;
1790                         nodeRemLink(snode->edittree, link);
1791
1792                         /* find a socket after the previously connected socket */
1793                         for(sock=sock->next; sock; sock= sock->next)
1794                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1795                                         break;
1796                 }
1797
1798                 /* find a socket starting from the first socket */
1799                 if(!sock) {
1800                         for(sock= tonode->outputs.first; sock; sock= sock->next)
1801                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1802                                         break;
1803                 }
1804                 
1805                 if(sock) {
1806                         /* get link to viewer */
1807                         for(link= snode->edittree->links.first; link; link= link->next)
1808                                 if(link->tonode==node && link->tosock==node->inputs.first)
1809                                         break;
1810                         
1811                         if(link==NULL) {
1812                                 nodeAddLink(snode->edittree, tonode, sock, node, node->inputs.first);
1813                         }
1814                         else {
1815                                 link->fromnode= tonode;
1816                                 link->fromsock= sock;
1817                         }
1818                         ntreeUpdateTree(snode->edittree);
1819                         snode_update(snode, node);
1820                 }
1821         }
1822 }
1823
1824
1825 static int node_active_link_viewer(bContext *C, wmOperator *UNUSED(op))
1826 {
1827         SpaceNode *snode= CTX_wm_space_node(C);
1828         bNode *node;
1829         
1830         node= editnode_get_active(snode->edittree);
1831         
1832         if(!node)
1833                 return OPERATOR_CANCELLED;
1834
1835         ED_preview_kill_jobs(C);
1836
1837         node_link_viewer(snode, node);
1838         snode_notify(C, snode);
1839
1840         return OPERATOR_FINISHED;
1841 }
1842
1843
1844
1845 void NODE_OT_link_viewer(wmOperatorType *ot)
1846 {
1847         /* identifiers */
1848         ot->name= "Link to Viewer Node";
1849         ot->description = "Link to viewer node";
1850         ot->idname= "NODE_OT_link_viewer";
1851         
1852         /* api callbacks */
1853         ot->exec= node_active_link_viewer;
1854         ot->poll= ED_operator_node_active;
1855         
1856         /* flags */
1857         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1858 }
1859
1860
1861
1862 /* return 0, nothing done */
1863 static int UNUSED_FUNCTION(node_mouse_groupheader)(SpaceNode *snode)
1864 {
1865         bNode *gnode;
1866         float mx=0, my=0;
1867 // XXX  int mval[2];
1868         
1869         gnode= node_tree_get_editgroup(snode->nodetree);
1870         if(gnode==NULL) return 0;
1871         
1872 // XXX  getmouseco_areawin(mval);
1873 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1874         
1875         /* click in header or outside? */
1876         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1877                 rctf rect= gnode->totr;
1878                 
1879                 rect.ymax += NODE_DY;
1880                 if(BLI_in_rctf(&rect, mx, my)==0)
1881                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1882 //              else
1883 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1884                 
1885                 return 1;
1886         }
1887         return 0;
1888 }
1889
1890 /* checks snode->mouse position, and returns found node/socket */
1891 /* type is SOCK_IN and/or SOCK_OUT */
1892 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1893 {
1894         bNode *node;
1895         bNodeSocket *sock;
1896         rctf rect;
1897         
1898         /* check if we click in a socket */
1899         for(node= snode->edittree->nodes.first; node; node= node->next) {
1900                 
1901                 rect.xmin = snode->mx - (NODE_SOCKSIZE+4);
1902                 rect.ymin = snode->my - (NODE_SOCKSIZE+4);
1903                 rect.xmax = snode->mx + (NODE_SOCKSIZE+4);
1904                 rect.ymax = snode->my + (NODE_SOCKSIZE+4);
1905                 
1906                 if (!(node->flag & NODE_HIDDEN)) {
1907                         /* extra padding inside and out - allow dragging on the text areas too */
1908                         if (in_out == SOCK_IN) {
1909                                 rect.xmax += NODE_SOCKSIZE;
1910                                 rect.xmin -= NODE_SOCKSIZE*4;
1911                         } else if (in_out == SOCK_OUT) {
1912                                 rect.xmax += NODE_SOCKSIZE*4;
1913                                 rect.xmin -= NODE_SOCKSIZE;
1914                         }
1915                 }
1916                 
1917                 if(in_out & SOCK_IN) {
1918                         for(sock= node->inputs.first; sock; sock= sock->next) {
1919                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1920                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1921                                                 if(node == visible_node(snode, &rect)) {
1922                                                         *nodep= node;
1923                                                         *sockp= sock;
1924                                                         return 1;
1925                                                 }
1926                                         }
1927                                 }
1928                         }
1929                 }
1930                 if(in_out & SOCK_OUT) {
1931                         for(sock= node->outputs.first; sock; sock= sock->next) {
1932                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1933                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1934                                                 if(node == visible_node(snode, &rect)) {
1935                                                         *nodep= node;
1936                                                         *sockp= sock;
1937                                                         return 1;
1938                                                 }
1939                                         }
1940                                 }
1941                         }
1942                 }
1943         }
1944         
1945         /* check group sockets
1946          * NB: using ngroup->outputs as input sockets and vice versa here!
1947          */
1948         if(in_out & SOCK_IN) {
1949                 for(sock= snode->edittree->outputs.first; sock; sock= sock->next) {
1950                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1951                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1952                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1953                                         *sockp= sock;
1954                                         return 1;
1955                                 }
1956                         }
1957                 }
1958         }
1959         if(in_out & SOCK_OUT) {
1960                 for(sock= snode->edittree->inputs.first; sock; sock= sock->next) {
1961                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1962                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1963                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1964                                         *sockp= sock;
1965                                         return 1;
1966                                 }
1967                         }
1968                 }
1969         }
1970         
1971         return 0;
1972 }
1973
1974 static int node_socket_hilights(SpaceNode *snode, int in_out)
1975 {
1976         bNode *node;
1977         bNodeSocket *sock, *tsock, *socksel= NULL;
1978         short redraw= 0;
1979         
1980         if(snode->edittree==NULL) return 0;
1981         
1982         /* deselect sockets */
1983         for(node= snode->edittree->nodes.first; node; node= node->next) {
1984                 for(sock= node->inputs.first; sock; sock= sock->next) {
1985                         if(sock->flag & SELECT) {
1986                                 sock->flag &= ~SELECT;
1987                                 redraw++;
1988                                 socksel= sock;
1989                         }
1990                 }
1991                 for(sock= node->outputs.first; sock; sock= sock->next) {
1992                         if(sock->flag & SELECT) {
1993                                 sock->flag &= ~SELECT;
1994                                 redraw++;
1995                                 socksel= sock;
1996                         }
1997                 }
1998         }
1999         
2000         // XXX mousepos should be set here!
2001         
2002         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
2003                 tsock->flag |= SELECT;
2004                 if(redraw==1 && tsock==socksel) redraw= 0;
2005                 else redraw= 1;
2006         }
2007         
2008         return redraw;
2009 }
2010
2011 static int outside_group_rect(SpaceNode *snode)
2012 {
2013         bNode *gnode= node_tree_get_editgroup(snode->nodetree);
2014         if (gnode) {
2015                 return (snode->mx < gnode->totr.xmin || snode->mx >= gnode->totr.xmax
2016                                 || snode->my < gnode->totr.ymin || snode->my >= gnode->totr.ymax);
2017         }
2018         return 0;
2019 }
2020
2021 /* ****************** Add *********************** */
2022
2023
2024 typedef struct bNodeListItem {
2025         struct bNodeListItem *next, *prev;
2026         struct bNode *node;     
2027 } bNodeListItem;
2028
2029 static int sort_nodes_locx(void *a, void *b)
2030 {
2031         bNodeListItem *nli1 = (bNodeListItem *)a;
2032         bNodeListItem *nli2 = (bNodeListItem *)b;
2033         bNode *node1 = nli1->node;
2034         bNode *node2 = nli2->node;
2035         
2036         if (node1->locx > node2->locx)
2037                 return 1;
2038         else 
2039                 return 0;
2040 }
2041
2042 static int socket_is_available(bNodeTree *ntree, bNodeSocket *sock, int allow_used)
2043 {
2044         if (sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))
2045                 return 0;
2046         
2047         if (!allow_used) {
2048                 if (nodeCountSocketLinks(ntree, sock) > 0)
2049                         return 0;
2050         }
2051         return 1;
2052 }
2053
2054 static bNodeSocket *best_socket_output(bNodeTree *ntree, bNode *node, bNodeSocket *sock_target, int allow_multiple)
2055 {
2056         bNodeSocket *sock;
2057         
2058         /* first try to find a socket with a matching name */
2059         for (sock=node->outputs.first; sock; sock=sock->next) {
2060
2061                 if (!socket_is_available(ntree, sock, allow_multiple))
2062                         continue;
2063
2064                 /* check for same types */
2065                 if (sock->type == sock_target->type) {
2066                         if (strcmp(sock->name, sock_target->name)==0)
2067                                 return sock;
2068                 }
2069         }
2070         
2071         /* otherwise settle for the first available socket of the right type */
2072         for (sock=node->outputs.first; sock; sock=sock->next) {
2073
2074                 if (!socket_is_available(ntree, sock, allow_multiple))
2075                         continue;
2076                 
2077                 /* check for same types */
2078                 if (sock->type == sock_target->type) {
2079                         return sock;
2080                 }
2081         }
2082         
2083         return NULL;
2084 }
2085
2086 /* this is a bit complicated, but designed to prioritise finding 
2087  * sockets of higher types, such as image, first */
2088 static bNodeSocket *best_socket_input(bNodeTree *ntree, bNode *node, int num, int replace)
2089 {
2090         bNodeSocket *sock;
2091         int socktype, maxtype=0;
2092         int a = 0;
2093         
2094         for (sock=node->inputs.first; sock; sock=sock->next) {
2095                 maxtype = MAX2(sock->type, maxtype);
2096         }
2097         
2098         /* find sockets of higher 'types' first (i.e. image) */
2099         for (socktype=maxtype; socktype >= 0; socktype--) {
2100                 for (sock=node->inputs.first; sock; sock=sock->next) {
2101                         
2102                         if (!socket_is_available(ntree, sock, replace)) {
2103                                 a++;
2104                                 continue;
2105                         }
2106                                 
2107                         if (sock->type == socktype) {
2108                                 /* increment to make sure we don't keep finding 
2109                                  * the same socket on every attempt running this function */
2110                                 a++;
2111                                 if (a > num)
2112                                         return sock;
2113                         }
2114                 }
2115         }
2116         
2117         return NULL;
2118 }
2119
2120 void snode_autoconnect(SpaceNode *snode, int allow_multiple, int replace)
2121 {
2122         ListBase *nodelist = MEM_callocN(sizeof(ListBase), "items_list");
2123         bNodeListItem *nli;
2124         bNode *node;
2125         bNodeLink *link;
2126         int i, numlinks=0;
2127         
2128         for(node= snode->edittree->nodes.first; node; node= node->next) {
2129                 if(node->flag & NODE_SELECT) {
2130                         nli = MEM_mallocN(sizeof(bNodeListItem), "temporary node list item");
2131                         nli->node = node;
2132                         BLI_addtail(nodelist, nli);
2133                 }
2134         }
2135         
2136         /* sort nodes left to right */
2137         BLI_sortlist(nodelist, sort_nodes_locx);
2138         
2139         for (nli=nodelist->first; nli; nli=nli->next) {
2140                 bNode *node_fr, *node_to;
2141                 bNodeSocket *sock_fr, *sock_to;
2142                 
2143                 if (nli->next == NULL) break;
2144                 
2145                 node_fr = nli->node;
2146                 node_to = nli->next->node;
2147                 
2148                 /* check over input sockets first */
2149                 for (i=0; i<BLI_countlist(&node_to->inputs); i++) {
2150                         
2151                         /* find the best guess input socket */
2152                         sock_to = best_socket_input(snode->edittree, node_to, i, replace);
2153                         if (!sock_to) continue;
2154                         
2155                         /* check for an appropriate output socket to connect from */
2156                         sock_fr = best_socket_output(snode->edittree, node_fr, sock_to, allow_multiple);
2157                         if (!sock_fr) continue;
2158                         
2159                         /* then we can connect */
2160                         if (replace)
2161                                 nodeRemSocketLinks(snode->edittree, sock_to);
2162                         
2163                         link = nodeAddLink(snode->edittree, node_fr, sock_fr, node_to, sock_to);
2164                         /* validate the new link */
2165                         ntreeUpdateTree(snode->edittree);
2166                         if (!(link->flag & NODE_LINK_VALID)) {
2167                                 nodeRemLink(snode->edittree, link);
2168                                 continue;
2169                         }
2170                         
2171                         snode_update(snode, node_to);
2172                         ++numlinks;
2173                         break;
2174                 }
2175         }
2176         
2177         if (numlinks > 0) {
2178                 ntreeUpdateTree(snode->edittree);
2179         }
2180         
2181         BLI_freelistN(nodelist);
2182         MEM_freeN(nodelist);
2183 }
2184
2185 /* can be called from menus too, but they should do own undopush and redraws */
2186 bNode *node_add_node(SpaceNode *snode, Main *bmain, Scene *scene, bNodeTemplate *ntemp, float locx, float locy)
2187 {
2188         bNode *node= NULL, *gnode;
2189         
2190         node_deselectall(snode);
2191         
2192         node = nodeAddNode(snode->edittree, ntemp);
2193         
2194         /* generics */
2195         if(node) {
2196                 node->locx= locx;
2197                 node->locy= locy + 60.0f;               // arbitrary.. so its visible, (0,0) is top of node
2198                 node->flag |= SELECT;
2199                 
2200                 gnode= node_tree_get_editgroup(snode->nodetree);
2201                 if(gnode) {
2202                         node->locx -= gnode->locx;
2203                         node->locy -= gnode->locy;
2204                 }
2205
2206                 ntreeUpdateTree(snode->edittree);
2207                 ED_node_set_active(bmain, snode->edittree, node);
2208                 
2209                 if(snode->nodetree->type==NTREE_COMPOSIT) {
2210                         if(ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE)) {
2211                                 node->id = &scene->id;
2212                         }
2213                         else if(ELEM3(node->type, CMP_NODE_MOVIECLIP, CMP_NODE_MOVIEDISTORTION, CMP_NODE_STABILIZE2D)) {
2214                                 if(G.main->movieclip.first == G.main->movieclip.last) {
2215                                         node->id= G.main->movieclip.first;
2216                                 }
2217                         }
2218                         
2219                         ntreeCompositForceHidden(snode->edittree, scene);
2220                 }
2221                         
2222                 if(node->id)
2223                         id_us_plus(node->id);
2224                         
2225                 snode_update(snode, node);
2226         }
2227         
2228         if(snode->nodetree->type==NTREE_TEXTURE) {
2229                 ntreeTexCheckCyclics(snode->edittree);
2230         }
2231         
2232         return node;
2233 }
2234
2235 /* ****************** Duplicate *********************** */
2236
2237 static int node_duplicate_exec(bContext *C, wmOperator *op)
2238 {
2239         SpaceNode *snode= CTX_wm_space_node(C);
2240         bNodeTree *ntree= snode->edittree;
2241         bNode *node, *newnode, *lastnode;
2242         bNodeLink *link, *newlink, *lastlink;
2243         int keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
2244         
2245         ED_preview_kill_jobs(C);
2246         
2247         lastnode = ntree->nodes.last;
2248         for(node= ntree->nodes.first; node; node= node->next) {
2249                 if(node->flag & SELECT) {
2250                         newnode = nodeCopyNode(ntree, node);
2251                         
2252                         if(newnode->id) {
2253                                 /* simple id user adjustment, node internal functions dont touch this
2254                                  * but operators and readfile.c do. */
2255                                 id_us_plus(newnode->id);
2256                                 /* to ensure redraws or rerenders happen */
2257                                 ED_node_changed_update(snode->id, newnode);
2258                         }
2259                 }
2260                 
2261                 /* make sure we don't copy new nodes again! */
2262                 if (node==lastnode)
2263                         break;
2264         }
2265         
2266         /* copy links between selected nodes
2267          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2268          */
2269         lastlink = ntree->links.last;
2270         for (link=ntree->links.first; link; link=link->next) {
2271                 /* This creates new links between copied nodes.
2272                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
2273                  */
2274                 if (link->tonode && (link->tonode->flag & NODE_SELECT)
2275                         && (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT)))) {
2276                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2277                         newlink->flag = link->flag;
2278                         newlink->tonode = link->tonode->new_node;
2279                         newlink->tosock = link->tosock->new_sock;
2280                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
2281                                 newlink->fromnode = link->fromnode->new_node;
2282                                 newlink->fromsock = link->fromsock->new_sock;
2283                         }
2284                         else {
2285                                 /* input node not copied, this keeps the original input linked */
2286                                 newlink->fromnode = link->fromnode;
2287                                 newlink->fromsock = link->fromsock;
2288                         }
2289                         
2290                         BLI_addtail(&ntree->links, newlink);
2291                 }
2292                 
2293                 /* make sure we don't copy new links again! */
2294                 if (link==lastlink)
2295                         break;
2296         }
2297         
2298         /* deselect old nodes, select the copies instead */
2299         for(node= ntree->nodes.first; node; node= node->next) {
2300                 if(node->flag & SELECT) {
2301                         /* has been set during copy above */
2302                         newnode = node->new_node;
2303                         
2304                         node->flag &= ~(NODE_SELECT|NODE_ACTIVE);
2305                         newnode->flag |= NODE_SELECT;
2306                 }
2307                 
2308                 /* make sure we don't copy new nodes again! */
2309                 if (node==lastnode)
2310                         break;
2311         }
2312         
2313         ntreeUpdateTree(snode->edittree);
2314         
2315         snode_notify(C, snode);
2316         snode_dag_update(C, snode);
2317
2318         return OPERATOR_FINISHED;
2319 }
2320
2321 void NODE_OT_duplicate(wmOperatorType *ot)
2322 {
2323         /* identifiers */
2324         ot->name= "Duplicate Nodes";
2325         ot->description = "Duplicate selected nodes";
2326         ot->idname= "NODE_OT_duplicate";
2327         
2328         /* api callbacks */
2329         ot->exec= node_duplicate_exec;
2330         ot->poll= ED_operator_node_active;
2331         
2332         /* flags */
2333         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2334         
2335         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
2336 }
2337
2338 /* *************************** add link op ******************** */
2339
2340 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
2341 {
2342         bNodeLink *tlink;
2343         bNodeSocket *sock;
2344         
2345         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
2346                 
2347                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
2348                         if(link!=tlink && tlink->tosock==link->tosock)
2349                                 break;
2350                 }
2351                 if(tlink) {
2352                         /* try to move the existing link to the next available socket */
2353                         if (tlink->tonode) {
2354                                 /* is there a free input socket with the target type? */
2355                                 for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
2356                                         if(sock->type==tlink->tosock->type)
2357                                                 if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
2358                                                         break;
2359                                 }
2360                                 if(sock) {
2361                                         tlink->tosock= sock;
2362                                         sock->flag &= ~SOCK_HIDDEN;
2363                                 }
2364                                 else {
2365                                         nodeRemLink(snode->edittree, tlink);
2366                                 }
2367                         }
2368                         else
2369                                 nodeRemLink(snode->edittree, tlink);
2370                 }
2371         }
2372 }
2373
2374 /* loop that adds a nodelink, called by function below  */
2375 /* in_out = starting socket */
2376 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
2377 {
2378         SpaceNode *snode= CTX_wm_space_node(C);
2379         ARegion *ar= CTX_wm_region(C);
2380         bNodeLinkDrag *nldrag= op->customdata;
2381         bNode *tnode, *node;
2382         bNodeSocket *tsock= NULL, *sock;
2383         bNodeLink *link;
2384         int in_out;
2385
2386         in_out= nldrag->in_out;
2387         node= nldrag->node;
2388         sock= nldrag->sock;
2389         link= nldrag->link;
2390         
2391         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2392                                                          &snode->mx, &snode->my);
2393
2394         switch (event->type) {
2395                 case MOUSEMOVE:
2396                         
2397                         if(in_out==SOCK_OUT) {
2398                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
2399                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2400                                                 if( link->tosock!= tsock && (!tnode || (tnode!=node && link->tonode!=tnode)) ) {
2401                                                         link->tonode= tnode;
2402                                                         link->tosock= tsock;
2403                                                         if (link->prev==NULL && link->next==NULL) {
2404                                                                 BLI_addtail(&snode->edittree->links, link);
2405                                                         }
2406                                                         
2407                                                         snode->edittree->update |= NTREE_UPDATE_LINKS;
2408                                                         ntreeUpdateTree(snode->edittree);
2409                                                 }
2410                                         }
2411                                 }
2412                                 else {
2413                                         if (link->tonode || link->tosock) {
2414                                                 BLI_remlink(&snode->edittree->links, link);
2415                                                 link->prev = link->next = NULL;
2416                                                 link->tonode= NULL;
2417                                                 link->tosock= NULL;
2418                                                 
2419                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2420                                                 ntreeUpdateTree(snode->edittree);
2421                                         }
2422                                 }
2423                         }
2424                         else {
2425                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
2426                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2427                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
2428                                                         if( link->fromsock!= tsock && (!tnode || (tnode!=node && link->fromnode!=tnode)) ) {
2429                                                                 link->fromnode= tnode;
2430                                                                 link->fromsock= tsock;
2431                                                                 if (link->prev==NULL && link->next==NULL) {
2432                                                                         BLI_addtail(&snode->edittree->links, link);
2433                                                                 }
2434                                                                 
2435                                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2436                                                                 ntreeUpdateTree(snode->edittree);
2437                                                         }
2438                                                 }
2439                                         }
2440                                 }
2441                                 else {
2442                                         if (link->tonode || link->tosock) {
2443                                                 BLI_remlink(&snode->edittree->links, link);
2444                                                 link->prev = link->next = NULL;
2445                                                 link->fromnode= NULL;
2446                                                 link->fromsock= NULL;
2447                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2448                                                 ntreeUpdateTree(snode->edittree);
2449                                         }
2450                                 }
2451                         }
2452                         /* hilight target sockets only */
2453                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
2454                         ED_region_tag_redraw(ar);
2455                         break;
2456                         
2457                 case LEFTMOUSE:
2458                 case RIGHTMOUSE:
2459                 case MIDDLEMOUSE:
2460                         if(link->tosock && link->fromsock) {
2461                                 /* send changed events for original tonode and new */
2462                                 snode_update(snode, link->tonode);
2463                                 
2464                                 /* we might need to remove a link */
2465                                 if(in_out==SOCK_OUT)
2466                                         node_remove_extra_links(snode, link->tosock, link);
2467                                 
2468                                 /* when linking to group outputs, update the socket type */
2469                                 /* XXX this should all be part of a generic update system */
2470                                 if (!link->tonode) {
2471                                         link->tosock->type = link->fromsock->type;
2472                                 }
2473                         }
2474                         else if (outside_group_rect(snode) && (link->tonode || link->fromnode)) {
2475                                 /* automatically add new group socket */
2476                                 if (link->tonode && link->tosock) {
2477                                         link->fromsock = node_group_expose_socket(snode->edittree, link->tosock, SOCK_IN);
2478                                         link->fromnode = NULL;
2479                                         if (link->prev==NULL && link->next==NULL) {
2480                                                 BLI_addtail(&snode->edittree->links, link);
2481                                         }
2482                                         snode->edittree->update |= NTREE_UPDATE_GROUP_IN | NTREE_UPDATE_LINKS;
2483                                 }
2484                                 else if (link->fromnode && link->fromsock) {
2485                                         link->tosock = node_group_expose_socket(snode->edittree, link->fromsock, SOCK_OUT);
2486                                         link->tonode = NULL;
2487                                         if (link->prev==NULL && link->next==NULL) {
2488                                                 BLI_addtail(&snode->edittree->links, link);
2489                                         }
2490                                         snode->edittree->update |= NTREE_UPDATE_GROUP_OUT | NTREE_UPDATE_LINKS;
2491                                 }
2492                         }
2493                         else
2494                                 nodeRemLink(snode->edittree, link);
2495                         
2496                         ntreeUpdateTree(snode->edittree);
2497                         snode_notify(C, snode);
2498                         snode_dag_update(C, snode);
2499                         
2500                         BLI_remlink(&snode->linkdrag, nldrag);
2501                         MEM_freeN(nldrag);
2502                         
2503                         return OPERATOR_FINISHED;
2504         }
2505         
2506         return OPERATOR_RUNNING_MODAL;
2507 }
2508
2509 /* return 1 when socket clicked */
2510 static int node_link_init(SpaceNode *snode, bNodeLinkDrag *nldrag)
2511 {
2512         bNodeLink *link;
2513
2514         /* output indicated? */
2515         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
2516                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2517                         return SOCK_OUT;
2518                 else {
2519                         /* find if we break a link */
2520                         for(link= snode->edittree->links.first; link; link= link->next) {
2521                                 if(link->fromsock==nldrag->sock)
2522                                         break;
2523                         }
2524                         if(link) {
2525                                 nldrag->node= link->tonode;
2526                                 nldrag->sock= link->tosock;
2527                                 nodeRemLink(snode->edittree, link);
2528                                 return SOCK_IN;
2529                         }
2530                 }
2531         }
2532         /* or an input? */
2533         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
2534                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2535                         return SOCK_IN;
2536                 else {
2537                         /* find if we break a link */
2538                         for(link= snode->edittree->links.first; link; link= link->next) {
2539                                 if(link->tosock==nldrag->sock)
2540                                         break;
2541                         }
2542                         if(link) {
2543                                 /* send changed event to original tonode */
2544                                 if(link->tonode) 
2545                                         snode_update(snode, link->tonode);
2546                                 
2547                                 nldrag->node= link->fromnode;
2548                                 nldrag->sock= link->fromsock;
2549                                 nodeRemLink(snode->edittree, link);
2550                                 return SOCK_OUT;
2551                         }
2552                 }
2553         }
2554         
2555         return 0;
2556 }
2557
2558 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2559 {
2560         SpaceNode *snode= CTX_wm_space_node(C);
2561         ARegion *ar= CTX_wm_region(C);
2562         bNodeLinkDrag *nldrag= MEM_callocN(sizeof(bNodeLinkDrag), "drag link op customdata");
2563         
2564         
2565         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2566                                                          &snode->mx, &snode->my);
2567
2568         ED_preview_kill_jobs(C);
2569
2570         nldrag->in_out= node_link_init(snode, nldrag);
2571         
2572         if(nldrag->in_out) {
2573                 op->customdata= nldrag;
2574                 
2575                 /* we make a temporal link */
2576                 if(nldrag->in_out==SOCK_OUT) {
2577                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2578                         nldrag->link->fromnode= nldrag->node;
2579                         nldrag->link->fromsock= nldrag->sock;
2580                         nldrag->link->tonode= NULL;
2581                         nldrag->link->tosock= NULL;
2582                 }
2583                 else {
2584                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2585                         nldrag->link->fromnode= NULL;
2586                         nldrag->link->fromsock= NULL;
2587                         nldrag->link->tonode= nldrag->node;
2588                         nldrag->link->tosock= nldrag->sock;
2589                 }
2590                 BLI_addtail(&snode->linkdrag, nldrag);
2591                 
2592                 /* add modal handler */
2593                 WM_event_add_modal_handler(C, op);
2594                 
2595                 return OPERATOR_RUNNING_MODAL;
2596         }
2597         else {
2598                 MEM_freeN(nldrag);
2599                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2600         }
2601 }
2602
2603 static int node_link_cancel(bContext *C, wmOperator *op)
2604 {
2605         SpaceNode *snode= CTX_wm_space_node(C);
2606         bNodeLinkDrag *nldrag= op->customdata;
2607
2608         nodeRemLink(snode->edittree, nldrag->link);
2609         BLI_remlink(&snode->linkdrag, nldrag);
2610         MEM_freeN(nldrag);
2611
2612         return OPERATOR_CANCELLED;
2613 }
2614
2615 void NODE_OT_link(wmOperatorType *ot)
2616 {
2617         /* identifiers */
2618         ot->name= "Link Nodes";
2619         ot->idname= "NODE_OT_link";
2620         
2621         /* api callbacks */
2622         ot->invoke= node_link_invoke;
2623         ot->modal= node_link_modal;
2624 //      ot->exec= node_link_exec;
2625         ot->poll= ED_operator_node_active;
2626         ot->cancel= node_link_cancel;
2627         
2628         /* flags */
2629         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2630 }
2631
2632 /* ********************** Make Link operator ***************** */
2633
2634 /* makes a link between selected output and input sockets */
2635 static int node_make_link_exec(bContext *C, wmOperator *op)
2636 {
2637         SpaceNode *snode= CTX_wm_space_node(C);
2638         int replace = RNA_boolean_get(op->ptr, "replace");
2639
2640         ED_preview_kill_jobs(C);
2641
2642         snode_autoconnect(snode, 1, replace);
2643
2644         ntreeUpdateTree(snode->edittree);
2645         snode_notify(C, snode);
2646         snode_dag_update(C, snode);
2647         
2648         return OPERATOR_FINISHED;
2649 }
2650
2651 void NODE_OT_link_make(wmOperatorType *ot)
2652 {
2653         /* identifiers */
2654         ot->name= "Make Links";
2655         ot->description= "Makes a link between selected output in input sockets";
2656         ot->idname= "NODE_OT_link_make";
2657         
2658         /* callbacks */
2659         ot->exec= node_make_link_exec;
2660         ot->poll= ED_operator_node_active; // XXX we need a special poll which checks that there are selected input/output sockets
2661         
2662         /* flags */
2663         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2664         
2665         RNA_def_boolean(ot->srna, "replace", 0, "Replace", "Replace socket connections with the new links");
2666 }
2667
2668 /* ********************** Cut Link operator ***************** */
2669
2670 #define LINK_RESOL 12
2671 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2672 {
2673         float coord_array[LINK_RESOL+1][2];
2674         int i, b;
2675         
2676         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2677
2678                 for(i=0; i<tot-1; i++)
2679                         for(b=0; b<LINK_RESOL; b++)
2680                                 if(isect_line_line_v2(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2681                                         return 1;
2682         }
2683         return 0;
2684 }
2685
2686 static int cut_links_exec(bContext *C, wmOperator *op)
2687 {
2688         SpaceNode *snode= CTX_wm_space_node(C);
2689         ARegion *ar= CTX_wm_region(C);
2690         float mcoords[256][2];
2691         int i= 0;
2692         
2693         RNA_BEGIN(op->ptr, itemptr, "path") {
2694                 float loc[2];
2695                 
2696                 RNA_float_get_array(&itemptr, "loc", loc);
2697                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2698                                                                  &mcoords[i][0], &mcoords[i][1]);
2699                 i++;
2700                 if(i>= 256) break;
2701         }
2702         RNA_END;
2703         
2704         if(i>1) {
2705                 bNodeLink *link, *next;
2706
2707                 ED_preview_kill_jobs(C);
2708                 
2709                 for(link= snode->edittree->links.first; link; link= next) {
2710                         next= link->next;
2711                         
2712                         if(cut_links_intersect(link, mcoords, i)) {
2713                                 snode_update(snode, link->tonode);
2714                                 nodeRemLink(snode->edittree, link);
2715                         }
2716                 }
2717                 
2718                 ntreeUpdateTree(snode->edittree);
2719                 snode_notify(C, snode);
2720                 snode_dag_update(C, snode);
2721                 
2722                 return OPERATOR_FINISHED;
2723         }
2724         
2725         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2726 }
2727
2728 void NODE_OT_links_cut(wmOperatorType *ot)
2729 {
2730         PropertyRNA *prop;
2731         
2732         ot->name= "Cut links";
2733         ot->idname= "NODE_OT_links_cut";
2734         
2735         ot->invoke= WM_gesture_lines_invoke;
2736         ot->modal= WM_gesture_lines_modal;
2737         ot->exec= cut_links_exec;
2738         ot->cancel= WM_gesture_lines_cancel;
2739         
2740         ot->poll= ED_operator_node_active;
2741         
2742         /* flags */
2743         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2744         
2745         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2746         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2747         /* internal */
2748         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2749 }
2750
2751 /* *********************  automatic node insert on dragging ******************* */
2752
2753 /* assumes sockets in list */
2754 static bNodeSocket *socket_best_match(ListBase *sockets, int type)
2755 {
2756         bNodeSocket *sock;
2757         
2758         /* first, match type */
2759         for(sock= sockets->first; sock; sock= sock->next)
2760                 if(!(sock->flag & SOCK_HIDDEN))
2761                         if(type == sock->type)
2762                                 return sock;
2763         
2764         /* then just use first unhidden socket */
2765         for(sock= sockets->first; sock; sock= sock->next)
2766                 if(!(sock->flag & SOCK_HIDDEN))
2767                         return sock;
2768
2769         /* OK, let's unhide proper one */
2770         for(sock= sockets->first; sock; sock= sock->next) {
2771                 if(type == sock->type) {
2772                         sock->flag &= ~SOCK_HIDDEN;
2773                         return sock;
2774                 }
2775         }
2776         
2777         /* just the first */
2778         sock= sockets->first;
2779         sock->flag &= ~SOCK_HIDDEN;
2780         
2781         return sockets->first;
2782 }
2783
2784 /* prevent duplicate testing code below */
2785 static SpaceNode *ed_node_link_conditions(ScrArea *sa, bNode **select)
2786 {
2787         SpaceNode *snode= sa?sa->spacedata.first:NULL;
2788         bNode *node;
2789         bNodeLink *link;
2790         
2791         /* no unlucky accidents */
2792         if(sa==NULL || sa->spacetype!=SPACE_NODE) return NULL;
2793         
2794         *select= NULL;
2795         
2796         for(node= snode->edittree->nodes.first; node; node= node->next) {
2797                 if(node->flag & SELECT) {
2798                         if(*select)
2799                                 break;
2800                         else
2801                                 *select= node;
2802                 }
2803         }
2804         /* only one selected */
2805         if(node || *select==NULL) return NULL;
2806         
2807         /* correct node */
2808         if((*select)->inputs.first==NULL || (*select)->outputs.first==NULL) return NULL;
2809         
2810         /* test node for links */
2811         for(link= snode->edittree->links.first; link; link=link->next) {
2812                 if(link->tonode == *select || link->fromnode == *select)
2813                         return NULL;
2814         }
2815         
2816         return snode;
2817 }
2818
2819 /* assumes link with NODE_LINKFLAG_HILITE set */
2820 void ED_node_link_insert(ScrArea *sa)
2821 {
2822         bNode *node, *select;
2823         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2824         bNodeLink *link;
2825         bNodeSocket *sockto;
2826         
2827         if(snode==NULL) return;
2828         
2829         /* get the link */
2830         for(link= snode->edittree->links.first; link; link=link->next)
2831                 if(link->flag & NODE_LINKFLAG_HILITE)
2832                         break;
2833         
2834         if(link) {
2835                 node= link->tonode;
2836                 sockto= link->tosock;
2837                 
2838                 link->tonode= select;
2839                 link->tosock= socket_best_match(&select->inputs, link->fromsock->type);
2840                 link->flag &= ~NODE_LINKFLAG_HILITE;
2841                 
2842                 nodeAddLink(snode->edittree, select, socket_best_match(&select->outputs, sockto->type), node, sockto);
2843                 ntreeUpdateTree(snode->edittree);       /* needed for pointers */
2844                 snode_update(snode, select);
2845                 ED_node_changed_update(snode->id, select);
2846         }
2847 }
2848
2849
2850 /* test == 0, clear all intersect flags */
2851 void ED_node_link_intersect_test(ScrArea *sa, int test)
2852 {
2853         bNode *select;
2854         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2855         bNodeLink *link, *selink=NULL;
2856         float mcoords[6][2];
2857         
2858         if(snode==NULL) return;
2859         
2860         /* clear flags */
2861         for(link= snode->edittree->links.first; link; link=link->next)
2862                 link->flag &= ~NODE_LINKFLAG_HILITE;
2863         
2864         if(test==0) return;
2865         
2866         /* okay, there's 1 node, without links, now intersect */
2867         mcoords[0][0]= select->totr.xmin;
2868         mcoords[0][1]= select->totr.ymin;
2869         mcoords[1][0]= select->totr.xmax;
2870         mcoords[1][1]= select->totr.ymin;
2871         mcoords[2][0]= select->totr.xmax;
2872         mcoords[2][1]= select->totr.ymax;
2873         mcoords[3][0]= select->totr.xmin;
2874         mcoords[3][1]= select->totr.ymax;
2875         mcoords[4][0]= select->totr.xmin;
2876         mcoords[4][1]= select->totr.ymin;
2877         mcoords[5][0]= select->totr.xmax;
2878         mcoords[5][1]= select->totr.ymax;
2879         
2880         /* we only tag a single link for intersect now */
2881         /* idea; use header dist when more? */
2882         for(link= snode->edittree->links.first; link; link=link->next) {
2883                 
2884                 if(cut_links_intersect(link, mcoords, 5)) { /* intersect code wants edges */
2885                         if(selink) 
2886                                 break;
2887                         selink= link;
2888                 }
2889         }
2890                 
2891         if(link==NULL && selink)
2892                 selink->flag |= NODE_LINKFLAG_HILITE;
2893 }
2894
2895
2896 /* ******************************** */
2897 // XXX some code needing updating to operators...
2898
2899
2900 /* goes over all scenes, reads render layers */
2901 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
2902 {
2903         Main *bmain= CTX_data_main(C);
2904         SpaceNode *snode= CTX_wm_space_node(C);
2905         Scene *curscene= CTX_data_scene(C), *scene;
2906         bNode *node;
2907
2908         ED_preview_kill_jobs(C);
2909
2910         /* first tag scenes unread */
2911         for(scene= bmain->scene.first; scene; scene= scene->id.next) 
2912                 scene->id.flag |= LIB_DOIT;
2913
2914         for(node= snode->edittree->nodes.first; node; node= node->next) {
2915                 if(node->type==CMP_NODE_R_LAYERS) {
2916                         ID *id= node->id;
2917                         if(id->flag & LIB_DOIT) {
2918                                 RE_ReadRenderResult(curscene, (Scene *)id);
2919                                 ntreeCompositTagRender((Scene *)id);
2920                                 id->flag &= ~LIB_DOIT;
2921                         }
2922                 }
2923         }
2924         
2925         snode_notify(C, snode);
2926         snode_dag_update(C, snode);
2927
2928         return OPERATOR_FINISHED;
2929 }
2930
2931 void NODE_OT_read_renderlayers(wmOperatorType *ot)
2932 {
2933         
2934         ot->name= "Read Render Layers";
2935         ot->idname= "NODE_OT_read_renderlayers";
2936         
2937         ot->exec= node_read_renderlayers_exec;
2938         
2939         ot->poll= composite_node_active;
2940         
2941         /* flags */
2942         ot->flag= 0;
2943 }
2944
2945 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
2946 {
2947         Main *bmain= CTX_data_main(C);
2948         SpaceNode *snode= CTX_wm_space_node(C);
2949         Scene *curscene= CTX_data_scene(C);
2950         Render *re= RE_NewRender(curscene->id.name);
2951
2952         WM_cursor_wait(1);
2953         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
2954         WM_cursor_wait(0);
2955
2956         /* note we are careful to send the right notifier, as otherwise the
2957            compositor would reexecute and overwrite the full sample result */
2958         WM_event_add_notifier(C, NC_SCENE|ND_COMPO_RESULT, NULL);
2959
2960         return OPERATOR_FINISHED;
2961 }
2962
2963
2964 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
2965 {
2966         
2967         ot->name= "Read Full Sample Layers";
2968         ot->idname= "NODE_OT_read_fullsamplelayers";
2969         
2970         ot->exec= node_read_fullsamplelayers_exec;
2971         
2972         ot->poll= composite_node_active;
2973         
2974         /* flags */
2975         ot->flag= 0;
2976 }
2977
2978 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
2979 {
2980         Scene *sce= CTX_data_scene(C);
2981         bNode *node;
2982         
2983         for(node= sce->nodetree->nodes.first; node; node= node->next) {
2984                 if(node->id==(ID *)sce && node->need_exec) {
2985                         break;
2986                 }
2987         }
2988         if(node) {
2989                 SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2990                 
2991                 if(srl) {
2992                         PointerRNA op_ptr;
2993                         
2994                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
2995                         RNA_string_set(&op_ptr, "layer", srl->name);
2996                         RNA_string_set(&op_ptr, "scene", sce->id.name+2);
2997                         
2998                         /* to keep keypositions */
2999                         sce->r.scemode |= R_NO_FRAME_UPDATE;
3000                         
3001                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
3002
3003                         WM_operator_properties_free(&op_ptr);
3004                         
3005                         return OPERATOR_FINISHED;
3006                 }
3007                    
3008         }
3009         return OPERATOR_CANCELLED;
3010 }
3011
3012 void NODE_OT_render_changed(wmOperatorType *ot)
3013 {
3014         
3015         ot->name= "Render Changed Layer";
3016         ot->idname= "NODE_OT_render_changed";
3017         
3018         ot->exec= node_render_changed_exec;
3019         
3020         ot->poll= composite_node_active;
3021         
3022         /* flags */
3023         ot->flag= 0;
3024 }
3025
3026
3027 /* ****************** Make Group operator ******************* */
3028
3029 static int node_group_make_exec(bContext *C, wmOperator *op)
3030 {
3031         SpaceNode *snode = CTX_wm_space_node(C);
3032         bNode *gnode;
3033         
3034         if(snode->edittree!=snode->nodetree) {
3035                 BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
3036                 return OPERATOR_CANCELLED;
3037         }
3038         
3039         /* for time being... is too complex to handle */
3040         if(snode->treetype==NTREE_COMPOSIT) {
3041                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
3042                         if(gnode->flag & SELECT)
3043                                 if(gnode->type==CMP_NODE_R_LAYERS)
3044                                         break;
3045                 }
3046                 
3047                 if(gnode) {
3048                         BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
3049                         return OPERATOR_CANCELLED;
3050                 }
3051         }
3052
3053         ED_preview_kill_jobs(C);
3054         
3055         gnode= node_group_make_from_selected(snode->nodetree);
3056         if(gnode==NULL) {
3057                 BKE_report(op->reports, RPT_WARNING, "Can not make Group");
3058                 return OPERATOR_CANCELLED;
3059         }
3060         else {
3061                 nodeSetActive(snode->nodetree, gnode);
3062                 ntreeUpdateTree(snode->nodetree);
3063         }
3064         
3065         snode_notify(C, snode);
3066         snode_dag_update(C, snode);
3067         
3068         return OPERATOR_FINISHED;
3069 }
3070
3071 void NODE_OT_group_make(wmOperatorType *ot)
3072 {
3073         /* identifiers */
3074         ot->name = "Group";
3075         ot->description = "Make group from selected nodes";
3076         ot->idname = "NODE_OT_group_make";
3077         
3078         /* api callbacks */
3079         ot->exec = node_group_make_exec;
3080         ot->poll = ED_operator_node_active;
3081         
3082         /* flags */
3083         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
3084 }
3085
3086 /* ****************** Hide operator *********************** */
3087
3088 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
3089 {
3090         int tot_eq= 0, tot_neq= 0;
3091         bNode *node;
3092
3093         for(node= snode->edittree->nodes.first; node; node= node->next) {
3094                 if(node->flag & SELECT) {
3095
3096                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3097                                 continue;
3098
3099                         if(node->flag & toggle_flag)
3100                                 tot_eq++;
3101                         else
3102                                 tot_neq++;
3103                 }
3104         }
3105         for(node= snode->edittree->nodes.first; node; node= node->next) {
3106                 if(node->flag & SELECT) {
3107
3108                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3109                                 continue;
3110
3111                         if( (tot_eq && tot_neq) || tot_eq==0)
3112                                 node->flag |= toggle_flag;
3113                         else
3114                                 node->flag &= ~toggle_flag;
3115                 }
3116         }
3117 }
3118
3119 static int node_hide_exec(bContext *C, wmOperator *UNUSED(op))
3120 {
3121         SpaceNode *snode= CTX_wm_space_node(C);
3122         
3123         /* sanity checking (poll callback checks this already) */
3124         if((snode == NULL) || (snode->edittree == NULL))
3125                 return OPERATOR_CANCELLED;
3126         
3127         node_flag_toggle_exec(snode, NODE_HIDDEN);
3128         
3129         snode_notify(C, snode);
3130         
3131         return OPERATOR_FINISHED;
3132 }
3133
3134 void NODE_OT_hide_toggle(wmOperatorType *ot)
3135 {
3136         /* identifiers */
3137         ot->name= "Hide";
3138         ot->description= "Toggle hiding of selected nodes";
3139         ot->idname= "NODE_OT_hide_toggle";
3140         
3141         /* callbacks */
3142         ot->exec= node_hide_exec;
3143         ot->poll= ED_operator_node_active;
3144
3145         /* flags */
3146         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3147 }
3148
3149 static int node_preview_exec(bContext *C, wmOperator *UNUSED(op))
3150 {
3151         SpaceNode *snode= CTX_wm_space_node(C);
3152
3153         /* sanity checking (poll callback checks this already) */
3154         if((snode == NULL) || (snode->edittree == NULL))
3155                 return OPERATOR_CANCELLED;
3156
3157         ED_preview_kill_jobs(C);
3158
3159         node_flag_toggle_exec(snode, NODE_PREVIEW);
3160
3161         snode_notify(C, snode);
3162
3163         return OPERATOR_FINISHED;
3164 }
3165
3166 void NODE_OT_preview_toggle(wmOperatorType *ot)
3167 {
3168         /* identifiers */
3169         ot->name= "Toggle Node Preview";
3170         ot->description= "Toggle preview display for selected nodes";
3171         ot->idname= "NODE_OT_preview_toggle";
3172
3173         /* callbacks */
3174         ot->exec= node_preview_exec;
3175         ot->poll= ED_operator_node_active;
3176
3177         /* flags */
3178         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3179 }
3180