50a99650ec093fd51e83453156697fb6adec931d
[blender.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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 #include <stdio.h>
31 #include <stdlib.h>
32 #include <math.h>
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_action_types.h"
38 #include "DNA_brush_types.h"
39 #include "DNA_color_types.h"
40 #include "DNA_image_types.h"
41 #include "DNA_ipo_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_material_types.h"
44 #include "DNA_texture_types.h"
45 #include "DNA_node_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_userdef_types.h"
50
51 #include "BKE_context.h"
52 #include "BKE_colortools.h"
53 #include "BKE_global.h"
54 #include "BKE_image.h"
55 #include "BKE_library.h"
56 #include "BKE_main.h"
57 #include "BKE_node.h"
58 #include "BKE_material.h"
59 #include "BKE_paint.h"
60 #include "BKE_texture.h"
61 #include "BKE_report.h"
62 #include "BKE_scene.h"
63 #include "BKE_utildefines.h"
64
65 #include "ED_render.h"
66
67 #include "BIF_gl.h"
68
69 #include "BLI_arithb.h"
70 #include "BLI_blenlib.h"
71 #include "BLI_storage_types.h"
72
73 #include "RE_pipeline.h"
74
75 #include "IMB_imbuf_types.h"
76
77 #include "ED_space_api.h"
78 #include "ED_screen.h"
79 #include "ED_transform.h"
80 #include "ED_types.h"
81
82 #include "RNA_access.h"
83 #include "RNA_define.h"
84
85 #include "WM_api.h"
86 #include "WM_types.h"
87
88 #include "UI_interface.h"
89 #include "UI_view2d.h"
90  
91 #include "node_intern.h"
92
93 #define SOCK_IN         1
94 #define SOCK_OUT        2
95
96 /* ***************** composite job manager ********************** */
97
98 typedef struct CompoJob {
99         Scene *scene;
100         bNodeTree *ntree;
101         bNodeTree *localtree;
102         short *stop;
103         short *do_update;
104 } CompoJob;
105
106 /* called by compo, only to check job 'stop' value */
107 static int compo_breakjob(void *cjv)
108 {
109         CompoJob *cj= cjv;
110         
111         return *(cj->stop);
112 }
113
114 /* called by compo, wmJob sends notifier */
115 static void compo_redrawjob(void *cjv, char *str)
116 {
117         CompoJob *cj= cjv;
118         
119         *(cj->do_update)= 1;
120 }
121
122 static void compo_freejob(void *cjv)
123 {
124         CompoJob *cj= cjv;
125
126         if(cj->localtree) {
127                 ntreeLocalMerge(cj->localtree, cj->ntree);
128         }
129         MEM_freeN(cj);
130 }
131
132 /* only now we copy the nodetree, so adding many jobs while
133    sliding buttons doesn't frustrate */
134 static void compo_initjob(void *cjv)
135 {
136         CompoJob *cj= cjv;
137
138         cj->localtree= ntreeLocalize(cj->ntree);
139 }
140
141 /* called before redraw notifiers, it moves finished previews over */
142 static void compo_updatejob(void *cjv)
143 {
144         CompoJob *cj= cjv;
145         
146         ntreeLocalSync(cj->localtree, cj->ntree);
147 }
148
149
150 /* only this runs inside thread */
151 static void compo_startjob(void *cjv, short *stop, short *do_update)
152 {
153         CompoJob *cj= cjv;
154         bNodeTree *ntree= cj->localtree;
155
156         if(cj->scene->use_nodes==0)
157                 return;
158         
159         cj->stop= stop;
160         cj->do_update= do_update;
161         
162         ntree->test_break= compo_breakjob;
163         ntree->tbh= cj;
164         ntree->stats_draw= compo_redrawjob;
165         ntree->sdh= cj;
166         
167         // XXX BIF_store_spare();
168         
169         ntreeCompositExecTree(ntree, &cj->scene->r, 1); /* 1 is do_previews */
170         
171         ntree->test_break= NULL;
172         ntree->stats_draw= NULL;
173
174 }
175
176 void snode_composite_job(const bContext *C, ScrArea *sa)
177 {
178         SpaceNode *snode= sa->spacedata.first;
179         wmJob *steve;
180         CompoJob *cj;
181
182         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, WM_JOB_EXCL_RENDER);
183         cj= MEM_callocN(sizeof(CompoJob), "compo job");
184         
185         /* customdata for preview thread */
186         cj->scene= CTX_data_scene(C);
187         cj->ntree= snode->nodetree;
188         
189         /* setup job */
190         WM_jobs_customdata(steve, cj, compo_freejob);
191         WM_jobs_timer(steve, 0.1, NC_SCENE, NC_SCENE|ND_COMPO_RESULT);
192         WM_jobs_callbacks(steve, compo_startjob, compo_initjob, compo_updatejob);
193         
194         WM_jobs_start(CTX_wm_manager(C), steve);
195         
196 }
197
198 /* ***************************************** */
199
200 /* also checks for edited groups */
201 bNode *editnode_get_active(bNodeTree *ntree)
202 {
203         bNode *node;
204         
205         /* check for edited group */
206         for(node= ntree->nodes.first; node; node= node->next)
207                 if(node->flag & NODE_GROUP_EDIT)
208                         break;
209         if(node)
210                 return nodeGetActive((bNodeTree *)node->id);
211         else
212                 return nodeGetActive(ntree);
213 }
214
215 void snode_handle_recalc(bContext *C, SpaceNode *snode)
216 {
217         if(snode->treetype==NTREE_SHADER)
218                 WM_event_add_notifier(C, NC_MATERIAL|ND_NODES, snode->id);
219         else if(snode->treetype==NTREE_COMPOSIT)
220                 WM_event_add_notifier(C, NC_SCENE|ND_NODES, snode->id);
221         else if(snode->treetype==NTREE_TEXTURE)
222                 WM_event_add_notifier(C, NC_TEXTURE|ND_NODES, snode->id);
223 }
224
225 #if 0
226 static int image_detect_file_sequence(int *start_p, int *frames_p, char *str)
227 {
228         SpaceFile *sfile;
229         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX], filename[FILE_MAX];
230         int a, frame, totframe, found, minframe;
231         unsigned short numlen;
232
233         sfile= scrarea_find_space_of_type(curarea, SPACE_FILE);
234         if(sfile==NULL || sfile->filelist==NULL)
235                 return 0;
236
237         /* find first frame */
238         found= 0;
239         minframe= 0;
240
241         for(a=0; a<sfile->totfile; a++) {
242                 if(sfile->filelist[a].flags & ACTIVE) {
243                         BLI_strncpy(name, sfile->filelist[a].relname, sizeof(name));
244                         frame= BLI_stringdec(name, head, tail, &numlen);
245
246                         if(!found || frame < minframe) {
247                                 BLI_strncpy(filename, name, sizeof(name));
248                                 minframe= frame;
249                                 found= 1;
250                         }
251                 }
252         }
253
254         /* not one frame found */
255         if(!found)
256                 return 0;
257
258         /* counter number of following frames */
259         found= 1;
260         totframe= 0;
261
262         for(frame=minframe; found; frame++) {
263                 found= 0;
264                 BLI_strncpy(name, filename, sizeof(name));
265                 BLI_stringenc(name, head, tail, numlen, frame);
266
267                 for(a=0; a<sfile->totfile; a++) {
268                         if(sfile->filelist[a].flags & ACTIVE) {
269                                 if(strcmp(sfile->filelist[a].relname, name) == 0) {
270                                         found= 1;
271                                         totframe++;
272                                         break;
273                                 }
274                         }
275                 }
276         }
277
278         if(totframe > 1) {
279                 BLI_strncpy(str, sfile->dir, sizeof(name));
280                 strcat(str, filename);
281
282                 *start_p= minframe;
283                 *frames_p= totframe;
284                 return 1;
285         }
286
287         return 0;
288 }
289
290 static void load_node_image(char *str)  /* called from fileselect */
291 {
292         SpaceNode *snode= curarea->spacedata.first;
293         bNode *node= nodeGetActive(snode->edittree);
294         Image *ima= NULL;
295         ImageUser *iuser= node->storage;
296         char filename[FILE_MAX];
297         int start=0, frames=0, sequence;
298
299         sequence= image_detect_file_sequence(&start, &frames, filename);
300         if(sequence)
301                 str= filename;
302         
303         ima= BKE_add_image_file(str);
304         if(ima) {
305                 if(node->id)
306                         node->id->us--;
307                 
308                 node->id= &ima->id;
309                 id_us_plus(node->id);
310
311                 BLI_strncpy(node->name, node->id->name+2, 21);
312
313                 if(sequence) {
314                         ima->source= IMA_SRC_SEQUENCE;
315                         iuser->frames= frames;
316                         iuser->offset= start-1;
317                 }
318                                    
319                 BKE_image_signal(ima, node->storage, IMA_SIGNAL_RELOAD);
320                 
321                 NodeTagChanged(snode->edittree, node);
322                 // XXX snode_handle_recalc(C, snode);
323         }
324 }
325
326 static void set_node_imagepath(char *str)       /* called from fileselect */
327 {
328         SpaceNode *snode= curarea->spacedata.first;
329         bNode *node= nodeGetActive(snode->edittree);
330         BLI_strncpy(((NodeImageFile *)node->storage)->name, str, sizeof( ((NodeImageFile *)node->storage)->name ));
331 }
332
333 #endif /* 0 */
334
335 bNode *node_tree_get_editgroup(bNodeTree *nodetree)
336 {
337         bNode *gnode;
338         
339         /* get the groupnode */
340         for(gnode= nodetree->nodes.first; gnode; gnode= gnode->next)
341                 if(gnode->flag & NODE_GROUP_EDIT)
342                         break;
343         return gnode;
344 }
345
346 #if 0
347
348 /* node has to be of type 'render layers' */
349 /* is a bit clumsy copying renderdata here... scene nodes use render size of current render */
350 static void composite_node_render(SpaceNode *snode, bNode *node)
351 {
352         RenderData rd;
353         Scene *scene= NULL;
354         int scemode, actlay;
355         
356         /* the button press won't show up otherwise, button hilites disabled */
357         force_draw(0);
358         
359         if(node->id && node->id!=(ID *)G.scene) {
360                 scene= G.scene;
361                 set_scene_bg((Scene *)node->id);
362                 rd= G.scene->r;
363                 G.scene->r.xsch= scene->r.xsch;
364                 G.scene->r.ysch= scene->r.ysch;
365                 G.scene->r.size= scene->r.size;
366                 G.scene->r.mode &= ~(R_BORDER|R_DOCOMP);
367                 G.scene->r.mode |= scene->r.mode & R_BORDER;
368                 G.scene->r.border= scene->r.border;
369                 G.scene->r.cfra= scene->r.cfra;
370         }
371         
372         scemode= G.scene->r.scemode;
373         actlay= G.scene->r.actlay;
374
375         G.scene->r.scemode |= R_SINGLE_LAYER|R_COMP_RERENDER;
376         G.scene->r.actlay= node->custom1;
377         
378         BIF_do_render(0);
379         
380         G.scene->r.scemode= scemode;
381         G.scene->r.actlay= actlay;
382
383         node->custom2= 0;
384         
385         if(scene) {
386                 G.scene->r= rd;
387                 set_scene_bg(scene);
388         }
389 }
390
391 static void composit_node_event(SpaceNode *snode, short event)
392 {
393         
394         switch(event) {
395                 case B_REDR:
396                         // allqueue(REDRAWNODE, 1);
397                         break;
398                 case B_NODE_LOADIMAGE:
399                 {
400                         bNode *node= nodeGetActive(snode->edittree);
401                         char name[FILE_MAXDIR+FILE_MAXFILE];
402                         
403                         if(node->id)
404                                 strcpy(name, ((Image *)node->id)->name);
405                         else strcpy(name, U.textudir);
406                         if (G.qual & LR_CTRLKEY) {
407                                 activate_imageselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
408                         } else {
409                                 activate_fileselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
410                         }
411                         break;
412                 }
413                 case B_NODE_SETIMAGE:
414                 {
415                         bNode *node= nodeGetActive(snode->edittree);
416                         char name[FILE_MAXDIR+FILE_MAXFILE];
417                         
418                         strcpy(name, ((NodeImageFile *)node->storage)->name);
419                         if (G.qual & LR_CTRLKEY) {
420                                 activate_imageselect(FILE_SPECIAL, "SELECT OUTPUT DIR", name, set_node_imagepath);
421                         } else {
422                                 activate_fileselect(FILE_SPECIAL, "SELECT OUTPUT DIR", name, set_node_imagepath);
423                         }
424                         break;
425                 }
426                 case B_NODE_TREE_EXEC:
427                         // XXX                  snode_handle_recalc(snode);
428                         break;          
429                 default:
430                         /* B_NODE_EXEC */
431                 {
432                         bNode *node= BLI_findlink(&snode->edittree->nodes, event-B_NODE_EXEC);
433                         if(node) {
434                                 NodeTagChanged(snode->edittree, node);
435                                 /* don't use NodeTagIDChanged, it gives far too many recomposites for image, scene layers, ... */
436                                 
437                                 /* not the best implementation of the world... but we need it to work now :) */
438                                 if(node->type==CMP_NODE_R_LAYERS && node->custom2) {
439                                         /* add event for this window (after render curarea can be changed) */
440                                         addqueue(curarea->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
441                                         
442                                         composite_node_render(snode, node);
443                                         // XXX                  snode_handle_recalc(snode);
444                                         
445                                         /* add another event, a render can go fullscreen and open new window */
446                                         addqueue(curarea->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
447                                 }
448                                 else {
449                                         node= node_tree_get_editgroup(snode->nodetree);
450                                         if(node)
451                                                 NodeTagIDChanged(snode->nodetree, node->id);
452                                         
453                                         // XXX                  snode_handle_recalc(snode);
454                                 }
455                         }
456                 }                       
457         }
458 }
459
460 static void texture_node_event(SpaceNode *snode, short event)
461 {
462         switch(event) {
463                 case B_REDR:
464                         // allqueue(REDRAWNODE, 1);
465                         break;
466                 case B_NODE_LOADIMAGE:
467                 {
468                         bNode *node= nodeGetActive(snode->edittree);
469                         char name[FILE_MAXDIR+FILE_MAXFILE];
470                         
471                         if(node->id)
472                                 strcpy(name, ((Image *)node->id)->name);
473                         else strcpy(name, U.textudir);
474                         if (G.qual & LR_CTRLKEY) {
475                                 activate_imageselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
476                         } else {
477                                 activate_fileselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
478                         }
479                         break;
480                 }
481                 default:
482                         /* B_NODE_EXEC */
483                         ntreeTexCheckCyclics( snode->nodetree );
484                         // XXX                  snode_handle_recalc(snode);
485                         // allqueue(REDRAWNODE, 1);
486                         break;
487         }
488 }
489
490 #endif /* 0  */
491 /* assumes nothing being done in ntree yet, sets the default in/out node */
492 /* called from shading buttons or header */
493 void ED_node_shader_default(Material *ma)
494 {
495         bNode *in, *out;
496         bNodeSocket *fromsock, *tosock;
497         
498         /* but lets check it anyway */
499         if(ma->nodetree) {
500                 printf("error in shader initialize\n");
501                 return;
502         }
503         
504         ma->nodetree= ntreeAddTree(NTREE_SHADER);
505         
506         out= nodeAddNodeType(ma->nodetree, SH_NODE_OUTPUT, NULL, NULL);
507         out->locx= 300.0f; out->locy= 300.0f;
508         
509         in= nodeAddNodeType(ma->nodetree, SH_NODE_MATERIAL, NULL, NULL);
510         in->locx= 10.0f; in->locy= 300.0f;
511         nodeSetActive(ma->nodetree, in);
512         
513         /* only a link from color to color */
514         fromsock= in->outputs.first;
515         tosock= out->inputs.first;
516         nodeAddLink(ma->nodetree, in, fromsock, out, tosock);
517         
518         ntreeSolveOrder(ma->nodetree);  /* needed for pointers */
519 }
520
521 /* assumes nothing being done in ntree yet, sets the default in/out node */
522 /* called from shading buttons or header */
523 void ED_node_composit_default(Scene *sce)
524 {
525         bNode *in, *out;
526         bNodeSocket *fromsock, *tosock;
527         
528         /* but lets check it anyway */
529         if(sce->nodetree) {
530                 printf("error in composit initialize\n");
531                 return;
532         }
533         
534         sce->nodetree= ntreeAddTree(NTREE_COMPOSIT);
535         
536         out= nodeAddNodeType(sce->nodetree, CMP_NODE_COMPOSITE, NULL, NULL);
537         out->locx= 300.0f; out->locy= 400.0f;
538         out->id= &sce->id;
539         
540         in= nodeAddNodeType(sce->nodetree, CMP_NODE_R_LAYERS, NULL, NULL);
541         in->locx= 10.0f; in->locy= 400.0f;
542         in->id= &sce->id;
543         nodeSetActive(sce->nodetree, in);
544         
545         /* links from color to color */
546         fromsock= in->outputs.first;
547         tosock= out->inputs.first;
548         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
549         
550         ntreeSolveOrder(sce->nodetree); /* needed for pointers */
551         
552         // XXX ntreeCompositForceHidden(sce->nodetree);
553 }
554
555 /* assumes nothing being done in ntree yet, sets the default in/out node */
556 /* called from shading buttons or header */
557 void ED_node_texture_default(Tex *tx)
558 {
559         bNode *in, *out;
560         bNodeSocket *fromsock, *tosock;
561         
562         /* but lets check it anyway */
563         if(tx->nodetree) {
564                 printf("error in texture initialize\n");
565                 return;
566         }
567         
568         tx->nodetree= ntreeAddTree(NTREE_TEXTURE);
569         
570         out= nodeAddNodeType(tx->nodetree, TEX_NODE_OUTPUT, NULL, NULL);
571         out->locx= 300.0f; out->locy= 300.0f;
572         
573         in= nodeAddNodeType(tx->nodetree, TEX_NODE_CHECKER, NULL, NULL);
574         in->locx= 10.0f; in->locy= 300.0f;
575         nodeSetActive(tx->nodetree, in);
576         
577         fromsock= in->outputs.first;
578         tosock= out->inputs.first;
579         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
580         
581         ntreeSolveOrder(tx->nodetree);  /* needed for pointers */
582 }
583
584 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
585 void snode_set_context(SpaceNode *snode, Scene *scene)
586 {
587         Object *ob= OBACT;
588         bNode *node= NULL;
589         
590         snode->nodetree= NULL;
591         snode->id= snode->from= NULL;
592         
593         if(snode->treetype==NTREE_SHADER) {
594                 /* need active object, or we allow pinning... */
595                 if(ob) {
596                         Material *ma= give_current_material(ob, ob->actcol);
597                         if(ma) {
598                                 snode->from= &ob->id;
599                                 snode->id= &ma->id;
600                                 snode->nodetree= ma->nodetree;
601                         }
602                 }
603         }
604         else if(snode->treetype==NTREE_COMPOSIT) {
605                 snode->from= NULL;
606                 snode->id= &scene->id;
607                 
608                 /* bit clumsy but reliable way to see if we draw first time */
609                 if(snode->nodetree==NULL)
610                         ntreeCompositForceHidden(scene->nodetree, scene);
611                 
612                 snode->nodetree= scene->nodetree;
613         }
614         else if(snode->treetype==NTREE_TEXTURE) {
615                 Tex *tx= NULL;
616
617                 if(snode->texfrom==SNODE_TEX_OBJECT) {
618                         if(ob) {
619                                 tx= give_current_texture(ob, ob->actcol);
620
621                                 if(ob->type == OB_LAMP)
622                                         snode->from= (ID*)ob->data;
623                                 else
624                                         snode->from= (ID*)give_current_material(ob, ob->actcol);
625
626                                 /* from is not set fully for material nodes, should be ID + Node then */
627                         }
628                 }
629                 else if(snode->texfrom==SNODE_TEX_WORLD) {
630                         tx= give_current_world_texture(scene);
631                         snode->from= (ID *)scene->world;
632                 }
633                 else {
634                         MTex *mtex= NULL;
635                         Brush *brush= NULL;
636                         
637                         if(ob && (ob->mode & OB_MODE_SCULPT))
638                                 brush= paint_brush(&scene->toolsettings->sculpt->paint);
639                         else
640                                 brush= paint_brush(&scene->toolsettings->imapaint.paint);
641
642                         if(brush && brush->texact != -1)
643                                 mtex= brush->mtex[brush->texact];
644
645                         snode->from= (ID *)brush;
646
647                         if(mtex)
648                                 tx= mtex->tex;
649                 }
650                 
651                 if(tx) {
652                         snode->id= &tx->id;
653                         snode->nodetree= tx->nodetree;
654                 }
655         }
656         
657         /* find editable group */
658         if(snode->nodetree)
659                 for(node= snode->nodetree->nodes.first; node; node= node->next)
660                         if(node->flag & NODE_GROUP_EDIT)
661                                 break;
662         
663         if(node && node->id)
664                 snode->edittree= (bNodeTree *)node->id;
665         else
666                 snode->edittree= snode->nodetree;
667 }
668
669 #if 0
670 /* on activate image viewer, check if we show it */
671 static void node_active_image(Image *ima)
672 {
673         ScrArea *sa;
674         SpaceImage *sima= NULL;
675         
676         /* find an imagewindow showing render result */
677         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
678                 if(sa->spacetype==SPACE_IMAGE) {
679                         sima= sa->spacedata.first;
680                         if(sima->image && sima->image->source!=IMA_SRC_VIEWER)
681                                 break;
682                 }
683         }
684         if(sa && sima) {
685                 sima->image= ima;
686                 scrarea_queue_winredraw(sa);
687                 scrarea_queue_headredraw(sa);
688         }
689 }
690 #endif /* 0 */
691
692 void node_set_active(SpaceNode *snode, bNode *node)
693 {
694         
695         nodeSetActive(snode->edittree, node);
696         
697         #if 0
698         // XXX
699         if(node->type!=NODE_GROUP) {
700                 
701                 /* tree specific activate calls */
702                 if(snode->treetype==NTREE_SHADER) {
703                         
704                         /* when we select a material, active texture is cleared, for buttons */
705                         if(node->id && GS(node->id->name)==ID_MA)
706                                 nodeClearActiveID(snode->edittree, ID_TE);
707                         if(node->id)
708                                 ; // XXX BIF_preview_changed(-1);       /* temp hack to force texture preview to update */
709                         
710                         // allqueue(REDRAWBUTSSHADING, 1);
711                         // allqueue(REDRAWIPO, 0);
712                 }
713                 else if(snode->treetype==NTREE_COMPOSIT) {
714                         /* make active viewer, currently only 1 supported... */
715                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
716                                 bNode *tnode;
717                                 int was_output= node->flag & NODE_DO_OUTPUT;
718
719                                 for(tnode= snode->edittree->nodes.first; tnode; tnode= tnode->next)
720                                         if( ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
721                                                 tnode->flag &= ~NODE_DO_OUTPUT;
722                                 
723                                 node->flag |= NODE_DO_OUTPUT;
724                                 if(was_output==0) {
725                                         bNode *gnode;
726                                         
727                                         NodeTagChanged(snode->edittree, node);
728                                         
729                                         /* if inside group, tag entire group */
730                                         gnode= node_tree_get_editgroup(snode->nodetree);
731                                         if(gnode)
732                                                 NodeTagIDChanged(snode->nodetree, gnode->id);
733                                         
734                                         // XXX                  snode_handle_recalc(snode);
735                                 }
736                                 
737                                 /* addnode() doesnt link this yet... */
738                                 node->id= (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
739                         }
740                         else if(node->type==CMP_NODE_IMAGE) {
741                                 if(node->id)
742                                         node_active_image((Image *)node->id);
743                         }
744                         else if(node->type==CMP_NODE_R_LAYERS) {
745                                 if(node->id==NULL || node->id==(ID *)G.scene) {
746                                         G.scene->r.actlay= node->custom1;
747                                         // allqueue(REDRAWBUTSSCENE, 0);
748                                 }
749                         }
750                 }
751                 else if(snode->treetype==NTREE_TEXTURE) {
752                         if(node->id)
753                                 ; // XXX BIF_preview_changed(-1);
754                         // allqueue(REDRAWBUTSSHADING, 1);
755                         // allqueue(REDRAWIPO, 0);
756                 }
757         }
758         #endif /* 0 */
759 }
760
761 /* ***************** Edit Group operator ************* */
762
763 void snode_make_group_editable(SpaceNode *snode, bNode *gnode)
764 {
765         bNode *node;
766         
767         /* make sure nothing has group editing on */
768         for(node= snode->nodetree->nodes.first; node; node= node->next)
769                 node->flag &= ~NODE_GROUP_EDIT;
770         
771         if(gnode==NULL) {
772                 /* with NULL argument we do a toggle */
773                 if(snode->edittree==snode->nodetree)
774                         gnode= nodeGetActive(snode->nodetree);
775         }
776         
777         if(gnode && gnode->type==NODE_GROUP && gnode->id) {
778                 if(gnode->id->lib)
779                         ntreeMakeLocal((bNodeTree *)gnode->id);
780
781                 gnode->flag |= NODE_GROUP_EDIT;
782                 snode->edittree= (bNodeTree *)gnode->id;
783                 
784                 /* deselect all other nodes, so we can also do grabbing of entire subtree */
785                 for(node= snode->nodetree->nodes.first; node; node= node->next)
786                         node->flag &= ~SELECT;
787                 gnode->flag |= SELECT;
788                 
789         }
790         else 
791                 snode->edittree= snode->nodetree;
792         
793         ntreeSolveOrder(snode->nodetree);
794         
795         /* finally send out events for new active node */
796         if(snode->treetype==NTREE_SHADER) {
797                 // allqueue(REDRAWBUTSSHADING, 0);
798                 
799                 // XXX BIF_preview_changed(-1); /* temp hack to force texture preview to update */
800         }
801 }
802
803 static int node_group_edit_exec(bContext *C, wmOperator *op)
804 {
805         SpaceNode *snode = CTX_wm_space_node(C);
806         bNode *gnode;
807
808         gnode= nodeGetActive(snode->edittree);
809         snode_make_group_editable(snode, gnode);
810
811         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
812
813         return OPERATOR_FINISHED;
814 }
815
816 static int node_group_edit_invoke(bContext *C, wmOperator *op, wmEvent *event)
817 {
818         SpaceNode *snode = CTX_wm_space_node(C);
819         bNode *gnode;
820
821         gnode= nodeGetActive(snode->edittree);
822         if(gnode && gnode->type==NODE_GROUP && gnode->id && gnode->id->lib) {
823                 uiPupMenuOkee(C, op->type->idname, "Make group local?");
824                 return OPERATOR_CANCELLED;
825         }
826
827         return node_group_edit_exec(C, op);
828 }
829
830 void NODE_OT_group_edit(wmOperatorType *ot)
831 {
832         /* identifiers */
833         ot->name = "Edit Group";
834         ot->description = "Edit node group.";
835         ot->idname = "NODE_OT_group_edit";
836         
837         /* api callbacks */
838         ot->invoke = node_group_edit_invoke;
839         ot->exec = node_group_edit_exec;
840         ot->poll = ED_operator_node_active;
841         
842         /* flags */
843         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
844 }
845
846 /* ******************** Ungroup operator ********************** */
847
848 static int node_group_ungroup_exec(bContext *C, wmOperator *op)
849 {
850         SpaceNode *snode = CTX_wm_space_node(C);
851         bNode *gnode;
852
853         /* are we inside of a group? */
854         gnode= node_tree_get_editgroup(snode->nodetree);
855         if(gnode)
856                 snode_make_group_editable(snode, NULL);
857         
858         gnode= nodeGetActive(snode->edittree);
859         if(gnode==NULL)
860                 return OPERATOR_CANCELLED;
861         
862         if(gnode->type!=NODE_GROUP) {
863                 BKE_report(op->reports, RPT_ERROR, "Not a group");
864                 return OPERATOR_CANCELLED;
865         }
866         else if(!nodeGroupUnGroup(snode->edittree, gnode)) {
867                 BKE_report(op->reports, RPT_ERROR, "Can't ungroup");
868                 return OPERATOR_CANCELLED;
869         }
870
871         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
872
873         return OPERATOR_FINISHED;
874 }
875
876 void NODE_OT_group_ungroup(wmOperatorType *ot)
877 {
878         /* identifiers */
879         ot->name = "Ungroup";
880         ot->description = "Ungroup selected nodes.";
881         ot->idname = "NODE_OT_group_ungroup";
882         
883         /* api callbacks */
884         ot->exec = node_group_ungroup_exec;
885         ot->poll = ED_operator_node_active;
886         
887         /* flags */
888         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
889 }
890
891 /* when links in groups change, inputs/outputs change, nodes added/deleted... */
892 static void node_tree_verify_groups(bNodeTree *nodetree)
893 {
894         bNode *gnode;
895         
896         gnode= node_tree_get_editgroup(nodetree);
897         
898         /* does all materials */
899         if(gnode)
900                 nodeVerifyGroup((bNodeTree *)gnode->id);
901         
902 }
903
904 #if 0
905
906 static void node_addgroup(SpaceNode *snode)
907 {
908         bNodeTree *ngroup;
909         int tot= 0, offs, val;
910         char *strp;
911         
912         if(snode->edittree!=snode->nodetree) {
913                 error("Can not add a Group in a Group");
914                 return;
915         }
916         
917         /* construct menu with choices */
918         for(ngroup= G.main->nodetree.first; ngroup; ngroup= ngroup->id.next) {
919                 if(ngroup->type==snode->treetype)
920                         tot++;
921         }
922         if(tot==0) {
923                 error("No groups available in database");
924                 return;
925         }
926         strp= MEM_mallocN(32*tot+32, "menu");
927         strcpy(strp, "Add Group %t");
928         offs= strlen(strp);
929         
930         for(tot=0, ngroup= G.main->nodetree.first; ngroup; ngroup= ngroup->id.next, tot++) {
931                 if(ngroup->type==snode->treetype)
932                         offs+= sprintf(strp+offs, "|%s %%x%d", ngroup->id.name+2, tot);
933         }       
934         
935         val= pupmenu(strp);
936         if(val>=0) {
937                 ngroup= BLI_findlink(&G.main->nodetree, val);
938                 if(ngroup) {
939                         bNode *node= nodeAddNodeType(snode->edittree, NODE_GROUP, ngroup, NULL);
940                         
941                         /* generics */
942                         if(node) {
943                                 float locx, locy;
944                                 short mval[2];
945
946                                 node_deselectall(snode, 0);
947                                 
948                                 getmouseco_areawin(mval);
949                                 areamouseco_to_ipoco(G.v2d, mval, &locx, &locy);
950                                 
951                                 node->locx= locx;
952                                 node->locy= locy + 60.0f;               // arbitrary.. so its visible
953                                 node->flag |= SELECT;
954                                 
955                                 id_us_plus(node->id);
956                                 
957                                 node_set_active(snode, node);
958                         }
959                 }                       
960         }
961         MEM_freeN(strp);
962 }
963
964 #endif /* 0 */
965
966 /* ************************** Node generic ************** */
967
968 /* allows to walk the list in order of visibility */
969 bNode *next_node(bNodeTree *ntree)
970 {
971         static bNode *current=NULL, *last= NULL;
972         
973         if(ntree) {
974                 /* set current to the first selected node */
975                 for(current= ntree->nodes.last; current; current= current->prev)
976                         if(current->flag & NODE_SELECT)
977                                 break;
978                 
979                 /* set last to the first unselected node */
980                 for(last= ntree->nodes.last; last; last= last->prev)
981                         if((last->flag & NODE_SELECT)==0)
982                                 break;
983                 
984                 if(current==NULL)
985                         current= last;
986                 
987                 return NULL;
988         }
989         /* no nodes, or we are ready */
990         if(current==NULL)
991                 return NULL;
992         
993         /* now we walk the list backwards, but we always return current */
994         if(current->flag & NODE_SELECT) {
995                 bNode *node= current;
996                 
997                 /* find previous selected */
998                 current= current->prev;
999                 while(current && (current->flag & NODE_SELECT)==0)
1000                         current= current->prev;
1001                 
1002                 /* find first unselected */
1003                 if(current==NULL)
1004                         current= last;
1005                 
1006                 return node;
1007         }
1008         else {
1009                 bNode *node= current;
1010                 
1011                 /* find previous unselected */
1012                 current= current->prev;
1013                 while(current && (current->flag & NODE_SELECT))
1014                         current= current->prev;
1015                 
1016                 return node;
1017         }
1018         
1019         return NULL;
1020 }
1021
1022 /* is rct in visible part of node? */
1023 static bNode *visible_node(SpaceNode *snode, rctf *rct)
1024 {
1025         bNode *tnode;
1026         
1027         for(next_node(snode->edittree); (tnode=next_node(NULL));) {
1028                 if(BLI_isect_rctf(&tnode->totr, rct, NULL))
1029                         break;
1030         }
1031         return tnode;
1032 }
1033
1034 void snode_home(ScrArea *sa, ARegion *ar, SpaceNode* snode)
1035 {
1036         bNode *node;
1037         rctf *cur, *tot;
1038         float oldwidth, oldheight, width, height;
1039         int first= 1;
1040         
1041         cur= &ar->v2d.cur;
1042         tot= &ar->v2d.tot;
1043         
1044         oldwidth= cur->xmax - cur->xmin;
1045         oldheight= cur->ymax - cur->ymin;
1046         
1047         cur->xmin= cur->ymin= 0.0f;
1048         cur->xmax=ar->winx;
1049         cur->xmax= ar->winy;
1050         
1051         if(snode->edittree) {
1052                 for(node= snode->edittree->nodes.first; node; node= node->next) {
1053                         if(first) {
1054                                 first= 0;
1055                                 ar->v2d.cur= node->totr;
1056                         }
1057                         else {
1058                                 BLI_union_rctf(cur, &node->totr);
1059                         }
1060                 }
1061         }
1062         
1063         snode->xof= 0;
1064         snode->yof= 0;
1065         width= cur->xmax - cur->xmin;
1066         height= cur->ymax- cur->ymin;
1067         if(width > height) {
1068                 float newheight;
1069                 newheight= oldheight * width/oldwidth;
1070                 cur->ymin= cur->ymin - newheight/4;
1071                 cur->ymax= cur->ymin + newheight;
1072         }
1073         else {
1074                 float newwidth;
1075                 newwidth= oldwidth * height/oldheight;
1076                 cur->xmin= cur->xmin - newwidth/4;
1077                 cur->xmax= cur->xmin + newwidth;
1078         }
1079         
1080         ar->v2d.tot= ar->v2d.cur;
1081         UI_view2d_curRect_validate(&ar->v2d);
1082 }
1083
1084 #if 0
1085 static void snode_bg_viewmove(SpaceNode *snode)
1086 {
1087         ScrArea *sa;
1088         Image *ima;
1089         ImBuf *ibuf;
1090         Window *win;
1091         short mval[2], mvalo[2];
1092         short rectx, recty, xmin, xmax, ymin, ymax, pad;
1093         int oldcursor;
1094         
1095         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1096         ibuf= BKE_image_get_ibuf(ima, NULL);
1097         
1098         sa = snode->area;
1099         
1100         if(ibuf) {
1101                 rectx = ibuf->x;
1102                 recty = ibuf->y;
1103         } else {
1104                 rectx = recty = 1;
1105         }
1106         
1107         pad = 10;
1108         xmin = -(sa->winx/2) - rectx/2 + pad;
1109         xmax = sa->winx/2 + rectx/2 - pad;
1110         ymin = -(sa->winy/2) - recty/2 + pad;
1111         ymax = sa->winy/2 + recty/2 - pad;
1112         
1113         getmouseco_sc(mvalo);
1114         
1115         /* store the old cursor to temporarily change it */
1116         oldcursor=get_cursor();
1117         win=winlay_get_active_window();
1118         
1119         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
1120         
1121         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
1122                 
1123                 getmouseco_sc(mval);
1124                 
1125                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
1126                         
1127                         snode->xof -= (mvalo[0]-mval[0]);
1128                         snode->yof -= (mvalo[1]-mval[1]);
1129                         
1130                         /* prevent dragging image outside of the window and losing it! */
1131                         CLAMP(snode->xof, xmin, xmax);
1132                         CLAMP(snode->yof, ymin, ymax);
1133                         
1134                         mvalo[0]= mval[0];
1135                         mvalo[1]= mval[1];
1136                         
1137                         scrarea_do_windraw(curarea);
1138                         screen_swapbuffers();
1139                 }
1140                 else BIF_wait_for_statechange();
1141         }
1142         
1143         window_set_cursor(win, oldcursor);
1144 }
1145 #endif
1146
1147 /* ********************** size widget operator ******************** */
1148
1149 typedef struct NodeSizeWidget {
1150         float mxstart;
1151         float oldwidth;
1152 } NodeSizeWidget;
1153
1154 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1155 {
1156         SpaceNode *snode= CTX_wm_space_node(C);
1157         ARegion *ar= CTX_wm_region(C);
1158         bNode *node= editnode_get_active(snode->edittree);
1159         NodeSizeWidget *nsw= op->customdata;
1160         float mx, my;
1161         
1162         switch (event->type) {
1163                 case MOUSEMOVE:
1164                         
1165                         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1166                                                                          &mx, &my);
1167                         
1168                         if(node->flag & NODE_HIDDEN) {
1169                                 node->miniwidth= nsw->oldwidth + mx - nsw->mxstart;
1170                                 CLAMP(node->miniwidth, 0.0f, 100.0f);
1171                         }
1172                         else {
1173                                 node->width= nsw->oldwidth + mx - nsw->mxstart;
1174                                 CLAMP(node->width, node->typeinfo->minwidth, node->typeinfo->maxwidth);
1175                         }
1176                                 
1177                         ED_region_tag_redraw(ar);
1178
1179                         break;
1180                         
1181                 case LEFTMOUSE:
1182                 case MIDDLEMOUSE:
1183                 case RIGHTMOUSE:
1184                         
1185                         MEM_freeN(nsw);
1186                         op->customdata= NULL;
1187                         
1188                         return OPERATOR_FINISHED;
1189         }
1190         
1191         return OPERATOR_RUNNING_MODAL;
1192 }
1193
1194 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1195 {
1196         SpaceNode *snode= CTX_wm_space_node(C);
1197         ARegion *ar= CTX_wm_region(C);
1198         bNode *node= editnode_get_active(snode->edittree);
1199         
1200         if(node) {
1201                 rctf totr;
1202                 
1203                 UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1204                                                                  &snode->mx, &snode->my);
1205                 totr= node->totr;
1206                 totr.xmin= totr.xmax-10.0f;
1207                 totr.ymax= totr.ymin+10.0f;
1208                 
1209                 if(BLI_in_rctf(&totr, snode->mx, snode->my)) {
1210                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1211                         
1212                         op->customdata= nsw;
1213                         nsw->mxstart= snode->mx;
1214                         
1215                         /* store old */
1216                         if(node->flag & NODE_HIDDEN)
1217                                 nsw->oldwidth= node->miniwidth;
1218                         else
1219                                 nsw->oldwidth= node->width;
1220                         
1221                         /* add modal handler */
1222                         WM_event_add_modal_handler(C, op);
1223
1224                         return OPERATOR_RUNNING_MODAL;
1225                 }
1226         }
1227         return OPERATOR_PASS_THROUGH;
1228 }
1229
1230 void NODE_OT_resize(wmOperatorType *ot)
1231 {
1232         /* identifiers */
1233         ot->name= "Resize Node";
1234         ot->idname= "NODE_OT_resize";
1235         
1236         /* api callbacks */
1237         ot->invoke= node_resize_invoke;
1238         ot->modal= node_resize_modal;
1239         ot->poll= ED_operator_node_active;
1240         
1241         /* flags */
1242         ot->flag= OPTYPE_BLOCKING;
1243 }
1244
1245
1246 #if 0
1247
1248 /* ******************** rename ******************* */
1249
1250 void node_rename(SpaceNode *snode)
1251 {
1252         bNode *node, *rename_node;
1253         short found_node= 0;
1254
1255         /* check if a node is selected */
1256         for(node= snode->edittree->nodes.first; node; node= node->next) {
1257                 if(node->flag & SELECT) {
1258                         found_node= 1;
1259                         break;
1260                 }
1261         }
1262
1263         if(found_node) {
1264                 rename_node= nodeGetActive(snode->edittree);
1265                 node_rename_but((char *)rename_node->username);
1266         
1267                 // allqueue(REDRAWNODE, 1);
1268         }
1269 }
1270
1271 /* ********************** select ******************** */
1272
1273 /* used in buttons to check context, also checks for edited groups */
1274 bNode *editnode_get_active_idnode(bNodeTree *ntree, short id_code)
1275 {
1276         return nodeGetActiveID(ntree, id_code);
1277 }
1278
1279 /* used in buttons to check context, also checks for edited groups */
1280 Material *editnode_get_active_material(Material *ma)
1281 {
1282         if(ma && ma->use_nodes && ma->nodetree) {
1283                 bNode *node= editnode_get_active_idnode(ma->nodetree, ID_MA);
1284                 if(node)
1285                         return (Material *)node->id;
1286                 else
1287                         return NULL;
1288         }
1289         return ma;
1290 }
1291 #endif /* 0 */
1292
1293
1294 /* no undo here! */
1295 void node_deselectall(SpaceNode *snode)
1296 {
1297         bNode *node;
1298         
1299         for(node= snode->edittree->nodes.first; node; node= node->next)
1300                 node->flag &= ~SELECT;
1301 }
1302
1303 int node_has_hidden_sockets(bNode *node)
1304 {
1305         bNodeSocket *sock;
1306         
1307         for(sock= node->inputs.first; sock; sock= sock->next)
1308                 if(sock->flag & SOCK_HIDDEN)
1309                         return 1;
1310         for(sock= node->outputs.first; sock; sock= sock->next)
1311                 if(sock->flag & SOCK_HIDDEN)
1312                         return 1;
1313         return 0;
1314 }
1315
1316
1317 static void node_hide_unhide_sockets(SpaceNode *snode, bNode *node)
1318 {
1319         bNodeSocket *sock;
1320         
1321         /* unhide all */
1322         if( node_has_hidden_sockets(node) ) {
1323                 for(sock= node->inputs.first; sock; sock= sock->next)
1324                         sock->flag &= ~SOCK_HIDDEN;
1325                 for(sock= node->outputs.first; sock; sock= sock->next)
1326                         sock->flag &= ~SOCK_HIDDEN;
1327         }
1328         else {
1329                 bNode *gnode= node_tree_get_editgroup(snode->nodetree);
1330                 
1331                 /* hiding inside group should not break links in other group users */
1332                 if(gnode) {
1333                         nodeGroupSocketUseFlags((bNodeTree *)gnode->id);
1334                         for(sock= node->inputs.first; sock; sock= sock->next)
1335                                 if(!(sock->flag & SOCK_IN_USE))
1336                                         if(sock->link==NULL)
1337                                                 sock->flag |= SOCK_HIDDEN;
1338                         for(sock= node->outputs.first; sock; sock= sock->next)
1339                                 if(!(sock->flag & SOCK_IN_USE))
1340                                         if(nodeCountSocketLinks(snode->edittree, sock)==0)
1341                                                 sock->flag |= SOCK_HIDDEN;
1342                 }
1343                 else {
1344                         /* hide unused sockets */
1345                         for(sock= node->inputs.first; sock; sock= sock->next) {
1346                                 if(sock->link==NULL)
1347                                         sock->flag |= SOCK_HIDDEN;
1348                         }
1349                         for(sock= node->outputs.first; sock; sock= sock->next) {
1350                                 if(nodeCountSocketLinks(snode->edittree, sock)==0)
1351                                         sock->flag |= SOCK_HIDDEN;
1352                         }
1353                 }
1354         }
1355
1356         // allqueue(REDRAWNODE, 1);
1357         node_tree_verify_groups(snode->nodetree);
1358
1359 }
1360
1361 /*static*/ int do_header_node(SpaceNode *snode, bNode *node, float mx, float my)
1362 {
1363         rctf totr= node->totr;
1364         
1365         totr.ymin= totr.ymax-20.0f;
1366         
1367         totr.xmax= totr.xmin+15.0f;
1368         if(BLI_in_rctf(&totr, mx, my)) {
1369                 node->flag |= NODE_HIDDEN;
1370                 // allqueue(REDRAWNODE, 0);
1371                 return 1;
1372         }       
1373         
1374         totr.xmax= node->totr.xmax;
1375         totr.xmin= totr.xmax-18.0f;
1376         if(node->typeinfo->flag & NODE_PREVIEW) {
1377                 if(BLI_in_rctf(&totr, mx, my)) {
1378                         node->flag ^= NODE_PREVIEW;
1379                         // allqueue(REDRAWNODE, 0);
1380                         return 1;
1381                 }
1382                 totr.xmin-=18.0f;
1383         }
1384         if(node->type == NODE_GROUP) {
1385                 if(BLI_in_rctf(&totr, mx, my)) {
1386                         snode_make_group_editable(snode, node);
1387                         return 1;
1388                 }
1389                 totr.xmin-=18.0f;
1390         }
1391         if(node->typeinfo->flag & NODE_OPTIONS) {
1392                 if(BLI_in_rctf(&totr, mx, my)) {
1393                         node->flag ^= NODE_OPTIONS;
1394                         // allqueue(REDRAWNODE, 0);
1395                         return 1;
1396                 }
1397                 totr.xmin-=18.0f;
1398         }
1399         /* hide unused sockets */
1400         if(BLI_in_rctf(&totr, mx, my)) {
1401                 node_hide_unhide_sockets(snode, node);
1402         }
1403         
1404         
1405         totr= node->totr;
1406         totr.xmin= totr.xmax-10.0f;
1407         totr.ymax= totr.ymin+10.0f;
1408         if(BLI_in_rctf(&totr, mx, my)) {
1409 //              scale_node(snode, node);
1410                 return 1;
1411         }
1412         return 0;
1413 }
1414
1415 /*static*/ int do_header_hidden_node(SpaceNode *snode, bNode *node, float mx, float my)
1416 {
1417         rctf totr= node->totr;
1418         
1419         totr.xmax= totr.xmin+15.0f;
1420         if(BLI_in_rctf(&totr, mx, my)) {
1421                 node->flag &= ~NODE_HIDDEN;
1422                 // allqueue(REDRAWNODE, 0);
1423                 return 1;
1424         }       
1425         
1426         totr.xmax= node->totr.xmax;
1427         totr.xmin= node->totr.xmax-15.0f;
1428         if(BLI_in_rctf(&totr, mx, my)) {
1429 //              scale_node(snode, node);
1430                 return 1;
1431         }
1432         return 0;
1433 }
1434
1435 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1436 {
1437         bNode *node;
1438
1439         /* context check */
1440         if(tonode==NULL || tonode->outputs.first==NULL)
1441                 return;
1442         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1443                 return;
1444         
1445         /* get viewer */
1446         for(node= snode->edittree->nodes.first; node; node= node->next)
1447                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1448                         if(node->flag & NODE_DO_OUTPUT)
1449                                 break;
1450                 
1451         if(node) {
1452                 bNodeLink *link;
1453                 
1454                 /* get link to viewer */
1455                 for(link= snode->edittree->links.first; link; link= link->next)
1456                         if(link->tonode==node)
1457                                 break;
1458
1459                 if(link) {
1460                         link->fromnode= tonode;
1461                         link->fromsock= tonode->outputs.first;
1462                         NodeTagChanged(snode->edittree, node);
1463                         
1464 // XXX                  snode_handle_recalc(snode);
1465                 }
1466         }
1467 }
1468
1469
1470 void node_active_link_viewer(SpaceNode *snode)
1471 {
1472         bNode *node= editnode_get_active(snode->edittree);
1473         if(node)
1474                 node_link_viewer(snode, node);
1475 }
1476
1477 /* return 0, nothing done */
1478 /*static*/ int node_mouse_groupheader(SpaceNode *snode)
1479 {
1480         bNode *gnode;
1481         float mx=0, my=0;
1482 // XXX  short mval[2];
1483         
1484         gnode= node_tree_get_editgroup(snode->nodetree);
1485         if(gnode==NULL) return 0;
1486         
1487 // XXX  getmouseco_areawin(mval);
1488 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1489         
1490         /* click in header or outside? */
1491         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1492                 rctf rect= gnode->totr;
1493                 
1494                 rect.ymax += NODE_DY;
1495                 if(BLI_in_rctf(&rect, mx, my)==0)
1496                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1497 //              else
1498 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1499                 
1500                 return 1;
1501         }
1502         return 0;
1503 }
1504
1505 /* checks snode->mouse position, and returns found node/socket */
1506 /* type is SOCK_IN and/or SOCK_OUT */
1507 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1508 {
1509         bNode *node;
1510         bNodeSocket *sock;
1511         rctf rect;
1512         
1513         /* check if we click in a socket */
1514         for(node= snode->edittree->nodes.first; node; node= node->next) {
1515                 
1516                 rect.xmin = snode->mx - NODE_SOCKSIZE+3;
1517                 rect.ymin = snode->my - NODE_SOCKSIZE+3;
1518                 rect.xmax = rect.xmin + 2*NODE_SOCKSIZE+6;
1519                 rect.ymax = rect.ymin + 2*NODE_SOCKSIZE+6;
1520                 
1521                 if (!(node->flag & NODE_HIDDEN)) {
1522                         /* extra padding inside and out - allow dragging on the text areas too */
1523                         if (in_out == SOCK_IN) {
1524                                 rect.xmax += NODE_SOCKSIZE;
1525                                 rect.xmin -= NODE_SOCKSIZE*4;
1526                         } else if (in_out == SOCK_OUT) {
1527                                 rect.xmax += NODE_SOCKSIZE*4;
1528                                 rect.xmin -= NODE_SOCKSIZE;
1529                         }
1530                 }
1531                 
1532                 if(in_out & SOCK_IN) {
1533                         for(sock= node->inputs.first; sock; sock= sock->next) {
1534                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1535                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1536                                                 if(node == visible_node(snode, &rect)) {
1537                                                         *nodep= node;
1538                                                         *sockp= sock;
1539                                                         return 1;
1540                                                 }
1541                                         }
1542                                 }
1543                         }
1544                 }
1545                 if(in_out & SOCK_OUT) {
1546                         for(sock= node->outputs.first; sock; sock= sock->next) {
1547                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1548                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1549                                                 if(node == visible_node(snode, &rect)) {
1550                                                         *nodep= node;
1551                                                         *sockp= sock;
1552                                                         return 1;
1553                                                 }
1554                                         }
1555                                 }
1556                         }
1557                 }
1558         }
1559         return 0;
1560 }
1561
1562 static int node_socket_hilights(SpaceNode *snode, int in_out)
1563 {
1564         bNode *node;
1565         bNodeSocket *sock, *tsock, *socksel= NULL;
1566         short redraw= 0;
1567         
1568         if(snode->edittree==NULL) return 0;
1569         
1570         /* deselect socks */
1571         for(node= snode->edittree->nodes.first; node; node= node->next) {
1572                 for(sock= node->inputs.first; sock; sock= sock->next) {
1573                         if(sock->flag & SELECT) {
1574                                 sock->flag &= ~SELECT;
1575                                 redraw++;
1576                                 socksel= sock;
1577                         }
1578                 }
1579                 for(sock= node->outputs.first; sock; sock= sock->next) {
1580                         if(sock->flag & SELECT) {
1581                                 sock->flag &= ~SELECT;
1582                                 redraw++;
1583                                 socksel= sock;
1584                         }
1585                 }
1586         }
1587         
1588         // XXX mousepos should be set here!
1589         
1590         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
1591                 tsock->flag |= SELECT;
1592                 if(redraw==1 && tsock==socksel) redraw= 0;
1593                 else redraw= 1;
1594         }
1595         
1596         return redraw;
1597 }
1598
1599 /* ****************** Add *********************** */
1600
1601 void snode_autoconnect(SpaceNode *snode, bNode *node_to, int flag)
1602 {
1603         bNodeSocket *sock, *sockfrom[8];
1604         bNode *node, *nodefrom[8];
1605         int totsock= 0, socktype=0;
1606
1607         if(node_to==NULL || node_to->inputs.first==NULL)
1608                 return;
1609         
1610         /* no inputs for node allowed (code it) */
1611
1612         /* connect first 1 socket type now */
1613         for(sock= node_to->inputs.first; sock; sock= sock->next)
1614                 if(socktype<sock->type)
1615                         socktype= sock->type;
1616
1617         
1618         /* find potential sockets, max 8 should work */
1619         for(node= snode->edittree->nodes.first; node; node= node->next) {
1620                 if((node->flag & flag) && node!=node_to) {
1621                         for(sock= node->outputs.first; sock; sock= sock->next) {
1622                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1623                                         sockfrom[totsock]= sock;
1624                                         nodefrom[totsock]= node;
1625                                         totsock++;
1626                                         if(totsock>7)
1627                                                 break;
1628                                 }
1629                         }
1630                 }
1631                 if(totsock>7)
1632                         break;
1633         }
1634
1635         /* now just get matching socket types and create links */
1636         for(sock= node_to->inputs.first; sock; sock= sock->next) {
1637                 int a;
1638                 
1639                 for(a=0; a<totsock; a++) {
1640                         if(sockfrom[a]) {
1641                                 if(sock->type==sockfrom[a]->type && sock->type==socktype) {
1642                                         nodeAddLink(snode->edittree, nodefrom[a], sockfrom[a], node_to, sock);
1643                                         sockfrom[a]= NULL;
1644                                         break;
1645                                 }
1646                         }
1647                 }
1648         }
1649         
1650         ntreeSolveOrder(snode->edittree);
1651 }
1652
1653
1654 /* can be called from menus too, but they should do own undopush and redraws */
1655 bNode *node_add_node(SpaceNode *snode, Scene *scene, int type, float locx, float locy)
1656 {
1657         bNode *node= NULL, *gnode;
1658         
1659         node_deselectall(snode);
1660         
1661         if(type>=NODE_DYNAMIC_MENU) {
1662                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1663         }
1664         else if(type>=NODE_GROUP_MENU) {
1665                 if(snode->edittree!=snode->nodetree) {
1666                         // XXX error("Can not add a Group in a Group");
1667                         return NULL;
1668                 }
1669                 else {
1670                         bNodeTree *ngroup= BLI_findlink(&G.main->nodetree, type-NODE_GROUP_MENU);
1671                         if(ngroup)
1672                                 node= nodeAddNodeType(snode->edittree, NODE_GROUP, ngroup, NULL);
1673                 }
1674         }
1675         else
1676                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1677         
1678         /* generics */
1679         if(node) {
1680                 node->locx= locx;
1681                 node->locy= locy + 60.0f;               // arbitrary.. so its visible
1682                 node->flag |= SELECT;
1683                 
1684                 gnode= node_tree_get_editgroup(snode->nodetree);
1685                 if(gnode) {
1686                         node->locx -= gnode->locx;
1687                         node->locy -= gnode->locy;
1688                 }
1689
1690                 node_tree_verify_groups(snode->nodetree);
1691                 node_set_active(snode, node);
1692                 
1693                 if(snode->nodetree->type==NTREE_COMPOSIT) {
1694                         if(ELEM(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE))
1695                                 node->id = &scene->id;
1696                         
1697                         ntreeCompositForceHidden(snode->edittree, scene);
1698                 }
1699                         
1700                 if(node->id)
1701                         id_us_plus(node->id);
1702                         
1703                 NodeTagChanged(snode->edittree, node);
1704         }
1705         
1706         if(snode->nodetree->type==NTREE_TEXTURE) {
1707                 ntreeTexCheckCyclics(snode->edittree);
1708         }
1709         
1710         return node;
1711 }
1712
1713 #if 0
1714
1715 void node_mute(SpaceNode *snode)
1716 {
1717         bNode *node;
1718
1719         /* no disabling inside of groups */
1720         if(node_tree_get_editgroup(snode->nodetree))
1721                 return;
1722         
1723         for(node= snode->edittree->nodes.first; node; node= node->next) {
1724                 if(node->flag & SELECT) {
1725                         if(node->inputs.first && node->outputs.first) {
1726                                 if(node->flag & NODE_MUTED)
1727                                         node->flag &= ~NODE_MUTED;
1728                                 else
1729                                         node->flag |= NODE_MUTED;
1730                         }
1731                 }
1732         }
1733         
1734
1735 }
1736
1737 #endif
1738
1739 int node_duplicate_exec(bContext *C, wmOperator *op)
1740 {
1741         SpaceNode *snode= CTX_wm_space_node(C);
1742         
1743         ntreeCopyTree(snode->edittree, 1);      /* 1 == internally selected nodes */
1744         
1745         ntreeSolveOrder(snode->edittree);
1746         node_tree_verify_groups(snode->nodetree);
1747         snode_handle_recalc(C, snode);
1748
1749         return OPERATOR_FINISHED;
1750 }
1751
1752 static int node_duplicate_invoke(bContext *C, wmOperator *op, wmEvent *event)
1753 {
1754         node_duplicate_exec(C, op);
1755         
1756         RNA_int_set(op->ptr, "mode", TFM_TRANSLATION);
1757         WM_operator_name_call(C, "TFM_OT_transform", WM_OP_INVOKE_REGION_WIN, op->ptr);
1758         
1759         return OPERATOR_FINISHED;
1760 }
1761
1762 void NODE_OT_duplicate(wmOperatorType *ot)
1763 {
1764         
1765         /* identifiers */
1766         ot->name= "Duplicate Nodes";
1767         ot->description = "Duplicate the nodes.";
1768         ot->idname= "NODE_OT_duplicate";
1769         
1770         /* api callbacks */
1771         ot->invoke= node_duplicate_invoke;
1772         ot->exec= node_duplicate_exec;
1773         
1774         ot->poll= ED_operator_node_active;
1775         
1776         /* flags */
1777         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1778         
1779         /* to give to transform */
1780         RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
1781 }
1782
1783 #if 0
1784
1785 static void node_insert_convertor(SpaceNode *snode, bNodeLink *link)
1786 {
1787         bNode *newnode= NULL;
1788         
1789         if(link->fromsock->type==SOCK_RGBA && link->tosock->type==SOCK_VALUE) {
1790                 if(snode->edittree->type==NTREE_SHADER)
1791                         newnode= node_add_node(snode, SH_NODE_RGBTOBW, 0.0f, 0.0f);
1792                 else if(snode->edittree->type==NTREE_COMPOSIT)
1793                         newnode= node_add_node(snode, CMP_NODE_RGBTOBW, 0.0f, 0.0f);
1794                 else
1795                         newnode= NULL;
1796         }
1797         else if(link->fromsock->type==SOCK_VALUE && link->tosock->type==SOCK_RGBA) {
1798                 if(snode->edittree->type==NTREE_SHADER)
1799                         newnode= node_add_node(snode, SH_NODE_VALTORGB, 0.0f, 0.0f);
1800                 else if(snode->edittree->type==NTREE_COMPOSIT)
1801                         newnode= node_add_node(snode, CMP_NODE_VALTORGB, 0.0f, 0.0f);
1802                 else
1803                         newnode= NULL;
1804         }
1805         
1806         if(newnode) {
1807                 /* dangerous assumption to use first in/out socks, but thats fine for now */
1808                 newnode->flag |= NODE_HIDDEN;
1809                 newnode->locx= 0.5f*(link->fromsock->locx + link->tosock->locx);
1810                 newnode->locy= 0.5f*(link->fromsock->locy + link->tosock->locy) + HIDDEN_RAD;
1811                 
1812                 nodeAddLink(snode->edittree, newnode, newnode->outputs.first, link->tonode, link->tosock);
1813                 link->tonode= newnode;
1814                 link->tosock= newnode->inputs.first;
1815         }
1816 }
1817
1818
1819 #endif /* 0 */
1820
1821 /* *************************** add link op ******************** */
1822
1823 /* temp data to pass on to modal */
1824 typedef struct NodeLinkDrag
1825 {
1826         bNode *node;
1827         bNodeSocket *sock;
1828         bNodeLink *link;
1829         int in_out;
1830 } NodeLinkDrag;
1831
1832 /*static*/ void reset_sel_socket(SpaceNode *snode, int in_out)
1833 {
1834         bNode *node;
1835         bNodeSocket *sock;
1836         
1837         for(node= snode->edittree->nodes.first; node; node= node->next) {
1838                 if(in_out & SOCK_IN) {
1839                         for(sock= node->inputs.first; sock; sock= sock->next)
1840                                 if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
1841                 }
1842                 if(in_out & SOCK_OUT) {
1843                         for(sock= node->outputs.first; sock; sock= sock->next)
1844                                 if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
1845                 }
1846         }
1847 }
1848
1849
1850 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
1851 {
1852         bNodeLink *tlink;
1853         bNodeSocket *sock;
1854         
1855         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
1856                 
1857                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
1858                         if(link!=tlink && tlink->tosock==link->tosock)
1859                                 break;
1860                 }
1861                 if(tlink) {
1862                         /* is there a free input socket with same type? */
1863                         for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
1864                                 if(sock->type==tlink->fromsock->type)
1865                                         if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
1866                                                 break;
1867                         }
1868                         if(sock) {
1869                                 tlink->tosock= sock;
1870                                 sock->flag &= ~SOCK_HIDDEN;
1871                         }
1872                         else {
1873                                 nodeRemLink(snode->edittree, tlink);
1874                         }
1875                 }
1876         }
1877 }
1878
1879 /* loop that adds a nodelink, called by function below  */
1880 /* in_out = starting socket */
1881 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
1882 {
1883         SpaceNode *snode= CTX_wm_space_node(C);
1884         ARegion *ar= CTX_wm_region(C);
1885         NodeLinkDrag *nldrag= op->customdata;
1886         bNode *tnode, *node;
1887         bNodeSocket *tsock= NULL, *sock;
1888         bNodeLink *link;
1889         int in_out;
1890
1891         in_out= nldrag->in_out;
1892         node= nldrag->node;
1893         sock= nldrag->sock;
1894         link= nldrag->link;
1895         
1896         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1897                                                          &snode->mx, &snode->my);
1898
1899         switch (event->type) {
1900                 case MOUSEMOVE:
1901                         
1902                         if(in_out==SOCK_OUT) {
1903                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
1904                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
1905                                                 if(tnode!=node  && link->tonode!=tnode && link->tosock!= tsock) {
1906                                                         link->tonode= tnode;
1907                                                         link->tosock= tsock;
1908                                                         ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
1909                                                 }
1910                                         }
1911                                 }
1912                                 else {
1913                                         link->tonode= NULL;
1914                                         link->tosock= NULL;
1915                                 }
1916                         }
1917                         else {
1918                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
1919                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
1920                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
1921                                                         if(tnode!=node && link->fromnode!=tnode && link->fromsock!= tsock) {
1922                                                                 link->fromnode= tnode;
1923                                                                 link->fromsock= tsock;
1924                                                                 ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
1925                                                         }
1926                                                 }
1927                                         }
1928                                 }
1929                                 else {
1930                                         link->fromnode= NULL;
1931                                         link->fromsock= NULL;
1932                                 }
1933                         }
1934                         /* hilight target sockets only */
1935                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
1936                         ED_region_tag_redraw(ar);
1937                         break;
1938                         
1939                 case LEFTMOUSE:
1940                 case RIGHTMOUSE:
1941                 case MIDDLEMOUSE:
1942         
1943                         /* remove link? */
1944                         if(link->tonode==NULL || link->fromnode==NULL) {
1945                                 nodeRemLink(snode->edittree, link);
1946                         }
1947                         else {
1948                                 /* send changed events for original tonode and new */
1949                                 if(link->tonode) 
1950                                         NodeTagChanged(snode->edittree, link->tonode);
1951                                 
1952                                 /* we might need to remove a link */
1953                                 if(in_out==SOCK_OUT) node_remove_extra_links(snode, link->tosock, link);
1954                         }
1955                         
1956                         ntreeSolveOrder(snode->edittree);
1957                         node_tree_verify_groups(snode->nodetree);
1958                         snode_handle_recalc(C, snode);
1959                         
1960                         MEM_freeN(op->customdata);
1961                         op->customdata= NULL;
1962                         
1963                         return OPERATOR_FINISHED;
1964         }
1965         
1966         return OPERATOR_RUNNING_MODAL;
1967 }
1968
1969 /* return 1 when socket clicked */
1970 static int node_link_init(SpaceNode *snode, NodeLinkDrag *nldrag)
1971 {
1972         bNodeLink *link;
1973         
1974         /* output indicated? */
1975         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
1976                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
1977                         return SOCK_OUT;
1978                 else {
1979                         /* find if we break a link */
1980                         for(link= snode->edittree->links.first; link; link= link->next) {
1981                                 if(link->fromsock==nldrag->sock)
1982                                         break;
1983                         }
1984                         if(link) {
1985                                 nldrag->node= link->tonode;
1986                                 nldrag->sock= link->tosock;
1987                                 nodeRemLink(snode->edittree, link);
1988                                 return SOCK_IN;
1989                         }
1990                 }
1991         }
1992         /* or an input? */
1993         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
1994                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
1995                         return SOCK_IN;
1996                 else {
1997                         /* find if we break a link */
1998                         for(link= snode->edittree->links.first; link; link= link->next) {
1999                                 if(link->tosock==nldrag->sock)
2000                                         break;
2001                         }
2002                         if(link) {
2003                                 /* send changed event to original tonode */
2004                                 if(link->tonode) 
2005                                         NodeTagChanged(snode->edittree, link->tonode);
2006                                 
2007                                 nldrag->node= link->fromnode;
2008                                 nldrag->sock= link->fromsock;
2009                                 nodeRemLink(snode->edittree, link);
2010                                 return SOCK_OUT;
2011                         }
2012                 }
2013         }
2014         
2015         return 0;
2016 }
2017
2018 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2019 {
2020         SpaceNode *snode= CTX_wm_space_node(C);
2021         ARegion *ar= CTX_wm_region(C);
2022         NodeLinkDrag *nldrag= MEM_callocN(sizeof(NodeLinkDrag), "drag link op customdata");
2023         
2024         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
2025                                                          &snode->mx, &snode->my);
2026
2027         nldrag->in_out= node_link_init(snode, nldrag);
2028                 
2029         if(nldrag->in_out) {
2030                 op->customdata= nldrag;
2031                 
2032                 /* we make a temporal link */
2033                 if(nldrag->in_out==SOCK_OUT)
2034                         nldrag->link= nodeAddLink(snode->edittree, nldrag->node, nldrag->sock, NULL, NULL);
2035                 else
2036                         nldrag->link= nodeAddLink(snode->edittree, NULL, NULL, nldrag->node, nldrag->sock);
2037                 
2038                 /* add modal handler */
2039                 WM_event_add_modal_handler(C, op);
2040                 
2041                 return OPERATOR_RUNNING_MODAL;
2042         }
2043         else {
2044                 MEM_freeN(nldrag);
2045                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2046         }
2047 }
2048
2049 void NODE_OT_link(wmOperatorType *ot)
2050 {
2051         /* identifiers */
2052         ot->name= "Link Nodes";
2053         ot->idname= "NODE_OT_link";
2054         
2055         /* api callbacks */
2056         ot->invoke= node_link_invoke;
2057         ot->modal= node_link_modal;
2058 //      ot->exec= node_link_exec;
2059         ot->poll= ED_operator_node_active;
2060         
2061         /* flags */
2062         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2063 }
2064
2065
2066 void node_hide(SpaceNode *snode)
2067 {
2068         bNode *node;
2069         int nothidden=0, ishidden=0;
2070         
2071         for(node= snode->edittree->nodes.first; node; node= node->next) {
2072                 if(node->flag & SELECT) {
2073                         if(node->flag & NODE_HIDDEN)
2074                                 ishidden++;
2075                         else
2076                                 nothidden++;
2077                 }
2078         }
2079         for(node= snode->edittree->nodes.first; node; node= node->next) {
2080                 if(node->flag & SELECT) {
2081                         if( (ishidden && nothidden) || ishidden==0)
2082                                 node->flag |= NODE_HIDDEN;
2083                         else 
2084                                 node->flag &= ~NODE_HIDDEN;
2085                 }
2086         }
2087 }
2088
2089 #if 0
2090
2091 void node_insert_key(SpaceNode *snode)
2092 {
2093         bNode *node= editnode_get_active(snode->edittree);
2094         
2095         if(node == NULL)
2096                 return;
2097         
2098         if(node->type==CMP_NODE_TIME) {
2099                 if(node->custom1<node->custom2) {
2100
2101                         CurveMapping *cumap= node->storage;
2102                         float fval, curval;
2103                 
2104                         curval= (float)(CFRA - node->custom1)/(float)(node->custom2-node->custom1);
2105                         fval= curvemapping_evaluateF(cumap, 0, curval);
2106                         
2107                         if(fbutton(&fval, 0.0f, 1.0f, 10, 10, "Insert Value")) {
2108                                 curvemap_insert(cumap->cm, curval, fval);
2109
2110                         }
2111                 }
2112         }
2113 }
2114
2115 /* makes a link between selected output and input sockets */
2116 void node_make_link(SpaceNode *snode)
2117 {
2118         bNode *fromnode, *tonode;
2119         bNodeLink *link;
2120         bNodeSocket *outsock= snode->edittree->selout;
2121         bNodeSocket *insock= snode->edittree->selin;
2122
2123         if(!insock || !outsock) return;
2124         if(nodeFindLink(snode->edittree, outsock, insock)) return;
2125
2126         if(nodeFindNode(snode->edittree, outsock, &fromnode, NULL) &&
2127                 nodeFindNode(snode->edittree, insock, &tonode, NULL)) {
2128                 link= nodeAddLink(snode->edittree, fromnode, outsock, tonode, insock);
2129                 NodeTagChanged(snode->edittree, tonode);
2130                 node_remove_extra_links(snode, insock, link);
2131         }
2132         else return;
2133
2134         ntreeSolveOrder(snode->edittree);
2135         node_tree_verify_groups(snode->nodetree);
2136         // XXX                  snode_handle_recalc(snode);
2137
2138 }
2139 #endif
2140
2141 /* ********************** Cut Link operator ***************** */
2142
2143 #define LINK_RESOL 12
2144 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2145 {
2146         float coord_array[LINK_RESOL+1][2];
2147         int i, b;
2148         
2149         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2150
2151                 for(i=0; i<tot-1; i++)
2152                         for(b=0; b<LINK_RESOL-1; b++)
2153                                 if(IsectLL2Df(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2154                                         return 1;
2155         }
2156         return 0;
2157 }
2158
2159 static int cut_links_exec(bContext *C, wmOperator *op)
2160 {
2161         SpaceNode *snode= CTX_wm_space_node(C);
2162         ARegion *ar= CTX_wm_region(C);
2163         float mcoords[256][2];
2164         int i= 0;
2165         
2166         RNA_BEGIN(op->ptr, itemptr, "path") {
2167                 float loc[2];
2168                 
2169                 RNA_float_get_array(&itemptr, "loc", loc);
2170                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2171                                                                  &mcoords[i][0], &mcoords[i][1]);
2172                 i++;
2173                 if(i>= 256) break;
2174         }
2175         RNA_END;
2176         
2177         if(i>1) {
2178                 bNodeLink *link, *next;
2179                 
2180                 for(link= snode->edittree->links.first; link; link= next) {
2181                         next= link->next;
2182                         
2183                         if(cut_links_intersect(link, mcoords, i)) {
2184                                 NodeTagChanged(snode->edittree, link->tonode);
2185                                 nodeRemLink(snode->edittree, link);
2186                         }
2187                 }
2188
2189                 ntreeSolveOrder(snode->edittree);
2190                 node_tree_verify_groups(snode->nodetree);
2191                 snode_handle_recalc(C, snode);
2192                 
2193                 return OPERATOR_FINISHED;
2194         }
2195         
2196         return OPERATOR_PASS_THROUGH;;
2197 }
2198
2199 void NODE_OT_links_cut(wmOperatorType *ot)
2200 {
2201         PropertyRNA *prop;
2202         
2203         ot->name= "Cut links";
2204         ot->idname= "NODE_OT_links_cut";
2205         
2206         ot->invoke= WM_gesture_lines_invoke;
2207         ot->modal= WM_gesture_lines_modal;
2208         ot->exec= cut_links_exec;
2209         
2210         ot->poll= ED_operator_node_active;
2211         
2212         /* flags */
2213         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2214         
2215         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2216         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2217         /* internal */
2218         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2219 }
2220
2221 /* ******************************** */
2222
2223 /* goes over all scenes, reads render layerss */
2224 void node_read_renderlayers(SpaceNode *snode)
2225 {
2226         Scene *curscene= NULL; // XXX
2227         Scene *scene;
2228         bNode *node;
2229
2230         /* first tag scenes unread */
2231         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2232                 scene->id.flag |= LIB_DOIT;
2233
2234         for(node= snode->edittree->nodes.first; node; node= node->next) {
2235                 if(node->type==CMP_NODE_R_LAYERS) {
2236                         ID *id= node->id;
2237                         if(id->flag & LIB_DOIT) {
2238                                 RE_ReadRenderResult(curscene, (Scene *)id);
2239                                 ntreeCompositTagRender((Scene *)id);
2240                                 id->flag &= ~LIB_DOIT;
2241                         }
2242                 }
2243         }
2244         
2245         // XXX                  snode_handle_recalc(snode);
2246 }
2247
2248 void node_read_fullsamplelayers(SpaceNode *snode)
2249 {
2250         Scene *curscene= NULL; // XXX
2251         Render *re= RE_NewRender(curscene->id.name);
2252
2253         WM_cursor_wait(1);
2254
2255         //BIF_init_render_callbacks(re, 1);
2256         RE_MergeFullSample(re, curscene, snode->nodetree);
2257         //BIF_end_render_callbacks();
2258         
2259         // allqueue(REDRAWNODE, 1);
2260         // allqueue(REDRAWIMAGE, 1);
2261         
2262         WM_cursor_wait(0);
2263 }
2264
2265 void imagepaint_composite_tags(bNodeTree *ntree, Image *image, ImageUser *iuser)
2266 {
2267         bNode *node;
2268         
2269         if(ntree==NULL)
2270                 return;
2271         
2272         /* search for renderresults */
2273         if(image->type==IMA_TYPE_R_RESULT) {
2274                 for(node= ntree->nodes.first; node; node= node->next) {
2275                         if(node->type==CMP_NODE_R_LAYERS && node->id==NULL) {
2276                                 /* imageuser comes from ImageWin, so indexes are offset 1 */
2277                                 if(node->custom1==iuser->layer-1)
2278                                         NodeTagChanged(ntree, node);
2279                         }
2280                 }
2281         }
2282         else {
2283                 for(node= ntree->nodes.first; node; node= node->next) {
2284                         if(node->id== &image->id)
2285                                 NodeTagChanged(ntree, node);
2286                 }
2287         }
2288 }
2289
2290 /* ****************** Make Group operator ******************* */
2291
2292 static int node_group_make_exec(bContext *C, wmOperator *op)
2293 {
2294         SpaceNode *snode = CTX_wm_space_node(C);
2295         bNode *gnode;
2296         
2297         if(snode->edittree!=snode->nodetree) {
2298                 BKE_report(op->reports, RPT_ERROR, "Can not add a new Group in a Group");
2299                 return OPERATOR_CANCELLED;
2300         }
2301         
2302         /* for time being... is too complex to handle */
2303         if(snode->treetype==NTREE_COMPOSIT) {
2304                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
2305                         if(gnode->flag & SELECT)
2306                                 if(gnode->type==CMP_NODE_R_LAYERS)
2307                                         break;
2308                 }
2309
2310                 if(gnode) {
2311                         BKE_report(op->reports, RPT_ERROR, "Can not add RenderLayer in a Group");
2312                         return OPERATOR_CANCELLED;
2313                 }
2314         }
2315         
2316         gnode= nodeMakeGroupFromSelected(snode->nodetree);
2317         if(gnode==NULL) {
2318                 BKE_report(op->reports, RPT_ERROR, "Can not make Group");
2319                 return OPERATOR_CANCELLED;
2320         }
2321         else {
2322                 nodeSetActive(snode->nodetree, gnode);
2323                 ntreeSolveOrder(snode->nodetree);
2324         }
2325
2326         return OPERATOR_FINISHED;
2327 }
2328
2329 void NODE_OT_group_make(wmOperatorType *ot)
2330 {
2331         /* identifiers */
2332         ot->name = "Group";
2333         ot->description = "Make group from selected nodes.";
2334         ot->idname = "NODE_OT_group_make";
2335         
2336         /* api callbacks */
2337         ot->exec = node_group_make_exec;
2338         ot->poll = ED_operator_node_active;
2339         
2340         /* flags */
2341         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2342 }
2343
2344 #if 0
2345
2346 /* ******************** main event loop ****************** */
2347
2348 void winqreadnodespace(ScrArea *sa, void *spacedata, BWinEvent *evt)
2349 {
2350         SpaceNode *snode= spacedata;
2351         bNode *actnode;
2352         bNodeSocket *actsock;
2353         unsigned short event= evt->event;
2354         short val= evt->val, doredraw=0, fromlib= 0;
2355         
2356         if(sa->win==0) return;
2357         
2358         if(snode->nodetree==NULL) {
2359                 /* no other events should be handled, but floating panels still should get handled */
2360                 uiDoBlocks(&curarea->uiblocks, event, 1);
2361                 return;
2362         }
2363         
2364         if(val) {
2365                 if( node_uiDoBlocks(sa, event)!=UI_NOTHING ) event= 0;
2366                 
2367                 fromlib= (snode->id && snode->id->lib);
2368                 
2369                 switch(event) {
2370                 case LEFTMOUSE:
2371                         if(gpencil_do_paint(sa, L_MOUSE)) {
2372                                 return;
2373                         }
2374                         else if(fromlib) {
2375                                 if(node_mouse_groupheader(snode)==0)
2376                                         //node_mouse_select(snode, event);
2377                         }
2378                         else {
2379                                 
2380                                 if(G.qual & LR_CTRLKEY)
2381                                         if(gesture())
2382                                                 break;
2383                                         
2384 //                              if(node_add_link(snode)==0)
2385                                         if(node_mouse_groupheader(snode)==0)
2386 //                                              if(node_mouse_select(snode, event)==0)
2387                                                         node_border_link_delete(snode);
2388                         }
2389                         break;
2390                         
2391                 case RIGHTMOUSE: 
2392                         if(gpencil_do_paint(sa, R_MOUSE)) {
2393                                 return;
2394                         }
2395                         else if(find_indicated_socket(snode, &actnode, &actsock, SOCK_IN)) {
2396                                 if(actsock->flag & SOCK_SEL) {
2397                                         snode->edittree->selin= NULL;
2398                                         actsock->flag&= ~SOCK_SEL;
2399                                 }
2400                                 else {
2401                                         snode->edittree->selin= actsock;
2402                                         reset_sel_socket(snode, SOCK_IN);
2403                                         actsock->flag|= SOCK_SEL;
2404                                 }
2405                         }
2406                         else if(find_indicated_socket(snode, &actnode, &actsock, SOCK_OUT)) {
2407                                 if(actsock->flag & SOCK_SEL) {
2408                                         snode->edittree->selout= NULL;
2409                                         actsock->flag&= ~SOCK_SEL;
2410                                 }
2411                                 else {
2412                                         snode->edittree->selout= actsock;
2413                                         reset_sel_socket(snode, SOCK_OUT);
2414                                         actsock->flag|= SOCK_SEL;
2415                                 }
2416                         }
2417 //                      else if(!node_mouse_select(snode, event)) 
2418 //                              toolbox_n();
2419
2420                         break;
2421                 case MIDDLEMOUSE:
2422                         if((snode->flag & SNODE_BACKDRAW) && (snode->treetype==NTREE_COMPOSIT)
2423                            && (G.qual==LR_SHIFTKEY)) {
2424                                 snode_bg_viewmove(snode);
2425                         } else {
2426                                 view2dmove(event);
2427                         }
2428                 case WHEELUPMOUSE:
2429                 case WHEELDOWNMOUSE:
2430                         view2dmove(event);      /* in drawipo.c */
2431                         break;
2432                         
2433                 case MOUSEY:
2434                         doredraw= node_socket_hilights(snode, SOCK_IN|SOCK_OUT);
2435                         break;
2436                 
2437                 case UI_BUT_EVENT:
2438                         /* future: handlerize this! */
2439                         if(snode->treetype==NTREE_SHADER)
2440                                 shader_node_event(snode, val);
2441                         else if(snode->treetype==NTREE_COMPOSIT)
2442                                 composit_node_event(snode, val);
2443                         else if(snode->treetype==NTREE_TEXTURE)
2444                                 texture_node_event(snode, val);
2445                         break;
2446                         
2447                 case PADPLUSKEY:
2448                         snode_zoom_in(sa);
2449                         doredraw= 1;
2450                         break;
2451                 case PADMINUS:
2452                         snode_zoom_out(sa);
2453                         doredraw= 1;
2454                         break;
2455                 case HOMEKEY:
2456                         snode_home(sa, snode);
2457                         doredraw= 1;
2458                         break;
2459                 case TABKEY:
2460                         if(fromlib) fromlib= -1;
2461                         else snode_make_group_editable(snode, NULL);
2462                         break;
2463                         
2464                 case AKEY:
2465                         if(G.qual==LR_SHIFTKEY) {
2466                                 if(fromlib) fromlib= -1;
2467                                 else toolbox_n_add();
2468                         }
2469                         break;
2470                 case BKEY:
2471                         if(G.qual==0)
2472                                 node_border_select(snode);
2473                         break;
2474                 case CKEY:      /* sort again, showing cyclics */
2475                         ntreeSolveOrder(snode->edittree);
2476                         doredraw= 1;
2477                         break;
2478                 case DKEY:
2479                         if(G.qual==LR_SHIFTKEY) {
2480                                 if(fromlib) fromlib= -1;
2481                                 else node_adduplicate(snode);
2482                         }
2483                         break;
2484                 case EKEY:
2485                         // XXX                  snode_handle_recalc(snode);
2486                         break;
2487                 case FKEY:
2488                         node_make_link(snode);
2489                         break;
2490                 case GKEY:
2491                         if(fromlib) fromlib= -1;
2492                         else {
2493                                 if(G.qual==LR_CTRLKEY) {
2494                                         if(okee("Make Group"))
2495                                                 node_make_group(snode);
2496                                 }
2497                                 else if(G.qual==LR_ALTKEY) {
2498                                         if(okee("Ungroup"))
2499                                                 node_ungroup(snode);
2500                                 }
2501                                 else if(G.qual==LR_SHIFTKEY) {
2502                                         node_addgroup(snode);
2503                                 }
2504 //                              else
2505 // XXX                                  transform_nodes(snode->edittree, 'g', "Move Node");
2506                         }
2507                         break;
2508                 case HKEY:
2509                         node_hide(snode);
2510                         break;
2511                 case IKEY:
2512                         node_insert_key(snode);
2513                         break;
2514                 case LKEY:
2515                         node_select_linked(snode, G.qual==LR_SHIFTKEY);
2516                         break;
2517                 case MKEY:
2518                         node_mute(snode);
2519                         break;
2520                 case RKEY:
2521                         if(G.qual==LR_CTRLKEY) {
2522                                 node_rename(snode);
2523                         } 
2524                         else if(G.qual==LR_SHIFTKEY) {
2525                                 if(okee("Read saved Full Sample Layers"))
2526                                         node_read_fullsamplelayers(snode);
2527                         }
2528                         else {
2529                                 if(okee("Read saved Render Layers"))
2530                                         node_read_renderlayers(snode);
2531                         }
2532                         break;
2533                 case DELKEY:
2534                 case XKEY:
2535                         if(G.qual==LR_ALTKEY) {
2536                                 gpencil_delete_menu();
2537                         }
2538                         else {
2539                                 if(fromlib) fromlib= -1;
2540                                 else node_delete(snode);
2541                         }
2542                         break;
2543                 }
2544         }
2545
2546         if(fromlib==-1)
2547                 error_libdata();
2548         if(doredraw)
2549                 scrarea_queue_winredraw(sa);
2550         if(doredraw==2)
2551                 scrarea_queue_headredraw(sa);
2552 }
2553 #endif
2554
2555 /* ****************** Delete operator ******************* */
2556
2557 static int node_delete_exec(bContext *C, wmOperator *op)
2558 {
2559         SpaceNode *snode= CTX_wm_space_node(C);
2560         bNode *node, *next;
2561         bNodeSocket *sock;
2562         
2563         for(node= snode->edittree->nodes.first; node; node= next) {
2564                 next= node->next;
2565                 if(node->flag & SELECT) {
2566                         /* set selin and selout NULL if the sockets belong to a node to be deleted */
2567                         for(sock= node->inputs.first; sock; sock= sock->next)
2568                                 if(snode->edittree->selin == sock) snode->edittree->selin= NULL;
2569
2570                         for(sock= node->outputs.first; sock; sock= sock->next)
2571                                 if(snode->edittree->selout == sock) snode->edittree->selout= NULL;
2572
2573                         /* check id user here, nodeFreeNode is called for free dbase too */
2574                         if(node->id)
2575                                 node->id->us--;
2576                         nodeFreeNode(snode->edittree, node);
2577                 }
2578         }
2579         
2580         node_tree_verify_groups(snode->nodetree);
2581
2582         // NODE_FIX_ME
2583         // snode_handle_recalc(snode);
2584
2585         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL); /* Do we need to pass the scene? */
2586
2587         return OPERATOR_FINISHED;
2588 }
2589
2590 void NODE_OT_delete(wmOperatorType *ot)
2591 {
2592         /* identifiers */
2593         ot->name= "Delete";
2594         ot->description = "Delete selected nodes.";
2595         ot->idname= "NODE_OT_delete";
2596         
2597         /* api callbacks */
2598         ot->exec= node_delete_exec;
2599         ot->poll= ED_operator_node_active;
2600         
2601         /* flags */
2602         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2603 }
2604