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