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