Cycles: svn merge -r39132:39457 https://svn.blender.org/svnroot/bf-blender/trunk...
[blender-staging.git] / source / blender / editors / space_node / node_edit.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2005 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): David Millan Escriva, Juho Vepsäläinen, Nathan Letwory
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/editors/space_node/node_edit.c
31  *  \ingroup spnode
32  */
33
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <math.h>
38 #include <string.h>
39 #include <errno.h>
40
41 #include "MEM_guardedalloc.h"
42
43 #include "DNA_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, closure_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                         closure_type = SH_NODE_BSDF_DIFFUSE;
286                         break;
287                 case ID_WO:
288                         ((World*)id)->nodetree = ntree;
289                         output_type = SH_NODE_OUTPUT_WORLD;
290                         closure_type = SH_NODE_BACKGROUND;
291                         break;
292                 case ID_LA:
293                         ((Lamp*)id)->nodetree = ntree;
294                         output_type = SH_NODE_OUTPUT_LAMP;
295                         closure_type = SH_NODE_EMISSION;
296                         break;
297                 case ID_TE:
298                         ((Tex*)id)->nodetree = ntree;
299                         output_type = SH_NODE_OUTPUT_TEXTURE;
300                         closure_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, closure_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                                 bNode *tnode;
616                                 
617                                 for(tnode= ntree->nodes.first; tnode; tnode= tnode->next)
618                                         if( tnode->type==CMP_NODE_COMPOSITE)
619                                                 tnode->flag &= ~NODE_DO_OUTPUT;
620                                 
621                                 node->flag |= NODE_DO_OUTPUT;
622                                 ED_node_generic_update(bmain, ntree, node);
623                         }
624                 }
625                 else if(ntree->type==NTREE_TEXTURE) {
626                         // XXX
627 #if 0
628                         if(node->id)
629                                 ; // XXX BIF_preview_changed(-1);
630                         // allqueue(REDRAWBUTSSHADING, 1);
631                         // allqueue(REDRAWIPO, 0);
632 #endif
633                 }
634         }
635 }
636
637 /* when links in groups change, inputs/outputs change, nodes added/deleted... */
638 void node_tree_verify_groups(bNodeTree *nodetree)
639 {
640         bNode *gnode;
641         
642         gnode= node_tree_get_editgroup(nodetree);
643         
644         /* does all materials */
645         if(gnode)
646                 nodeGroupVerify((bNodeTree *)gnode->id);
647         
648 }
649
650 /* ***************** Edit Group operator ************* */
651
652 void snode_make_group_editable(SpaceNode *snode, bNode *gnode)
653 {
654         bNode *node;
655         
656         /* make sure nothing has group editing on */
657         for(node= snode->nodetree->nodes.first; node; node= node->next)
658                 node->flag &= ~NODE_GROUP_EDIT;
659         
660         if(gnode==NULL) {
661                 /* with NULL argument we do a toggle */
662                 if(snode->edittree==snode->nodetree)
663                         gnode= nodeGetActive(snode->nodetree);
664         }
665         
666         if(gnode && gnode->type==NODE_GROUP && gnode->id) {
667                 if(gnode->id->lib)
668                         ntreeMakeLocal((bNodeTree *)gnode->id);
669
670                 gnode->flag |= NODE_GROUP_EDIT;
671                 snode->edittree= (bNodeTree *)gnode->id;
672                 
673                 /* deselect all other nodes, so we can also do grabbing of entire subtree */
674                 for(node= snode->nodetree->nodes.first; node; node= node->next)
675                         node->flag &= ~SELECT;
676                 gnode->flag |= SELECT;
677                 
678         }
679         else 
680                 snode->edittree= snode->nodetree;
681         
682         ntreeSolveOrder(snode->nodetree);
683 }
684
685 static int node_group_edit_exec(bContext *C, wmOperator *UNUSED(op))
686 {
687         SpaceNode *snode = CTX_wm_space_node(C);
688         bNode *gnode;
689
690         ED_preview_kill_jobs(C);
691
692         gnode= nodeGetActive(snode->edittree);
693         snode_make_group_editable(snode, gnode);
694
695         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
696
697         return OPERATOR_FINISHED;
698 }
699
700 static int node_group_edit_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
701 {
702         SpaceNode *snode = CTX_wm_space_node(C);
703         bNode *gnode;
704
705         gnode= nodeGetActive(snode->edittree);
706         if(gnode && gnode->type==NODE_GROUP && gnode->id && gnode->id->lib) {
707                 uiPupMenuOkee(C, op->type->idname, "Make group local?");
708                 return OPERATOR_CANCELLED;
709         }
710
711         return node_group_edit_exec(C, op);
712 }
713
714 void NODE_OT_group_edit(wmOperatorType *ot)
715 {
716         /* identifiers */
717         ot->name = "Edit Group";
718         ot->description = "Edit node group";
719         ot->idname = "NODE_OT_group_edit";
720         
721         /* api callbacks */
722         ot->invoke = node_group_edit_invoke;
723         ot->exec = node_group_edit_exec;
724         ot->poll = ED_operator_node_active;
725         
726         /* flags */
727         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
728 }
729
730 /* ***************** Add Group Socket operator ************* */
731
732 static int node_group_socket_add_exec(bContext *C, wmOperator *op)
733 {
734         SpaceNode *snode = CTX_wm_space_node(C);
735         int in_out= -1;
736         char name[32]= "";
737         int type= SOCK_VALUE;
738         bNodeTree *ngroup= snode->edittree;
739         bNodeSocket *sock;
740         
741         ED_preview_kill_jobs(C);
742         
743         if (RNA_property_is_set(op->ptr, "name"))
744                 RNA_string_get(op->ptr, "name", name);
745         
746         if (RNA_property_is_set(op->ptr, "type"))
747                 type = RNA_enum_get(op->ptr, "type");
748         
749         if (RNA_property_is_set(op->ptr, "in_out"))
750                 in_out = RNA_enum_get(op->ptr, "in_out");
751         else
752                 return OPERATOR_CANCELLED;
753         
754         sock = nodeGroupAddSocket(ngroup, name, type, in_out);
755         
756         node_tree_verify_groups(snode->nodetree);
757         
758         snode_notify(C, snode);
759         
760         return OPERATOR_FINISHED;
761 }
762
763 void NODE_OT_group_socket_add(wmOperatorType *ot)
764 {
765         /* identifiers */
766         ot->name = "Add Group Socket";
767         ot->description = "Add node group socket";
768         ot->idname = "NODE_OT_group_socket_add";
769         
770         /* api callbacks */
771         ot->exec = node_group_socket_add_exec;
772         ot->poll = ED_operator_node_active;
773         
774         /* flags */
775         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
776         
777         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
778         RNA_def_string(ot->srna, "name", "", 32, "Name", "Group socket name");
779         RNA_def_enum(ot->srna, "type", node_socket_type_items, SOCK_VALUE, "Type", "Type of the group socket");
780 }
781
782 /* ***************** Remove Group Socket operator ************* */
783
784 static int node_group_socket_remove_exec(bContext *C, wmOperator *op)
785 {
786         SpaceNode *snode = CTX_wm_space_node(C);
787         int index= -1;
788         int in_out= -1;
789         bNodeTree *ngroup= snode->edittree;
790         bNodeSocket *sock;
791         
792         ED_preview_kill_jobs(C);
793         
794         if (RNA_property_is_set(op->ptr, "index"))
795                 index = RNA_int_get(op->ptr, "index");
796         else
797                 return OPERATOR_CANCELLED;
798         
799         if (RNA_property_is_set(op->ptr, "in_out"))
800                 in_out = RNA_enum_get(op->ptr, "in_out");
801         else
802                 return OPERATOR_CANCELLED;
803         
804         sock = (bNodeSocket*)BLI_findlink(in_out==SOCK_IN ? &ngroup->inputs : &ngroup->outputs, index);
805         if (sock) {
806                 nodeGroupRemoveSocket(ngroup, sock, in_out);
807                 node_tree_verify_groups(snode->nodetree);
808                 
809                 snode_notify(C, snode);
810         }
811         
812         return OPERATOR_FINISHED;
813 }
814
815 void NODE_OT_group_socket_remove(wmOperatorType *ot)
816 {
817         /* identifiers */
818         ot->name = "Remove Group Socket";
819         ot->description = "Removed node group socket";
820         ot->idname = "NODE_OT_group_socket_remove";
821         
822         /* api callbacks */
823         ot->exec = node_group_socket_remove_exec;
824         ot->poll = ED_operator_node_active;
825         
826         /* flags */
827         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
828         
829         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
830         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
831 }
832
833 /* ***************** Move Group Socket Up operator ************* */
834
835 static int node_group_socket_move_up_exec(bContext *C, wmOperator *op)
836 {
837         SpaceNode *snode = CTX_wm_space_node(C);
838         int index= -1;
839         int in_out= -1;
840         bNodeTree *ngroup= snode->edittree;
841         bNodeSocket *sock, *prev;
842         
843         ED_preview_kill_jobs(C);
844         
845         if (RNA_property_is_set(op->ptr, "index"))
846                 index = RNA_int_get(op->ptr, "index");
847         else
848                 return OPERATOR_CANCELLED;
849         
850         if (RNA_property_is_set(op->ptr, "in_out"))
851                 in_out = RNA_enum_get(op->ptr, "in_out");
852         else
853                 return OPERATOR_CANCELLED;
854         
855         /* swap */
856         if (in_out==SOCK_IN) {
857                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
858                 prev = sock->prev;
859                 /* can't move up the first socket */
860                 if (!prev)
861                         return OPERATOR_CANCELLED;
862                 BLI_remlink(&ngroup->inputs, sock);
863                 BLI_insertlinkbefore(&ngroup->inputs, prev, sock);
864         }
865         else if (in_out==SOCK_OUT) {
866                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
867                 prev = sock->prev;
868                 /* can't move up the first socket */
869                 if (!prev)
870                         return OPERATOR_CANCELLED;
871                 BLI_remlink(&ngroup->outputs, sock);
872                 BLI_insertlinkbefore(&ngroup->outputs, prev, sock);
873         }
874         node_tree_verify_groups(snode->nodetree);
875         
876         snode_notify(C, snode);
877         
878         return OPERATOR_FINISHED;
879 }
880
881 void NODE_OT_group_socket_move_up(wmOperatorType *ot)
882 {
883         /* identifiers */
884         ot->name = "Move Group Socket Up";
885         ot->description = "Move up node group socket";
886         ot->idname = "NODE_OT_group_socket_move_up";
887         
888         /* api callbacks */
889         ot->exec = node_group_socket_move_up_exec;
890         ot->poll = ED_operator_node_active;
891         
892         /* flags */
893         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
894         
895         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
896         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
897 }
898
899 /* ***************** Move Group Socket Up operator ************* */
900
901 static int node_group_socket_move_down_exec(bContext *C, wmOperator *op)
902 {
903         SpaceNode *snode = CTX_wm_space_node(C);
904         int index= -1;
905         int in_out= -1;
906         bNodeTree *ngroup= snode->edittree;
907         bNodeSocket *sock, *next;
908         
909         ED_preview_kill_jobs(C);
910         
911         if (RNA_property_is_set(op->ptr, "index"))
912                 index = RNA_int_get(op->ptr, "index");
913         else
914                 return OPERATOR_CANCELLED;
915         
916         if (RNA_property_is_set(op->ptr, "in_out"))
917                 in_out = RNA_enum_get(op->ptr, "in_out");
918         else
919                 return OPERATOR_CANCELLED;
920         
921         /* swap */
922         if (in_out==SOCK_IN) {
923                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
924                 next = sock->next;
925                 /* can't move down the last socket */
926                 if (!next)
927                         return OPERATOR_CANCELLED;
928                 BLI_remlink(&ngroup->inputs, sock);
929                 BLI_insertlinkafter(&ngroup->inputs, next, sock);
930         }
931         else if (in_out==SOCK_OUT) {
932                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
933                 next = sock->next;
934                 /* can't move down the last socket */
935                 if (!next)
936                         return OPERATOR_CANCELLED;
937                 BLI_remlink(&ngroup->outputs, sock);
938                 BLI_insertlinkafter(&ngroup->outputs, next, sock);
939         }
940         node_tree_verify_groups(snode->nodetree);
941         
942         snode_notify(C, snode);
943         
944         return OPERATOR_FINISHED;
945 }
946
947 void NODE_OT_group_socket_move_down(wmOperatorType *ot)
948 {
949         /* identifiers */
950         ot->name = "Move Group Socket Down";
951         ot->description = "Move down node group socket";
952         ot->idname = "NODE_OT_group_socket_move_down";
953         
954         /* api callbacks */
955         ot->exec = node_group_socket_move_down_exec;
956         ot->poll = ED_operator_node_active;
957         
958         /* flags */
959         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
960         
961         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
962         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
963 }
964
965 /* ******************** Ungroup operator ********************** */
966
967 static int node_group_ungroup_exec(bContext *C, wmOperator *op)
968 {
969         SpaceNode *snode = CTX_wm_space_node(C);
970         bNode *gnode;
971
972         ED_preview_kill_jobs(C);
973
974         /* are we inside of a group? */
975         gnode= node_tree_get_editgroup(snode->nodetree);
976         if(gnode)
977                 snode_make_group_editable(snode, NULL);
978         
979         gnode= nodeGetActive(snode->edittree);
980         if(gnode==NULL)
981                 return OPERATOR_CANCELLED;
982         
983         if(gnode->type!=NODE_GROUP) {
984                 BKE_report(op->reports, RPT_WARNING, "Not a group");
985                 return OPERATOR_CANCELLED;
986         }
987         else if(!nodeGroupUnGroup(snode->edittree, gnode)) {
988                 BKE_report(op->reports, RPT_WARNING, "Can't ungroup");
989                 return OPERATOR_CANCELLED;
990         }
991
992         snode_notify(C, snode);
993         snode_dag_update(C, snode);
994
995         return OPERATOR_FINISHED;
996 }
997
998 void NODE_OT_group_ungroup(wmOperatorType *ot)
999 {
1000         /* identifiers */
1001         ot->name = "Ungroup";
1002         ot->description = "Ungroup selected nodes";
1003         ot->idname = "NODE_OT_group_ungroup";
1004         
1005         /* api callbacks */
1006         ot->exec = node_group_ungroup_exec;
1007         ot->poll = ED_operator_node_active;
1008         
1009         /* flags */
1010         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1011 }
1012
1013 /* ************************** Node generic ************** */
1014
1015 /* allows to walk the list in order of visibility */
1016 bNode *next_node(bNodeTree *ntree)
1017 {
1018         static bNode *current=NULL, *last= NULL;
1019         
1020         if(ntree) {
1021                 /* set current to the first selected node */
1022                 for(current= ntree->nodes.last; current; current= current->prev)
1023                         if(current->flag & NODE_SELECT)
1024                                 break;
1025                 
1026                 /* set last to the first unselected node */
1027                 for(last= ntree->nodes.last; last; last= last->prev)
1028                         if((last->flag & NODE_SELECT)==0)
1029                                 break;
1030                 
1031                 if(current==NULL)
1032                         current= last;
1033                 
1034                 return NULL;
1035         }
1036         /* no nodes, or we are ready */
1037         if(current==NULL)
1038                 return NULL;
1039         
1040         /* now we walk the list backwards, but we always return current */
1041         if(current->flag & NODE_SELECT) {
1042                 bNode *node= current;
1043                 
1044                 /* find previous selected */
1045                 current= current->prev;
1046                 while(current && (current->flag & NODE_SELECT)==0)
1047                         current= current->prev;
1048                 
1049                 /* find first unselected */
1050                 if(current==NULL)
1051                         current= last;
1052                 
1053                 return node;
1054         }
1055         else {
1056                 bNode *node= current;
1057                 
1058                 /* find previous unselected */
1059                 current= current->prev;
1060                 while(current && (current->flag & NODE_SELECT))
1061                         current= current->prev;
1062                 
1063                 return node;
1064         }
1065         
1066         return NULL;
1067 }
1068
1069 /* is rct in visible part of node? */
1070 static bNode *visible_node(SpaceNode *snode, rctf *rct)
1071 {
1072         bNode *tnode;
1073         
1074         for(next_node(snode->edittree); (tnode=next_node(NULL));) {
1075                 if(BLI_isect_rctf(&tnode->totr, rct, NULL))
1076                         break;
1077         }
1078         return tnode;
1079 }
1080
1081 /* **************************** */
1082
1083 typedef struct NodeViewMove {
1084         int mvalo[2];
1085         int xmin, ymin, xmax, ymax;
1086 } NodeViewMove;
1087
1088 static int snode_bg_viewmove_modal(bContext *C, wmOperator *op, wmEvent *event)
1089 {
1090         SpaceNode *snode= CTX_wm_space_node(C);
1091         ARegion *ar= CTX_wm_region(C);
1092         NodeViewMove *nvm= op->customdata;
1093
1094         switch (event->type) {
1095                 case MOUSEMOVE:
1096                         
1097                         snode->xof -= (nvm->mvalo[0]-event->mval[0]);
1098                         snode->yof -= (nvm->mvalo[1]-event->mval[1]);
1099                         nvm->mvalo[0]= event->mval[0];
1100                         nvm->mvalo[1]= event->mval[1];
1101                         
1102                         /* prevent dragging image outside of the window and losing it! */
1103                         CLAMP(snode->xof, nvm->xmin, nvm->xmax);
1104                         CLAMP(snode->yof, nvm->ymin, nvm->ymax);
1105                         
1106                         ED_region_tag_redraw(ar);
1107                         
1108                         break;
1109                         
1110                 case LEFTMOUSE:
1111                 case MIDDLEMOUSE:
1112                 case RIGHTMOUSE:
1113                         
1114                         MEM_freeN(nvm);
1115                         op->customdata= NULL;
1116
1117                         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_NODE, NULL);
1118                         
1119                         return OPERATOR_FINISHED;
1120         }
1121         
1122         return OPERATOR_RUNNING_MODAL;
1123 }
1124
1125 static int snode_bg_viewmove_invoke(bContext *C, wmOperator *op, wmEvent *event)
1126 {
1127         ARegion *ar= CTX_wm_region(C);
1128         NodeViewMove *nvm;
1129         Image *ima;
1130         ImBuf *ibuf;
1131         int pad= 10;
1132         void *lock;
1133         
1134         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1135         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1136         
1137         if(ibuf == NULL) {
1138                 BKE_image_release_ibuf(ima, lock);
1139                 return OPERATOR_CANCELLED;
1140         }
1141
1142         nvm= MEM_callocN(sizeof(NodeViewMove), "NodeViewMove struct");
1143         op->customdata= nvm;
1144         nvm->mvalo[0]= event->mval[0];
1145         nvm->mvalo[1]= event->mval[1];
1146
1147         nvm->xmin = -(ar->winx/2) - ibuf->x/2 + pad;
1148         nvm->xmax = ar->winx/2 + ibuf->x/2 - pad;
1149         nvm->ymin = -(ar->winy/2) - ibuf->y/2 + pad;
1150         nvm->ymax = ar->winy/2 + ibuf->y/2 - pad;
1151
1152         BKE_image_release_ibuf(ima, lock);
1153         
1154         /* add modal handler */
1155         WM_event_add_modal_handler(C, op);
1156         
1157         return OPERATOR_RUNNING_MODAL;
1158 }
1159
1160 static int snode_bg_viewmove_cancel(bContext *UNUSED(C), wmOperator *op)
1161 {
1162         MEM_freeN(op->customdata);
1163         op->customdata= NULL;
1164
1165         return OPERATOR_CANCELLED;
1166 }
1167
1168 void NODE_OT_backimage_move(wmOperatorType *ot)
1169 {
1170         /* identifiers */
1171         ot->name= "Background Image Move";
1172         ot->description = "Move Node backdrop";
1173         ot->idname= "NODE_OT_backimage_move";
1174         
1175         /* api callbacks */
1176         ot->invoke= snode_bg_viewmove_invoke;
1177         ot->modal= snode_bg_viewmove_modal;
1178         ot->poll= composite_node_active;
1179         ot->cancel= snode_bg_viewmove_cancel;
1180         
1181         /* flags */
1182         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1183 }
1184
1185 static int backimage_zoom(bContext *C, wmOperator *op)
1186 {
1187         SpaceNode *snode= CTX_wm_space_node(C);
1188         ARegion *ar= CTX_wm_region(C);
1189         float fac= RNA_float_get(op->ptr, "factor");
1190
1191         snode->zoom *= fac;
1192         ED_region_tag_redraw(ar);
1193
1194         return OPERATOR_FINISHED;
1195 }
1196
1197
1198 void NODE_OT_backimage_zoom(wmOperatorType *ot)
1199 {
1200         
1201         /* identifiers */
1202         ot->name= "Background Image Zoom";
1203         ot->idname= "NODE_OT_backimage_zoom";
1204         
1205         /* api callbacks */
1206         ot->exec= backimage_zoom;
1207         ot->poll= composite_node_active;
1208         
1209         /* flags */
1210         ot->flag= OPTYPE_BLOCKING;
1211
1212         /* internal */
1213         RNA_def_float(ot->srna, "factor", 1.2f, 0.0f, 10.0f, "Factor", "", 0.0f, 10.0f);
1214 }
1215
1216 /******************** sample backdrop operator ********************/
1217
1218 typedef struct ImageSampleInfo {
1219         ARegionType *art;
1220         void *draw_handle;
1221         int x, y;
1222         int channels;
1223         int color_manage;
1224
1225         char col[4];
1226         float colf[4];
1227
1228         int draw;
1229 } ImageSampleInfo;
1230
1231 static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
1232 {
1233         ImageSampleInfo *info= arg_info;
1234
1235         draw_nodespace_color_info(ar, (CTX_data_scene(C)->r.color_mgt_flag & R_COLOR_MANAGEMENT), info->channels,
1236                                                           info->x, info->y, info->col, info->colf);
1237 }
1238
1239 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1240 {
1241         SpaceNode *snode= CTX_wm_space_node(C);
1242         ARegion *ar= CTX_wm_region(C);
1243         ImageSampleInfo *info= op->customdata;
1244         void *lock;
1245         Image *ima;
1246         ImBuf *ibuf;
1247         float fx, fy, bufx, bufy;
1248         
1249         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1250         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1251         if(!ibuf)
1252                 return;
1253         
1254         if(!ibuf->rect) {
1255                 if(info->color_manage)
1256                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1257                 else
1258                         ibuf->profile = IB_PROFILE_NONE;
1259                 IMB_rect_from_float(ibuf);
1260         }
1261
1262         /* map the mouse coords to the backdrop image space */
1263         bufx = ibuf->x * snode->zoom;
1264         bufy = ibuf->y * snode->zoom;
1265         fx = (bufx > 0.0f ? ((float)event->mval[0] - 0.5f*ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
1266         fy = (bufy > 0.0f ? ((float)event->mval[1] - 0.5f*ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
1267
1268         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1269                 float *fp;
1270                 char *cp;
1271                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1272
1273                 CLAMP(x, 0, ibuf->x-1);
1274                 CLAMP(y, 0, ibuf->y-1);
1275
1276                 info->x= x;
1277                 info->y= y;
1278                 info->draw= 1;
1279                 info->channels= ibuf->channels;
1280
1281                 if(ibuf->rect) {
1282                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1283
1284                         info->col[0]= cp[0];
1285                         info->col[1]= cp[1];
1286                         info->col[2]= cp[2];
1287                         info->col[3]= cp[3];
1288
1289                         info->colf[0]= (float)cp[0]/255.0f;
1290                         info->colf[1]= (float)cp[1]/255.0f;
1291                         info->colf[2]= (float)cp[2]/255.0f;
1292                         info->colf[3]= (float)cp[3]/255.0f;
1293                 }
1294                 if(ibuf->rect_float) {
1295                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1296
1297                         info->colf[0]= fp[0];
1298                         info->colf[1]= fp[1];
1299                         info->colf[2]= fp[2];
1300                         info->colf[3]= fp[3];
1301                 }
1302         }
1303         else
1304                 info->draw= 0;
1305
1306         BKE_image_release_ibuf(ima, lock);
1307         
1308         ED_area_tag_redraw(CTX_wm_area(C));
1309 }
1310
1311 static void sample_exit(bContext *C, wmOperator *op)
1312 {
1313         ImageSampleInfo *info= op->customdata;
1314
1315         ED_region_draw_cb_exit(info->art, info->draw_handle);
1316         ED_area_tag_redraw(CTX_wm_area(C));
1317         MEM_freeN(info);
1318 }
1319
1320 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1321 {
1322         SpaceNode *snode= CTX_wm_space_node(C);
1323         ARegion *ar= CTX_wm_region(C);
1324         ImageSampleInfo *info;
1325
1326         if(snode->treetype!=NTREE_COMPOSIT || !(snode->flag & SNODE_BACKDRAW))
1327                 return OPERATOR_CANCELLED;
1328         
1329         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1330         info->art= ar->type;
1331         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1332         op->customdata= info;
1333
1334         sample_apply(C, op, event);
1335
1336         WM_event_add_modal_handler(C, op);
1337
1338         return OPERATOR_RUNNING_MODAL;
1339 }
1340
1341 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1342 {
1343         switch(event->type) {
1344                 case LEFTMOUSE:
1345                 case RIGHTMOUSE: // XXX hardcoded
1346                         sample_exit(C, op);
1347                         return OPERATOR_CANCELLED;
1348                 case MOUSEMOVE:
1349                         sample_apply(C, op, event);
1350                         break;
1351         }
1352
1353         return OPERATOR_RUNNING_MODAL;
1354 }
1355
1356 static int sample_cancel(bContext *C, wmOperator *op)
1357 {
1358         sample_exit(C, op);
1359         return OPERATOR_CANCELLED;
1360 }
1361
1362 void NODE_OT_backimage_sample(wmOperatorType *ot)
1363 {
1364         /* identifiers */
1365         ot->name= "Backimage Sample";
1366         ot->idname= "NODE_OT_backimage_sample";
1367         
1368         /* api callbacks */
1369         ot->invoke= sample_invoke;
1370         ot->modal= sample_modal;
1371         ot->cancel= sample_cancel;
1372         ot->poll= ED_operator_node_active;
1373
1374         /* flags */
1375         ot->flag= OPTYPE_BLOCKING;
1376 }
1377
1378 /* ********************** size widget operator ******************** */
1379
1380 typedef struct NodeSizeWidget {
1381         float mxstart;
1382         float oldwidth;
1383 } NodeSizeWidget;
1384
1385 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1386 {
1387         SpaceNode *snode= CTX_wm_space_node(C);
1388         ARegion *ar= CTX_wm_region(C);
1389         bNode *node= editnode_get_active(snode->edittree);
1390         NodeSizeWidget *nsw= op->customdata;
1391         float mx, my;
1392         
1393         switch (event->type) {
1394                 case MOUSEMOVE:
1395                         
1396                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1397                                                                          &mx, &my);
1398                         
1399                         if (node) {
1400                                 if(node->flag & NODE_HIDDEN) {
1401                                         node->miniwidth= nsw->oldwidth + mx - nsw->mxstart;
1402                                         CLAMP(node->miniwidth, 0.0f, 100.0f);
1403                                 }
1404                                 else {
1405                                         node->width= nsw->oldwidth + mx - nsw->mxstart;
1406                                         CLAMP(node->width, UI_DPI_FAC*node->typeinfo->minwidth, UI_DPI_FAC*node->typeinfo->maxwidth);
1407                                 }
1408                         }
1409                                 
1410                         ED_region_tag_redraw(ar);
1411
1412                         break;
1413                         
1414                 case LEFTMOUSE:
1415                 case MIDDLEMOUSE:
1416                 case RIGHTMOUSE:
1417                         
1418                         MEM_freeN(nsw);
1419                         op->customdata= NULL;
1420                         
1421                         return OPERATOR_FINISHED;
1422         }
1423         
1424         return OPERATOR_RUNNING_MODAL;
1425 }
1426
1427 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1428 {
1429         SpaceNode *snode= CTX_wm_space_node(C);
1430         ARegion *ar= CTX_wm_region(C);
1431         bNode *node= editnode_get_active(snode->edittree);
1432         
1433         if(node) {
1434                 rctf totr;
1435                 
1436                 /* convert mouse coordinates to v2d space */
1437                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1438                                                                  &snode->mx, &snode->my);
1439                 
1440                 totr= node->totr;
1441                 
1442                 if(node->flag & NODE_HIDDEN) {
1443                         /* right part of node */
1444                         totr.xmin= node->totr.xmax-20.0f;
1445                 }
1446                 else {
1447                         /* bottom right corner */
1448                         totr.xmin= totr.xmax-10.0f;
1449                         totr.ymax= totr.ymin+10.0f;
1450                 }
1451                 
1452                 if(BLI_in_rctf(&totr, snode->mx, snode->my)) {
1453                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1454                         
1455                         op->customdata= nsw;
1456                         nsw->mxstart= snode->mx;
1457                         
1458                         /* store old */
1459                         if(node->flag & NODE_HIDDEN)
1460                                 nsw->oldwidth= node->miniwidth;
1461                         else
1462                                 nsw->oldwidth= node->width;
1463                         
1464                         /* add modal handler */
1465                         WM_event_add_modal_handler(C, op);
1466
1467                         return OPERATOR_RUNNING_MODAL;
1468                 }
1469         }
1470         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
1471 }
1472
1473 static int node_resize_cancel(bContext *UNUSED(C), wmOperator *op)
1474 {
1475         MEM_freeN(op->customdata);
1476         op->customdata= NULL;
1477
1478         return OPERATOR_CANCELLED;
1479 }
1480
1481 void NODE_OT_resize(wmOperatorType *ot)
1482 {
1483         /* identifiers */
1484         ot->name= "Resize Node";
1485         ot->idname= "NODE_OT_resize";
1486         
1487         /* api callbacks */
1488         ot->invoke= node_resize_invoke;
1489         ot->modal= node_resize_modal;
1490         ot->poll= ED_operator_node_active;
1491         ot->cancel= node_resize_cancel;
1492         
1493         /* flags */
1494         ot->flag= OPTYPE_BLOCKING;
1495 }
1496
1497 /* ********************** select ******************** */
1498
1499
1500 /* no undo here! */
1501 void node_deselectall(SpaceNode *snode)
1502 {
1503         bNode *node;
1504         
1505         for(node= snode->edittree->nodes.first; node; node= node->next)
1506                 node->flag &= ~SELECT;
1507 }
1508
1509 /* return 1 if we need redraw otherwise zero. */
1510 int node_select_same_type(SpaceNode *snode)
1511 {
1512         bNode *nac, *p;
1513         int redraw;
1514
1515         /* search for the active node. */
1516         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1517                 if (nac->flag & SELECT)
1518                         break;
1519         }
1520
1521         /* no active node, return. */
1522         if (!nac)
1523                 return(0);
1524
1525         redraw= 0;
1526         for (p= snode->edittree->nodes.first; p; p= p->next) {
1527                 if (p->type != nac->type && p->flag & SELECT) {
1528                         /* if it's selected but different type, unselect */
1529                         redraw= 1;
1530                         p->flag &= ~SELECT;
1531                 }
1532                 else if (p->type == nac->type && (!(p->flag & SELECT))) {
1533                         /* if it's the same type and is not selected, select! */
1534                         redraw= 1;
1535                         p->flag |= SELECT;
1536                 }
1537         }
1538         return(redraw);
1539 }
1540
1541 /* return 1 if we need redraw, otherwise zero.
1542  * dir can be 0 == next or 0 != prev.
1543  */
1544 int node_select_same_type_np(SpaceNode *snode, int dir)
1545 {
1546         bNode *nac, *p;
1547
1548         /* search the active one. */
1549         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1550                 if (nac->flag & SELECT)
1551                         break;
1552         }
1553
1554         /* no active node, return. */
1555         if (!nac)
1556                 return(0);
1557
1558         if (dir == 0)
1559                 p= nac->next;
1560         else
1561                 p= nac->prev;
1562
1563         while (p) {
1564                 /* Now search the next with the same type. */
1565                 if (p->type == nac->type)
1566                         break;
1567
1568                 if (dir == 0)
1569                         p= p->next;
1570                 else
1571                         p= p->prev;
1572         }
1573
1574         if (p) {
1575                 node_deselectall(snode);
1576                 p->flag |= SELECT;
1577                 return(1);
1578         }
1579         return(0);
1580 }
1581
1582 int node_has_hidden_sockets(bNode *node)
1583 {
1584         bNodeSocket *sock;
1585         
1586         for(sock= node->inputs.first; sock; sock= sock->next)
1587                 if(sock->flag & SOCK_HIDDEN)
1588                         return 1;
1589         for(sock= node->outputs.first; sock; sock= sock->next)
1590                 if(sock->flag & SOCK_HIDDEN)
1591                         return 1;
1592         return 0;
1593 }
1594
1595 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1596 {
1597         bNode *node;
1598
1599         /* context check */
1600         if(tonode==NULL || tonode->outputs.first==NULL)
1601                 return;
1602         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1603                 return;
1604         
1605         /* get viewer */
1606         for(node= snode->edittree->nodes.first; node; node= node->next)
1607                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1608                         if(node->flag & NODE_DO_OUTPUT)
1609                                 break;
1610         /* no viewer, we make one active */
1611         if(node==NULL) {
1612                 for(node= snode->edittree->nodes.first; node; node= node->next) {
1613                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
1614                                 node->flag |= NODE_DO_OUTPUT;
1615                                 break;
1616                         }
1617                 }
1618         }
1619                 
1620         if(node) {
1621                 bNodeLink *link;
1622                 bNodeSocket *sock= NULL;
1623
1624                 /* try to find an already connected socket to cycle to the next */
1625                 for(link= snode->edittree->links.first; link; link= link->next)
1626                         if(link->tonode==node && link->fromnode==tonode)
1627                                 if(link->tosock==node->inputs.first)
1628                                         break;
1629
1630                 if(link) {
1631                         /* unlink existing connection */
1632                         sock= link->fromsock;
1633                         nodeRemLink(snode->edittree, link);
1634
1635                         /* find a socket after the previously connected socket */
1636                         for(sock=sock->next; sock; sock= sock->next)
1637                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1638                                         break;
1639                 }
1640
1641                 /* find a socket starting from the first socket */
1642                 if(!sock) {
1643                         for(sock= tonode->outputs.first; sock; sock= sock->next)
1644                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1645                                         break;
1646                 }
1647                 
1648                 if(sock) {
1649                         /* get link to viewer */
1650                         for(link= snode->edittree->links.first; link; link= link->next)
1651                                 if(link->tonode==node && link->tosock==node->inputs.first)
1652                                         break;
1653                         
1654                         if(link==NULL) {
1655                                 nodeAddLink(snode->edittree, tonode, sock, node, node->inputs.first);
1656                         }
1657                         else {
1658                                 link->fromnode= tonode;
1659                                 link->fromsock= sock;
1660                         }
1661                         ntreeSolveOrder(snode->edittree);
1662                         snode_tag_changed(snode, node);
1663                 }
1664         }
1665 }
1666
1667
1668 static int node_active_link_viewer(bContext *C, wmOperator *UNUSED(op))
1669 {
1670         SpaceNode *snode= CTX_wm_space_node(C);
1671         bNode *node;
1672         
1673         node= editnode_get_active(snode->edittree);
1674         
1675         if(!node)
1676                 return OPERATOR_CANCELLED;
1677
1678         ED_preview_kill_jobs(C);
1679
1680         node_link_viewer(snode, node);
1681         snode_notify(C, snode);
1682
1683         return OPERATOR_FINISHED;
1684 }
1685
1686
1687
1688 void NODE_OT_link_viewer(wmOperatorType *ot)
1689 {
1690         /* identifiers */
1691         ot->name= "Link to Viewer Node";
1692         ot->description = "Link to Viewer Node";
1693         ot->idname= "NODE_OT_link_viewer";
1694         
1695         /* api callbacks */
1696         ot->exec= node_active_link_viewer;
1697         ot->poll= ED_operator_node_active;
1698         
1699         /* flags */
1700         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1701 }
1702
1703
1704
1705 /* return 0, nothing done */
1706 static int UNUSED_FUNCTION(node_mouse_groupheader)(SpaceNode *snode)
1707 {
1708         bNode *gnode;
1709         float mx=0, my=0;
1710 // XXX  int mval[2];
1711         
1712         gnode= node_tree_get_editgroup(snode->nodetree);
1713         if(gnode==NULL) return 0;
1714         
1715 // XXX  getmouseco_areawin(mval);
1716 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1717         
1718         /* click in header or outside? */
1719         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1720                 rctf rect= gnode->totr;
1721                 
1722                 rect.ymax += NODE_DY;
1723                 if(BLI_in_rctf(&rect, mx, my)==0)
1724                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1725 //              else
1726 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1727                 
1728                 return 1;
1729         }
1730         return 0;
1731 }
1732
1733 /* checks snode->mouse position, and returns found node/socket */
1734 /* type is SOCK_IN and/or SOCK_OUT */
1735 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1736 {
1737         bNode *node;
1738         bNodeSocket *sock;
1739         rctf rect;
1740         
1741         /* check if we click in a socket */
1742         for(node= snode->edittree->nodes.first; node; node= node->next) {
1743                 
1744                 rect.xmin = snode->mx - (NODE_SOCKSIZE+4);
1745                 rect.ymin = snode->my - (NODE_SOCKSIZE+4);
1746                 rect.xmax = snode->mx + (NODE_SOCKSIZE+4);
1747                 rect.ymax = snode->my + (NODE_SOCKSIZE+4);
1748                 
1749                 if (!(node->flag & NODE_HIDDEN)) {
1750                         /* extra padding inside and out - allow dragging on the text areas too */
1751                         if (in_out == SOCK_IN) {
1752                                 rect.xmax += NODE_SOCKSIZE;
1753                                 rect.xmin -= NODE_SOCKSIZE*4;
1754                         } else if (in_out == SOCK_OUT) {
1755                                 rect.xmax += NODE_SOCKSIZE*4;
1756                                 rect.xmin -= NODE_SOCKSIZE;
1757                         }
1758                 }
1759                 
1760                 if(in_out & SOCK_IN) {
1761                         for(sock= node->inputs.first; sock; sock= sock->next) {
1762                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1763                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1764                                                 if(node == visible_node(snode, &rect)) {
1765                                                         *nodep= node;
1766                                                         *sockp= sock;
1767                                                         return 1;
1768                                                 }
1769                                         }
1770                                 }
1771                         }
1772                 }
1773                 if(in_out & SOCK_OUT) {
1774                         for(sock= node->outputs.first; sock; sock= sock->next) {
1775                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1776                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1777                                                 if(node == visible_node(snode, &rect)) {
1778                                                         *nodep= node;
1779                                                         *sockp= sock;
1780                                                         return 1;
1781                                                 }
1782                                         }
1783                                 }
1784                         }
1785                 }
1786         }
1787         
1788         /* check group sockets
1789          * NB: using ngroup->outputs as input sockets and vice versa here!
1790          */
1791         if(in_out & SOCK_IN) {
1792                 for(sock= snode->edittree->outputs.first; sock; sock= sock->next) {
1793                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1794                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1795                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1796                                         *sockp= sock;
1797                                         return 1;
1798                                 }
1799                         }
1800                 }
1801         }
1802         if(in_out & SOCK_OUT) {
1803                 for(sock= snode->edittree->inputs.first; sock; sock= sock->next) {
1804                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1805                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1806                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1807                                         *sockp= sock;
1808                                         return 1;
1809                                 }
1810                         }
1811                 }
1812         }
1813         
1814         return 0;
1815 }
1816
1817 static int node_socket_hilights(SpaceNode *snode, int in_out)
1818 {
1819         bNode *node;
1820         bNodeSocket *sock, *tsock, *socksel= NULL;
1821         short redraw= 0;
1822         
1823         if(snode->edittree==NULL) return 0;
1824         
1825         /* deselect sockets */
1826         for(node= snode->edittree->nodes.first; node; node= node->next) {
1827                 for(sock= node->inputs.first; sock; sock= sock->next) {
1828                         if(sock->flag & SELECT) {
1829                                 sock->flag &= ~SELECT;
1830                                 redraw++;
1831                                 socksel= sock;
1832                         }
1833                 }
1834                 for(sock= node->outputs.first; sock; sock= sock->next) {
1835                         if(sock->flag & SELECT) {
1836                                 sock->flag &= ~SELECT;
1837                                 redraw++;
1838                                 socksel= sock;
1839                         }
1840                 }
1841         }
1842         
1843         // XXX mousepos should be set here!
1844         
1845         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
1846                 tsock->flag |= SELECT;
1847                 if(redraw==1 && tsock==socksel) redraw= 0;
1848                 else redraw= 1;
1849         }
1850         
1851         return redraw;
1852 }
1853
1854 static int outside_group_rect(SpaceNode *snode)
1855 {
1856         bNode *gnode= node_tree_get_editgroup(snode->nodetree);
1857         if (gnode) {
1858                 return (snode->mx < gnode->totr.xmin || snode->mx >= gnode->totr.xmax
1859                                 || snode->my < gnode->totr.ymin || snode->my >= gnode->totr.ymax);
1860         }
1861         return 0;
1862 }
1863
1864 /* ****************** Add *********************** */
1865
1866
1867 typedef struct bNodeListItem {
1868         struct bNodeListItem *next, *prev;
1869         struct bNode *node;     
1870 } bNodeListItem;
1871
1872 static int sort_nodes_locx(void *a, void *b)
1873 {
1874         bNodeListItem *nli1 = (bNodeListItem *)a;
1875         bNodeListItem *nli2 = (bNodeListItem *)b;
1876         bNode *node1 = nli1->node;
1877         bNode *node2 = nli2->node;
1878         
1879         if (node1->locx > node2->locx)
1880                 return 1;
1881         else 
1882                 return 0;
1883 }
1884
1885 static int socket_is_available(bNodeTree *ntree, bNodeSocket *sock, int allow_used)
1886 {
1887         if (sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))
1888                 return 0;
1889         
1890         if (!allow_used) {
1891                 if (nodeCountSocketLinks(ntree, sock) > 0)
1892                         return 0;
1893         }
1894         return 1;
1895 }
1896
1897 static bNodeSocket *best_socket_output(bNodeTree *ntree, bNode *node, bNodeSocket *sock_target, int allow_multiple)
1898 {
1899         bNodeSocket *sock;
1900         
1901         /* first try to find a socket with a matching name */
1902         for (sock=node->outputs.first; sock; sock=sock->next) {
1903
1904                 if (!socket_is_available(ntree, sock, allow_multiple))
1905                         continue;
1906
1907                 /* check for same types */
1908                 if (sock->type == sock_target->type) {
1909                         if (strcmp(sock->name, sock_target->name)==0)
1910                                 return sock;
1911                 }
1912         }
1913         
1914         /* otherwise settle for the first available socket of the right type */
1915         for (sock=node->outputs.first; sock; sock=sock->next) {
1916
1917                 if (!socket_is_available(ntree, sock, allow_multiple))
1918                         continue;
1919                 
1920                 /* check for same types */
1921                 if (sock->type == sock_target->type) {
1922                         return sock;
1923                 }
1924         }
1925         
1926         return NULL;
1927 }
1928
1929 /* this is a bit complicated, but designed to prioritise finding 
1930  * sockets of higher types, such as image, first */
1931 static bNodeSocket *best_socket_input(bNodeTree *ntree, bNode *node, int num, int replace)
1932 {
1933         bNodeSocket *sock;
1934         int socktype, maxtype=0;
1935         int a = 0;
1936         
1937         for (sock=node->inputs.first; sock; sock=sock->next) {
1938                 maxtype = MAX2(sock->type, maxtype);
1939         }
1940         
1941         /* find sockets of higher 'types' first (i.e. image) */
1942         for (socktype=maxtype; socktype >= 0; socktype--) {
1943                 for (sock=node->inputs.first; sock; sock=sock->next) {
1944                         
1945                         if (!socket_is_available(ntree, sock, replace)) {
1946                                 a++;
1947                                 continue;
1948                         }
1949                                 
1950                         if (sock->type == socktype) {
1951                                 /* increment to make sure we don't keep finding 
1952                                  * the same socket on every attempt running this function */
1953                                 a++;
1954                                 if (a > num)
1955                                         return sock;
1956                         }
1957                 }
1958         }
1959         
1960         return NULL;
1961 }
1962
1963 void snode_autoconnect(SpaceNode *snode, int allow_multiple, int replace)
1964 {
1965         ListBase *nodelist = MEM_callocN(sizeof(ListBase), "items_list");
1966         bNodeListItem *nli;
1967         bNode *node;
1968         int i, numlinks=0;
1969         
1970         for(node= snode->edittree->nodes.first; node; node= node->next) {
1971                 if(node->flag & NODE_SELECT) {
1972                         nli = MEM_mallocN(sizeof(bNodeListItem), "temporary node list item");
1973                         nli->node = node;
1974                         BLI_addtail(nodelist, nli);
1975                 }
1976         }
1977         
1978         /* sort nodes left to right */
1979         BLI_sortlist(nodelist, sort_nodes_locx);
1980         
1981         for (nli=nodelist->first; nli; nli=nli->next) {
1982                 bNode *node_fr, *node_to;
1983                 bNodeSocket *sock_fr, *sock_to;
1984                 
1985                 if (nli->next == NULL) break;
1986                 
1987                 node_fr = nli->node;
1988                 node_to = nli->next->node;
1989                 
1990                 /* check over input sockets first */
1991                 for (i=0; i<BLI_countlist(&node_to->inputs); i++) {
1992                         
1993                         /* find the best guess input socket */
1994                         sock_to = best_socket_input(snode->edittree, node_to, i, replace);
1995                         if (!sock_to) continue;
1996                         
1997                         /* check for an appropriate output socket to connect from */
1998                         sock_fr = best_socket_output(snode->edittree, node_fr, sock_to, allow_multiple);
1999                         if (!sock_fr) continue;
2000                         
2001                         /* then we can connect */
2002                         if (replace)
2003                                 nodeRemSocketLinks(snode->edittree, sock_to);
2004                         nodeAddLink(snode->edittree, node_fr, sock_fr, node_to, sock_to);
2005                         snode_tag_changed(snode, node_to);
2006                         ++numlinks;
2007                         break;
2008                 }
2009         }
2010         
2011         if (numlinks > 0) {
2012                 node_tree_verify_groups(snode->nodetree);
2013                 ntreeSolveOrder(snode->edittree);
2014         }
2015         
2016         BLI_freelistN(nodelist);
2017         MEM_freeN(nodelist);
2018 }
2019
2020 /* can be called from menus too, but they should do own undopush and redraws */
2021 bNode *node_add_node(SpaceNode *snode, Main *bmain, Scene *scene, int type, float locx, float locy)
2022 {
2023         bNode *node= NULL, *gnode;
2024         
2025         node_deselectall(snode);
2026         
2027         if(type>=NODE_DYNAMIC_MENU) {
2028                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
2029         }
2030         else if(type>=NODE_GROUP_MENU) {
2031                 if(snode->edittree!=snode->nodetree) {
2032                         // XXX error("Can not add a Group in a Group");
2033                         return NULL;
2034                 }
2035                 else {
2036                         bNodeTree *ngroup= BLI_findlink(&bmain->nodetree, type-NODE_GROUP_MENU);
2037                         if(ngroup)
2038                                 node= nodeAddNodeType(snode->edittree, NODE_GROUP, ngroup, NULL);
2039                 }
2040         }
2041         else
2042                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
2043         
2044         /* generics */
2045         if(node) {
2046                 node->locx= locx;
2047                 node->locy= locy + 60.0f;               // arbitrary.. so its visible, (0,0) is top of node
2048                 node->flag |= SELECT;
2049                 
2050                 gnode= node_tree_get_editgroup(snode->nodetree);
2051                 if(gnode) {
2052                         node->locx -= gnode->locx;
2053                         node->locy -= gnode->locy;
2054                 }
2055
2056                 node_tree_verify_groups(snode->nodetree);
2057                 ED_node_set_active(bmain, snode->edittree, node);
2058                 
2059                 if(snode->nodetree->type==NTREE_COMPOSIT) {
2060                         if(ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE))
2061                                 node->id = &scene->id;
2062                         
2063                         ntreeCompositForceHidden(snode->edittree, scene);
2064                 }
2065                         
2066                 if(node->id)
2067                         id_us_plus(node->id);
2068                         
2069                 snode_tag_changed(snode, node);
2070         }
2071         
2072         if(snode->nodetree->type==NTREE_TEXTURE) {
2073                 ntreeTexCheckCyclics(snode->edittree);
2074         }
2075         
2076         return node;
2077 }
2078
2079 /* ****************** Duplicate *********************** */
2080
2081 static int node_duplicate_exec(bContext *C, wmOperator *op)
2082 {
2083         SpaceNode *snode= CTX_wm_space_node(C);
2084         bNodeTree *ntree= snode->edittree;
2085         bNode *node, *newnode, *lastnode;
2086         bNodeLink *link, *newlink, *lastlink;
2087         int keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
2088         
2089         ED_preview_kill_jobs(C);
2090         
2091         lastnode = ntree->nodes.last;
2092         for(node= ntree->nodes.first; node; node= node->next) {
2093                 if(node->flag & SELECT) {
2094                         newnode = nodeCopyNode(ntree, node);
2095                         
2096                         if(newnode->id) {
2097                                 /* simple id user adjustment, node internal functions dont touch this
2098                                  * but operators and readfile.c do. */
2099                                 id_us_plus(newnode->id);
2100                                 /* to ensure redraws or rerenders happen */
2101                                 ED_node_changed_update(snode->id, newnode);
2102                         }
2103                 }
2104                 
2105                 /* make sure we don't copy new nodes again! */
2106                 if (node==lastnode)
2107                         break;
2108         }
2109         
2110         /* copy links between selected nodes
2111          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2112          */
2113         lastlink = ntree->links.last;
2114         for (link=ntree->links.first; link; link=link->next) {
2115                 /* This creates new links between copied nodes.
2116                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
2117                  */
2118                 if (link->tonode && (link->tonode->flag & NODE_SELECT)
2119                         && (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT)))) {
2120                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2121                         newlink->flag = link->flag;
2122                         newlink->tonode = link->tonode->new_node;
2123                         newlink->tosock = link->tosock->new_sock;
2124                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
2125                                 newlink->fromnode = link->fromnode->new_node;
2126                                 newlink->fromsock = link->fromsock->new_sock;
2127                         }
2128                         else {
2129                                 /* input node not copied, this keeps the original input linked */
2130                                 newlink->fromnode = link->fromnode;
2131                                 newlink->fromsock = link->fromsock;
2132                         }
2133                         
2134                         BLI_addtail(&ntree->links, newlink);
2135                 }
2136                 
2137                 /* make sure we don't copy new links again! */
2138                 if (link==lastlink)
2139                         break;
2140         }
2141         
2142         /* deselect old nodes, select the copies instead */
2143         for(node= ntree->nodes.first; node; node= node->next) {
2144                 if(node->flag & SELECT) {
2145                         /* has been set during copy above */
2146                         newnode = node->new_node;
2147                         
2148                         node->flag &= ~(NODE_SELECT|NODE_ACTIVE);
2149                         newnode->flag |= NODE_SELECT;
2150                 }
2151                 
2152                 /* make sure we don't copy new nodes again! */
2153                 if (node==lastnode)
2154                         break;
2155         }
2156         
2157         ntreeSolveOrder(ntree);
2158         
2159         node_tree_verify_groups(snode->nodetree);
2160         snode_notify(C, snode);
2161         snode_dag_update(C, snode);
2162
2163         return OPERATOR_FINISHED;
2164 }
2165
2166 void NODE_OT_duplicate(wmOperatorType *ot)
2167 {
2168         /* identifiers */
2169         ot->name= "Duplicate Nodes";
2170         ot->description = "Duplicate the nodes";
2171         ot->idname= "NODE_OT_duplicate";
2172         
2173         /* api callbacks */
2174         ot->exec= node_duplicate_exec;
2175         ot->poll= ED_operator_node_active;
2176         
2177         /* flags */
2178         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2179         
2180         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
2181 }
2182
2183 /* *************************** add link op ******************** */
2184
2185 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
2186 {
2187         bNodeLink *tlink;
2188         bNodeSocket *sock;
2189         
2190         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
2191                 
2192                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
2193                         if(link!=tlink && tlink->tosock==link->tosock)
2194                                 break;
2195                 }
2196                 if(tlink) {
2197                         /* try to move the existing link to the next available socket */
2198                         if (tlink->tonode) {
2199                                 /* is there a free input socket with the target type? */
2200                                 for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
2201                                         if(sock->type==tlink->tosock->type)
2202                                                 if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
2203                                                         break;
2204                                 }
2205                                 if(sock) {
2206                                         tlink->tosock= sock;
2207                                         sock->flag &= ~SOCK_HIDDEN;
2208                                 }
2209                                 else {
2210                                         nodeRemLink(snode->edittree, tlink);
2211                                 }
2212                         }
2213                         else
2214                                 nodeRemLink(snode->edittree, tlink);
2215                 }
2216         }
2217 }
2218
2219 /* loop that adds a nodelink, called by function below  */
2220 /* in_out = starting socket */
2221 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
2222 {
2223         SpaceNode *snode= CTX_wm_space_node(C);
2224         ARegion *ar= CTX_wm_region(C);
2225         bNodeLinkDrag *nldrag= op->customdata;
2226         bNode *tnode, *node;
2227         bNodeSocket *tsock= NULL, *sock;
2228         bNodeLink *link;
2229         int in_out;
2230
2231         in_out= nldrag->in_out;
2232         node= nldrag->node;
2233         sock= nldrag->sock;
2234         link= nldrag->link;
2235         
2236         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2237                                                          &snode->mx, &snode->my);
2238
2239         switch (event->type) {
2240                 case MOUSEMOVE:
2241                         
2242                         if(in_out==SOCK_OUT) {
2243                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
2244                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2245                                                 if( link->tosock!= tsock && (!tnode || (tnode!=node && link->tonode!=tnode)) ) {
2246                                                         link->tonode= tnode;
2247                                                         link->tosock= tsock;
2248                                                         if (link->prev==NULL && link->next==NULL)
2249                                                                 BLI_addtail(&snode->edittree->links, link);
2250                                                         ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
2251                                                 }
2252                                         }
2253                                 }
2254                                 else {
2255                                         BLI_remlink(&snode->edittree->links, link);
2256                                         link->prev = link->next = NULL;
2257                                         link->tonode= NULL;
2258                                         link->tosock= NULL;
2259                                 }
2260                         }
2261                         else {
2262                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
2263                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2264                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
2265                                                         if( link->fromsock!= tsock && (!tnode || (tnode!=node && link->fromnode!=tnode)) ) {
2266                                                                 link->fromnode= tnode;
2267                                                                 link->fromsock= tsock;
2268                                                                 if (link->prev==NULL && link->next==NULL)
2269                                                                         BLI_addtail(&snode->edittree->links, link);
2270                                                                 ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
2271                                                         }
2272                                                 }
2273                                         }
2274                                 }
2275                                 else {
2276                                         BLI_remlink(&snode->edittree->links, link);
2277                                         link->prev = link->next = NULL;
2278                                         link->fromnode= NULL;
2279                                         link->fromsock= NULL;
2280                                 }
2281                         }
2282                         /* hilight target sockets only */
2283                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
2284                         ED_region_tag_redraw(ar);
2285                         break;
2286                         
2287                 case LEFTMOUSE:
2288                 case RIGHTMOUSE:
2289                 case MIDDLEMOUSE:
2290                         if(link->tosock && link->fromsock) {
2291                                 /* send changed events for original tonode and new */
2292                                 snode_tag_changed(snode, link->tonode);
2293                                 
2294                                 /* we might need to remove a link */
2295                                 if(in_out==SOCK_OUT)
2296                                         node_remove_extra_links(snode, link->tosock, link);
2297                                 
2298                                 /* when linking to group outputs, update the socket type */
2299                                 /* XXX this should all be part of a generic update system */
2300                                 if (!link->tonode) {
2301                                         link->tosock->type = link->fromsock->type;
2302                                 }
2303                         }
2304                         else if (outside_group_rect(snode) && (link->tonode || link->fromnode)) {
2305                                 /* automatically add new group socket */
2306                                 if (link->tonode && link->tosock) {
2307                                         link->fromsock = nodeGroupExposeSocket(snode->edittree, link->tosock, SOCK_IN);
2308                                         link->fromnode = NULL;
2309                                         if (link->prev==NULL && link->next==NULL)
2310                                                 BLI_addtail(&snode->edittree->links, link);
2311                                 }
2312                                 else if (link->fromnode && link->fromsock) {
2313                                         link->tosock = nodeGroupExposeSocket(snode->edittree, link->fromsock, SOCK_OUT);
2314                                         link->tonode = NULL;
2315                                         if (link->prev==NULL && link->next==NULL)
2316                                                 BLI_addtail(&snode->edittree->links, link);
2317                                 }
2318                         }
2319                         else
2320                                 nodeRemLink(snode->edittree, link);
2321                         
2322                         ntreeSolveOrder(snode->edittree);
2323                         node_tree_verify_groups(snode->nodetree);
2324                         snode_notify(C, snode);
2325                         snode_dag_update(C, snode);
2326                         
2327                         BLI_remlink(&snode->linkdrag, nldrag);
2328                         MEM_freeN(nldrag);
2329                         
2330                         return OPERATOR_FINISHED;
2331         }
2332         
2333         return OPERATOR_RUNNING_MODAL;
2334 }
2335
2336 /* return 1 when socket clicked */
2337 static int node_link_init(SpaceNode *snode, bNodeLinkDrag *nldrag)
2338 {
2339         bNodeLink *link;
2340
2341         /* output indicated? */
2342         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
2343                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2344                         return SOCK_OUT;
2345                 else {
2346                         /* find if we break a link */
2347                         for(link= snode->edittree->links.first; link; link= link->next) {
2348                                 if(link->fromsock==nldrag->sock)
2349                                         break;
2350                         }
2351                         if(link) {
2352                                 nldrag->node= link->tonode;
2353                                 nldrag->sock= link->tosock;
2354                                 nodeRemLink(snode->edittree, link);
2355                                 return SOCK_IN;
2356                         }
2357                 }
2358         }
2359         /* or an input? */
2360         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
2361                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2362                         return SOCK_IN;
2363                 else {
2364                         /* find if we break a link */
2365                         for(link= snode->edittree->links.first; link; link= link->next) {
2366                                 if(link->tosock==nldrag->sock)
2367                                         break;
2368                         }
2369                         if(link) {
2370                                 /* send changed event to original tonode */
2371                                 if(link->tonode) 
2372                                         snode_tag_changed(snode, link->tonode);
2373                                 
2374                                 nldrag->node= link->fromnode;
2375                                 nldrag->sock= link->fromsock;
2376                                 nodeRemLink(snode->edittree, link);
2377                                 return SOCK_OUT;
2378                         }
2379                 }
2380         }
2381         
2382         return 0;
2383 }
2384
2385 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2386 {
2387         SpaceNode *snode= CTX_wm_space_node(C);
2388         ARegion *ar= CTX_wm_region(C);
2389         bNodeLinkDrag *nldrag= MEM_callocN(sizeof(bNodeLinkDrag), "drag link op customdata");
2390         
2391         
2392         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2393                                                          &snode->mx, &snode->my);
2394
2395         ED_preview_kill_jobs(C);
2396
2397         nldrag->in_out= node_link_init(snode, nldrag);
2398                 
2399         if(nldrag->in_out) {
2400                 op->customdata= nldrag;
2401                 
2402                 /* we make a temporal link */
2403                 if(nldrag->in_out==SOCK_OUT) {
2404                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2405                         nldrag->link->fromnode= nldrag->node;
2406                         nldrag->link->fromsock= nldrag->sock;
2407                         nldrag->link->tonode= NULL;
2408                         nldrag->link->tosock= NULL;
2409                 }
2410                 else {
2411                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2412                         nldrag->link->fromnode= NULL;
2413                         nldrag->link->fromsock= NULL;
2414                         nldrag->link->tonode= nldrag->node;
2415                         nldrag->link->tosock= nldrag->sock;
2416                 }
2417                 BLI_addtail(&snode->linkdrag, nldrag);
2418                 
2419                 /* add modal handler */
2420                 WM_event_add_modal_handler(C, op);
2421                 
2422                 return OPERATOR_RUNNING_MODAL;
2423         }
2424         else {
2425                 MEM_freeN(nldrag);
2426                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2427         }
2428 }
2429
2430 static int node_link_cancel(bContext *C, wmOperator *op)
2431 {
2432         SpaceNode *snode= CTX_wm_space_node(C);
2433         bNodeLinkDrag *nldrag= op->customdata;
2434
2435         nodeRemLink(snode->edittree, nldrag->link);
2436         BLI_remlink(&snode->linkdrag, nldrag);
2437         MEM_freeN(nldrag);
2438
2439         return OPERATOR_CANCELLED;
2440 }
2441
2442 void NODE_OT_link(wmOperatorType *ot)
2443 {
2444         /* identifiers */
2445         ot->name= "Link Nodes";
2446         ot->idname= "NODE_OT_link";
2447         
2448         /* api callbacks */
2449         ot->invoke= node_link_invoke;
2450         ot->modal= node_link_modal;
2451 //      ot->exec= node_link_exec;
2452         ot->poll= ED_operator_node_active;
2453         ot->cancel= node_link_cancel;
2454         
2455         /* flags */
2456         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2457 }
2458
2459 /* ********************** Make Link operator ***************** */
2460
2461 /* makes a link between selected output and input sockets */
2462 static int node_make_link_exec(bContext *C, wmOperator *op)
2463 {
2464         SpaceNode *snode= CTX_wm_space_node(C);
2465         int replace = RNA_boolean_get(op->ptr, "replace");
2466
2467         ED_preview_kill_jobs(C);
2468
2469         snode_autoconnect(snode, 1, replace);
2470
2471         node_tree_verify_groups(snode->nodetree);
2472         snode_notify(C, snode);
2473         snode_dag_update(C, snode);
2474         
2475         return OPERATOR_FINISHED;
2476 }
2477
2478 void NODE_OT_link_make(wmOperatorType *ot)
2479 {
2480         /* identifiers */
2481         ot->name= "Make Links";
2482         ot->description= "Makes a link between selected output in input sockets";
2483         ot->idname= "NODE_OT_link_make";
2484         
2485         /* callbacks */
2486         ot->exec= node_make_link_exec;
2487         ot->poll= ED_operator_node_active; // XXX we need a special poll which checks that there are selected input/output sockets
2488         
2489         /* flags */
2490         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2491         
2492         RNA_def_boolean(ot->srna, "replace", 0, "Replace", "Replace socket connections with the new links");
2493 }
2494
2495 /* ********************** Cut Link operator ***************** */
2496
2497 #define LINK_RESOL 12
2498 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2499 {
2500         float coord_array[LINK_RESOL+1][2];
2501         int i, b;
2502         
2503         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2504
2505                 for(i=0; i<tot-1; i++)
2506                         for(b=0; b<LINK_RESOL; b++)
2507                                 if(isect_line_line_v2(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2508                                         return 1;
2509         }
2510         return 0;
2511 }
2512
2513 static int cut_links_exec(bContext *C, wmOperator *op)
2514 {
2515         SpaceNode *snode= CTX_wm_space_node(C);
2516         ARegion *ar= CTX_wm_region(C);
2517         float mcoords[256][2];
2518         int i= 0;
2519         
2520         RNA_BEGIN(op->ptr, itemptr, "path") {
2521                 float loc[2];
2522                 
2523                 RNA_float_get_array(&itemptr, "loc", loc);
2524                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2525                                                                  &mcoords[i][0], &mcoords[i][1]);
2526                 i++;
2527                 if(i>= 256) break;
2528         }
2529         RNA_END;
2530         
2531         if(i>1) {
2532                 bNodeLink *link, *next;
2533
2534                 ED_preview_kill_jobs(C);
2535                 
2536                 for(link= snode->edittree->links.first; link; link= next) {
2537                         next= link->next;
2538                         
2539                         if(cut_links_intersect(link, mcoords, i)) {
2540                                 snode_tag_changed(snode, link->tonode);
2541                                 nodeRemLink(snode->edittree, link);
2542                         }
2543                 }
2544                 
2545                 ntreeSolveOrder(snode->edittree);
2546                 node_tree_verify_groups(snode->nodetree);
2547                 snode_notify(C, snode);
2548                 snode_dag_update(C, snode);
2549                 
2550                 return OPERATOR_FINISHED;
2551         }
2552         
2553         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2554 }
2555
2556 void NODE_OT_links_cut(wmOperatorType *ot)
2557 {
2558         PropertyRNA *prop;
2559         
2560         ot->name= "Cut links";
2561         ot->idname= "NODE_OT_links_cut";
2562         
2563         ot->invoke= WM_gesture_lines_invoke;
2564         ot->modal= WM_gesture_lines_modal;
2565         ot->exec= cut_links_exec;
2566         ot->cancel= WM_gesture_lines_cancel;
2567         
2568         ot->poll= ED_operator_node_active;
2569         
2570         /* flags */
2571         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2572         
2573         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2574         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2575         /* internal */
2576         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2577 }
2578
2579 /* *********************  automatic node insert on dragging ******************* */
2580
2581 /* assumes sockets in list */
2582 static bNodeSocket *socket_best_match(ListBase *sockets, int type)
2583 {
2584         bNodeSocket *sock;
2585         
2586         /* first, match type */
2587         for(sock= sockets->first; sock; sock= sock->next)
2588                 if(!(sock->flag & SOCK_HIDDEN))
2589                         if(type == sock->type)
2590                                 return sock;
2591         
2592         /* then just use first unhidden socket */
2593         for(sock= sockets->first; sock; sock= sock->next)
2594                 if(!(sock->flag & SOCK_HIDDEN))
2595                         return sock;
2596
2597         /* OK, let's unhide proper one */
2598         for(sock= sockets->first; sock; sock= sock->next) {
2599                 if(type == sock->type) {
2600                         sock->flag &= ~SOCK_HIDDEN;
2601                         return sock;
2602                 }
2603         }
2604         
2605         /* just the first */
2606         sock= sockets->first;
2607         sock->flag &= ~SOCK_HIDDEN;
2608         
2609         return sockets->first;
2610 }
2611
2612 /* prevent duplicate testing code below */
2613 static SpaceNode *ed_node_link_conditions(ScrArea *sa, bNode **select)
2614 {
2615         SpaceNode *snode= sa?sa->spacedata.first:NULL;
2616         bNode *node;
2617         bNodeLink *link;
2618         
2619         /* no unlucky accidents */
2620         if(sa==NULL || sa->spacetype!=SPACE_NODE) return NULL;
2621         
2622         *select= NULL;
2623         
2624         for(node= snode->edittree->nodes.first; node; node= node->next) {
2625                 if(node->flag & SELECT) {
2626                         if(*select)
2627                                 break;
2628                         else
2629                                 *select= node;
2630                 }
2631         }
2632         /* only one selected */
2633         if(node || *select==NULL) return NULL;
2634         
2635         /* correct node */
2636         if((*select)->inputs.first==NULL || (*select)->outputs.first==NULL) return NULL;
2637         
2638         /* test node for links */
2639         for(link= snode->edittree->links.first; link; link=link->next) {
2640                 if(link->tonode == *select || link->fromnode == *select)
2641                         return NULL;
2642         }
2643         
2644         return snode;
2645 }
2646
2647 /* assumes link with NODE_LINKFLAG_HILITE set */
2648 void ED_node_link_insert(ScrArea *sa)
2649 {
2650         bNode *node, *select;
2651         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2652         bNodeLink *link;
2653         bNodeSocket *sockto;
2654         
2655         if(snode==NULL) return;
2656         
2657         /* get the link */
2658         for(link= snode->edittree->links.first; link; link=link->next)
2659                 if(link->flag & NODE_LINKFLAG_HILITE)
2660                         break;
2661         
2662         if(link) {
2663                 node= link->tonode;
2664                 sockto= link->tosock;
2665                 
2666                 link->tonode= select;
2667                 link->tosock= socket_best_match(&select->inputs, link->fromsock->type);
2668                 link->flag &= ~NODE_LINKFLAG_HILITE;
2669                 
2670                 nodeAddLink(snode->edittree, select, socket_best_match(&select->outputs, sockto->type), node, sockto);
2671                 ntreeSolveOrder(snode->edittree);       /* needed for pointers */
2672                 snode_tag_changed(snode, select);
2673                 ED_node_changed_update(snode->id, select);
2674         }
2675 }
2676
2677
2678 /* test == 0, clear all intersect flags */
2679 void ED_node_link_intersect_test(ScrArea *sa, int test)
2680 {
2681         bNode *select;
2682         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2683         bNodeLink *link, *selink=NULL;
2684         float mcoords[6][2];
2685         
2686         if(snode==NULL) return;
2687         
2688         /* clear flags */
2689         for(link= snode->edittree->links.first; link; link=link->next)
2690                 link->flag &= ~NODE_LINKFLAG_HILITE;
2691         
2692         if(test==0) return;
2693         
2694         /* okay, there's 1 node, without links, now intersect */
2695         mcoords[0][0]= select->totr.xmin;
2696         mcoords[0][1]= select->totr.ymin;
2697         mcoords[1][0]= select->totr.xmax;
2698         mcoords[1][1]= select->totr.ymin;
2699         mcoords[2][0]= select->totr.xmax;
2700         mcoords[2][1]= select->totr.ymax;
2701         mcoords[3][0]= select->totr.xmin;
2702         mcoords[3][1]= select->totr.ymax;
2703         mcoords[4][0]= select->totr.xmin;
2704         mcoords[4][1]= select->totr.ymin;
2705         mcoords[5][0]= select->totr.xmax;
2706         mcoords[5][1]= select->totr.ymax;
2707         
2708         /* we only tag a single link for intersect now */
2709         /* idea; use header dist when more? */
2710         for(link= snode->edittree->links.first; link; link=link->next) {
2711                 
2712                 if(cut_links_intersect(link, mcoords, 5)) { /* intersect code wants edges */
2713                         if(selink) 
2714                                 break;
2715                         selink= link;
2716                 }
2717         }
2718                 
2719         if(link==NULL && selink)
2720                 selink->flag |= NODE_LINKFLAG_HILITE;
2721 }
2722
2723
2724 /* ******************************** */
2725 // XXX some code needing updating to operators...
2726
2727
2728 /* goes over all scenes, reads render layers */
2729 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
2730 {
2731         Main *bmain= CTX_data_main(C);
2732         SpaceNode *snode= CTX_wm_space_node(C);
2733         Scene *curscene= CTX_data_scene(C), *scene;
2734         bNode *node;
2735
2736         ED_preview_kill_jobs(C);
2737
2738         /* first tag scenes unread */
2739         for(scene= bmain->scene.first; scene; scene= scene->id.next) 
2740                 scene->id.flag |= LIB_DOIT;
2741
2742         for(node= snode->edittree->nodes.first; node; node= node->next) {
2743                 if(node->type==CMP_NODE_R_LAYERS) {
2744                         ID *id= node->id;
2745                         if(id->flag & LIB_DOIT) {
2746                                 RE_ReadRenderResult(curscene, (Scene *)id);
2747                                 ntreeCompositTagRender((Scene *)id);
2748                                 id->flag &= ~LIB_DOIT;
2749                         }
2750                 }
2751         }
2752         
2753         snode_notify(C, snode);
2754         snode_dag_update(C, snode);
2755
2756         return OPERATOR_FINISHED;
2757 }
2758
2759 void NODE_OT_read_renderlayers(wmOperatorType *ot)
2760 {
2761         
2762         ot->name= "Read Render Layers";
2763         ot->idname= "NODE_OT_read_renderlayers";
2764         
2765         ot->exec= node_read_renderlayers_exec;
2766         
2767         ot->poll= composite_node_active;
2768         
2769         /* flags */
2770         ot->flag= 0;
2771 }
2772
2773 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
2774 {
2775         Main *bmain= CTX_data_main(C);
2776         SpaceNode *snode= CTX_wm_space_node(C);
2777         Scene *curscene= CTX_data_scene(C);
2778         Render *re= RE_NewRender(curscene->id.name);
2779
2780         WM_cursor_wait(1);
2781
2782         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
2783         snode_notify(C, snode);
2784         snode_dag_update(C, snode);
2785         
2786         WM_cursor_wait(0);
2787         return OPERATOR_FINISHED;
2788 }
2789
2790
2791 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
2792 {
2793         
2794         ot->name= "Read Full Sample Layers";
2795         ot->idname= "NODE_OT_read_fullsamplelayers";
2796         
2797         ot->exec= node_read_fullsamplelayers_exec;
2798         
2799         ot->poll= composite_node_active;
2800         
2801         /* flags */
2802         ot->flag= 0;
2803 }
2804
2805 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
2806 {
2807         Scene *sce= CTX_data_scene(C);
2808         bNode *node;
2809         
2810         for(node= sce->nodetree->nodes.first; node; node= node->next) {
2811                 if(node->id==(ID *)sce && node->need_exec) {
2812                         break;
2813                 }
2814         }
2815         if(node) {
2816                 SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2817                 
2818                 if(srl) {
2819                         PointerRNA op_ptr;
2820                         
2821                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
2822                         RNA_string_set(&op_ptr, "layer", srl->name);
2823                         RNA_string_set(&op_ptr, "scene", sce->id.name+2);
2824                         
2825                         /* to keep keypositions */
2826                         sce->r.scemode |= R_NO_FRAME_UPDATE;
2827                         
2828                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
2829
2830                         WM_operator_properties_free(&op_ptr);
2831                         
2832                         return OPERATOR_FINISHED;
2833                 }
2834                    
2835         }
2836         return OPERATOR_CANCELLED;
2837 }
2838
2839 void NODE_OT_render_changed(wmOperatorType *ot)
2840 {
2841         
2842         ot->name= "Render Changed Layer";
2843         ot->idname= "NODE_OT_render_changed";
2844         
2845         ot->exec= node_render_changed_exec;
2846         
2847         ot->poll= composite_node_active;
2848         
2849         /* flags */
2850         ot->flag= 0;
2851 }
2852
2853
2854 /* ****************** Make Group operator ******************* */
2855
2856 static int node_group_make_exec(bContext *C, wmOperator *op)
2857 {
2858         SpaceNode *snode = CTX_wm_space_node(C);
2859         bNode *gnode;
2860         
2861         if(snode->edittree!=snode->nodetree) {
2862                 BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
2863                 return OPERATOR_CANCELLED;
2864         }
2865         
2866         /* for time being... is too complex to handle */
2867         if(snode->treetype==NTREE_COMPOSIT) {
2868                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
2869                         if(gnode->flag & SELECT)
2870                                 if(gnode->type==CMP_NODE_R_LAYERS)
2871                                         break;
2872                 }
2873                 
2874                 if(gnode) {
2875                         BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
2876                         return OPERATOR_CANCELLED;
2877                 }
2878         }
2879
2880         ED_preview_kill_jobs(C);
2881         
2882         gnode= nodeMakeGroupFromSelected(snode->nodetree);
2883         if(gnode==NULL) {
2884                 BKE_report(op->reports, RPT_WARNING, "Can not make Group");
2885                 return OPERATOR_CANCELLED;
2886         }
2887         else {
2888                 nodeSetActive(snode->nodetree, gnode);
2889                 ntreeSolveOrder(snode->nodetree);
2890         }
2891         
2892         snode_notify(C, snode);
2893         snode_dag_update(C, snode);
2894         
2895         return OPERATOR_FINISHED;
2896 }
2897
2898 void NODE_OT_group_make(wmOperatorType *ot)
2899 {
2900         /* identifiers */
2901         ot->name = "Group";
2902         ot->description = "Make group from selected nodes";
2903         ot->idname = "NODE_OT_group_make";
2904         
2905         /* api callbacks */
2906         ot->exec = node_group_make_exec;
2907         ot->poll = ED_operator_node_active;
2908         
2909         /* flags */
2910         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2911 }
2912
2913 /* ****************** Hide operator *********************** */
2914
2915 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
2916 {
2917         int tot_eq= 0, tot_neq= 0;
2918         bNode *node;
2919
2920         for(node= snode->edittree->nodes.first; node; node= node->next) {
2921                 if(node->flag & SELECT) {
2922
2923                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
2924                                 continue;
2925
2926                         if(node->flag & toggle_flag)
2927                                 tot_eq++;
2928                         else
2929                                 tot_neq++;
2930                 }
2931         }
2932         for(node= snode->edittree->nodes.first; node; node= node->next) {
2933                 if(node->flag & SELECT) {
2934
2935                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
2936                                 continue;
2937
2938                         if( (tot_eq && tot_neq) || tot_eq==0)
2939                                 node->flag |= toggle_flag;
2940                         else
2941                                 node->flag &= ~toggle_flag;
2942                 }
2943         }
2944 }
2945
2946 static int node_hide_exec(bContext *C, wmOperator *UNUSED(op))
2947 {
2948         SpaceNode *snode= CTX_wm_space_node(C);
2949         
2950         /* sanity checking (poll callback checks this already) */
2951         if((snode == NULL) || (snode->edittree == NULL))
2952                 return OPERATOR_CANCELLED;
2953         
2954         node_flag_toggle_exec(snode, NODE_HIDDEN);
2955         
2956         snode_notify(C, snode);
2957         
2958         return OPERATOR_FINISHED;
2959 }
2960
2961 void NODE_OT_hide_toggle(wmOperatorType *ot)
2962 {
2963         /* identifiers */
2964         ot->name= "Hide";
2965         ot->description= "Toggle hiding of selected nodes";
2966         ot->idname= "NODE_OT_hide_toggle";
2967         
2968         /* callbacks */
2969         ot->exec= node_hide_exec;
2970         ot->poll= ED_operator_node_active;
2971
2972         /* flags */
2973         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2974 }
2975
2976 static int node_preview_exec(bContext *C, wmOperator *UNUSED(op))
2977 {
2978         SpaceNode *snode= CTX_wm_space_node(C);
2979
2980         /* sanity checking (poll callback checks this already) */
2981         if((snode == NULL) || (snode->edittree == NULL))
2982                 return OPERATOR_CANCELLED;
2983
2984         ED_preview_kill_jobs(C);
2985
2986         node_flag_toggle_exec(snode, NODE_PREVIEW);
2987
2988         snode_notify(C, snode);
2989
2990         return OPERATOR_FINISHED;
2991 }
2992
2993 void NODE_OT_preview_toggle(wmOperatorType *ot)
2994 {
2995         /* identifiers */
2996         ot->name= "Toggle Node Preview";
2997         ot->description= "Toggle preview display for selected nodes";
2998         ot->idname= "NODE_OT_preview_toggle";
2999
3000         /* callbacks */
3001         ot->exec= node_preview_exec;
3002         ot->poll= ED_operator_node_active;
3003
3004         /* flags */
3005         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3006 }
3007
3008 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
3009 {
3010         SpaceNode *snode= CTX_wm_space_node(C);
3011         bNode *node;
3012         int hidden= 0;
3013
3014         /* sanity checking (poll callback checks this already) */
3015         if((snode == NULL) || (snode->edittree == NULL))
3016                 return OPERATOR_CANCELLED;
3017
3018         ED_preview_kill_jobs(C);
3019
3020         for(node= snode->edittree->nodes.first; node; node= node->next) {
3021                 if(node->flag & SELECT) {
3022                         if(node_has_hidden_sockets(node)) {
3023                                 hidden= 1;
3024                                 break;
3025                         }
3026                 }
3027         }
3028
3029         for(node= snode->edittree->nodes.first; node; node= node->next) {
3030                 if(node->flag & SELECT) {
3031                         node_set_hidden_sockets(snode, node, !hidden);
3032                 }
3033         }
3034
3035         node_tree_verify_groups(snode->nodetree);
3036
3037         snode_notify(C, snode);
3038
3039         return OPERATOR_FINISHED;
3040 }
3041
3042 void NODE_OT_hide_socket_toggle(wmOperatorType *ot)
3043 {
3044         /* identifiers */
3045         ot->name= "Toggle Hidden Node Sockets";
3046         ot->description= "Toggle unused node socket display";
3047         ot->idname= "NODE_OT_hide_socket_toggle";
3048
3049         /* callbacks */
3050         ot->exec= node_socket_toggle_exec;
3051         ot->poll= ED_operator_node_active;
3052
3053         /* flags */
3054         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3055 }
3056
3057 /* ****************** Mute operator *********************** */
3058
3059 static int node_mute_exec(bContext *C, wmOperator *UNUSED(op))
3060 {
3061         SpaceNode *snode= CTX_wm_space_node(C);
3062         bNode *node;
3063
3064         /* no disabling inside of groups */
3065         if(node_tree_get_editgroup(snode->nodetree))
3066                 return OPERATOR_CANCELLED;
3067         
3068         ED_preview_kill_jobs(C);
3069
3070         for(node= snode->edittree->nodes.first; node; node= node->next) {
3071                 if(node->flag & SELECT) {
3072                         /* Be able to mute in-/output nodes as well.  - DingTo
3073                         if(node->inputs.first && node->outputs.first) { */
3074                                 node->flag ^= NODE_MUTED;
3075                                 snode_tag_changed(snode, node);
3076                 }
3077         }
3078         
3079         snode_notify(C, snode);
3080         snode_dag_update(C, snode);
3081         
3082         return OPERATOR_FINISHED;
3083 }
3084
3085 void NODE_OT_mute_toggle(wmOperatorType *ot)
3086 {
3087         /* identifiers */
3088         ot->name= "Toggle Node Mute";
3089         ot->description= "Toggle muting of the nodes";
3090         ot->idname= "NODE_OT_mute_toggle";
3091         
3092         /* callbacks */
3093         ot->exec= node_mute_exec;
3094         ot->poll= ED_operator_node_active;
3095         
3096         /* flags */
3097         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3098 }
3099
3100 /* ****************** Delete operator ******************* */
3101
3102 static int node_delete_exec(bContext *C, wmOperator *UNUSED(op))
3103 {
3104         SpaceNode *snode= CTX_wm_space_node(C);
3105         bNode *node, *next;
3106         
3107         ED_preview_kill_jobs(C);
3108
3109         for(node= snode->edittree->nodes.first; node; node= next) {
3110                 next= node->next;
3111                 if(node->flag & SELECT) {
3112                         /* check id user here, nodeFreeNode is called for free dbase too */
3113                         if(node->id)
3114                                 node->id->us--;
3115                         nodeFreeNode(snode->edittree, node);
3116                 }
3117         }
3118         
3119         node_tree_verify_groups(snode->nodetree);
3120
3121         snode_notify(C, snode);
3122         snode_dag_update(C, snode);
3123         
3124         return OPERATOR_FINISHED;
3125 }
3126
3127 void NODE_OT_delete(wmOperatorType *ot)
3128 {
3129         /* identifiers */
3130         ot->name= "Delete";
3131         ot->description = "Delete selected nodes";
3132         ot->idname= "NODE_OT_delete";
3133         
3134         /* api callbacks */
3135         ot->exec= node_delete_exec;
3136         ot->poll= ED_operator_node_active;
3137         
3138         /* flags */
3139         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3140 }
3141