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