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