Cycles / HSV Separator and Combine node:
[blender.git] / source / blender / editors / space_node / node_edit.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): David Millan Escriva, Juho Vepsäläinen, Nathan Letwory
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/space_node/node_edit.c
29  *  \ingroup spnode
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_action_types.h"
35 #include "DNA_anim_types.h"
36 #include "DNA_lamp_types.h"
37 #include "DNA_material_types.h"
38 #include "DNA_node_types.h"
39 #include "DNA_object_types.h"
40 #include "DNA_text_types.h"
41 #include "DNA_world_types.h"
42
43 #include "BLI_math.h"
44 #include "BLI_blenlib.h"
45
46 #include "BKE_blender.h"
47 #include "BKE_context.h"
48 #include "BKE_depsgraph.h"
49 #include "BKE_global.h"
50 #include "BKE_image.h"
51 #include "BKE_library.h"
52 #include "BKE_main.h"
53 #include "BKE_material.h"
54 #include "BKE_node.h"
55 #include "BKE_paint.h"
56 #include "BKE_report.h"
57 #include "BKE_scene.h"
58 #include "BKE_texture.h"
59
60 #include "RE_engine.h"
61 #include "RE_pipeline.h"
62
63
64 #include "ED_node.h"  /* own include */
65 #include "ED_screen.h"
66 #include "ED_render.h"
67
68 #include "RNA_access.h"
69 #include "RNA_define.h"
70 #include "RNA_enum_types.h"
71
72 #include "WM_api.h"
73 #include "WM_types.h"
74
75 #include "UI_view2d.h"
76
77 #include "GPU_material.h"
78
79 #include "IMB_imbuf_types.h"
80
81 #include "node_intern.h"  /* own include */
82 #include "NOD_common.h"
83 #include "NOD_socket.h"
84 #include "NOD_composite.h"
85 #include "NOD_shader.h"
86 #include "NOD_texture.h"
87
88
89 #define USE_ESC_COMPO
90
91 /* ***************** composite job manager ********************** */
92
93 enum {
94         COM_RECALC_COMPOSITE = 1,
95         COM_RECALC_VIEWER    = 2
96 };
97
98 typedef struct CompoJob {
99         Scene *scene;
100         bNodeTree *ntree;
101         bNodeTree *localtree;
102         short *stop;
103         short *do_update;
104         float *progress;
105         short need_sync;
106         int recalc_flags;
107 } CompoJob;
108
109 static void compo_tag_output_nodes(bNodeTree *nodetree, int recalc_flags)
110 {
111         bNode *node;
112
113         for (node = nodetree->nodes.first; node; node = node->next) {
114                 if (node->type == CMP_NODE_COMPOSITE) {
115                         if (recalc_flags & COM_RECALC_COMPOSITE)
116                                 node->flag |= NODE_DO_OUTPUT_RECALC;
117                 }
118                 else if (node->type == CMP_NODE_VIEWER || node->type == CMP_NODE_SPLITVIEWER) {
119                         if (recalc_flags & COM_RECALC_VIEWER)
120                                 node->flag |= NODE_DO_OUTPUT_RECALC;
121                 }
122                 else if (node->type == NODE_GROUP) {
123                         if (node->id)
124                                 compo_tag_output_nodes((bNodeTree *)node->id, recalc_flags);
125                 }
126         }
127 }
128
129 static int compo_get_recalc_flags(const bContext *C)
130 {
131         wmWindowManager *wm = CTX_wm_manager(C);
132         wmWindow *win;
133         int recalc_flags = 0;
134
135         for (win = wm->windows.first; win; win = win->next) {
136                 bScreen *sc = win->screen;
137                 ScrArea *sa;
138
139                 for (sa = sc->areabase.first; sa; sa = sa->next) {
140                         if (sa->spacetype == SPACE_IMAGE) {
141                                 SpaceImage *sima = sa->spacedata.first;
142                                 if (sima->image) {
143                                         if (sima->image->type == IMA_TYPE_R_RESULT)
144                                                 recalc_flags |= COM_RECALC_COMPOSITE;
145                                         else if (sima->image->type == IMA_TYPE_COMPOSITE)
146                                                 recalc_flags |= COM_RECALC_VIEWER;
147                                 }
148                         }
149                         else if (sa->spacetype == SPACE_NODE) {
150                                 SpaceNode *snode = sa->spacedata.first;
151                                 if (snode->flag & SNODE_BACKDRAW)
152                                         recalc_flags |= COM_RECALC_VIEWER;
153                         }
154                 }
155         }
156
157         return recalc_flags;
158 }
159
160 /* called by compo, only to check job 'stop' value */
161 static int compo_breakjob(void *cjv)
162 {
163         CompoJob *cj = cjv;
164         
165         /* without G.is_break 'ESC' wont quit - which annoys users */
166         return (*(cj->stop)
167 #ifdef USE_ESC_COMPO
168                 ||
169                 G.is_break
170 #endif
171                 );
172 }
173
174 /* called by compo, wmJob sends notifier, old compositor system only */
175 static void compo_statsdrawjob(void *cjv, char *UNUSED(str))
176 {
177         CompoJob *cj = cjv;
178         
179         *(cj->do_update) = TRUE;
180         cj->need_sync = TRUE;
181 }
182
183 /* called by compo, wmJob sends notifier */
184 static void compo_redrawjob(void *cjv)
185 {
186         CompoJob *cj = cjv;
187         
188         *(cj->do_update) = TRUE;
189 }
190
191 static void compo_freejob(void *cjv)
192 {
193         CompoJob *cj = cjv;
194
195         if (cj->localtree) {
196                 ntreeLocalMerge(cj->localtree, cj->ntree);
197         }
198         MEM_freeN(cj);
199 }
200
201 /* only now we copy the nodetree, so adding many jobs while
202  * sliding buttons doesn't frustrate */
203 static void compo_initjob(void *cjv)
204 {
205         CompoJob *cj = cjv;
206
207         cj->localtree = ntreeLocalize(cj->ntree);
208
209         if (cj->recalc_flags)
210                 compo_tag_output_nodes(cj->localtree, cj->recalc_flags);
211 }
212
213 /* called before redraw notifiers, it moves finished previews over */
214 static void compo_updatejob(void *cjv)
215 {
216         CompoJob *cj = cjv;
217
218         if (cj->need_sync) {
219                 /* was used by old compositor system only */
220                 ntreeLocalSync(cj->localtree, cj->ntree);
221
222                 cj->need_sync = FALSE;
223         }
224
225         WM_main_add_notifier(NC_SCENE | ND_COMPO_RESULT, NULL);
226 }
227
228 static void compo_progressjob(void *cjv, float progress)
229 {
230         CompoJob *cj = cjv;
231         
232         *(cj->progress) = progress;
233 }
234
235
236 /* only this runs inside thread */
237 static void compo_startjob(void *cjv, short *stop, short *do_update, float *progress)
238 {
239         CompoJob *cj = cjv;
240         bNodeTree *ntree = cj->localtree;
241         Scene *scene = cj->scene;
242
243         if (scene->use_nodes == FALSE)
244                 return;
245         
246         cj->stop = stop;
247         cj->do_update = do_update;
248         cj->progress = progress;
249
250         ntree->test_break = compo_breakjob;
251         ntree->tbh = cj;
252         ntree->stats_draw = compo_statsdrawjob;
253         ntree->sdh = cj;
254         ntree->progress = compo_progressjob;
255         ntree->prh = cj;
256         ntree->update_draw = compo_redrawjob;
257         ntree->udh = cj;
258
259         // XXX BIF_store_spare();
260         
261         /* 1 is do_previews */
262         ntreeCompositExecTree(ntree, &cj->scene->r, FALSE, TRUE, &scene->view_settings, &scene->display_settings);
263
264         ntree->test_break = NULL;
265         ntree->stats_draw = NULL;
266         ntree->progress = NULL;
267
268 }
269
270 /**
271  * \param scene_owner is the owner of the job,
272  * we don't use it for anything else currently so could also be a void pointer,
273  * but for now keep it an 'Scene' for consistency.
274  *
275  * \note only call from spaces `refresh` callbacks, not direct! - use with care.
276  */
277 void ED_node_composite_job(const bContext *C, struct bNodeTree *nodetree, Scene *scene_owner)
278 {
279         wmJob *wm_job;
280         CompoJob *cj;
281
282         /* to fix bug: [#32272] */
283         if (G.is_rendering) {
284                 return;
285         }
286
287 #ifdef USE_ESC_COMPO
288         G.is_break = FALSE;
289 #endif
290
291         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene_owner, "Compositing",
292                              WM_JOB_EXCL_RENDER | WM_JOB_PROGRESS, WM_JOB_TYPE_COMPOSITE);
293         cj = MEM_callocN(sizeof(CompoJob), "compo job");
294
295         /* customdata for preview thread */
296         cj->scene = CTX_data_scene(C);
297         cj->ntree = nodetree;
298         cj->recalc_flags = compo_get_recalc_flags(C);
299
300         /* setup job */
301         WM_jobs_customdata_set(wm_job, cj, compo_freejob);
302         WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_COMPO_RESULT, NC_SCENE | ND_COMPO_RESULT);
303         WM_jobs_callbacks(wm_job, compo_startjob, compo_initjob, compo_updatejob, NULL);
304
305         WM_jobs_start(CTX_wm_manager(C), wm_job);
306 }
307
308 /* ***************************************** */
309
310 /* operator poll callback */
311 int composite_node_active(bContext *C)
312 {
313         if (ED_operator_node_active(C)) {
314                 SpaceNode *snode = CTX_wm_space_node(C);
315                 if (ED_node_is_compositor(snode))
316                         return 1;
317         }
318         return 0;
319 }
320
321 /* operator poll callback */
322 int composite_node_editable(bContext *C)
323 {
324         if (ED_operator_node_editable(C)) {
325                 SpaceNode *snode = CTX_wm_space_node(C);
326                 if (ED_node_is_compositor(snode))
327                         return 1;
328         }
329         return 0;
330 }
331
332 static int has_nodetree(bNodeTree *ntree, bNodeTree *lookup)
333 {
334         bNode *node;
335         
336         if (ntree == lookup)
337                 return 1;
338         
339         for (node = ntree->nodes.first; node; node = node->next)
340                 if (node->type == NODE_GROUP && node->id)
341                         if (has_nodetree((bNodeTree *)node->id, lookup))
342                                 return 1;
343         
344         return 0;
345 }
346
347 void snode_dag_update(bContext *C, SpaceNode *snode)
348 {
349         Main *bmain = CTX_data_main(C);
350
351         /* for groups, update all ID's using this */
352         if (snode->edittree != snode->nodetree) {
353                 FOREACH_NODETREE(bmain, tntree, id) {
354                         if (has_nodetree(tntree, snode->edittree))
355                                 DAG_id_tag_update(id, 0);
356                 } FOREACH_NODETREE_END
357         }
358
359         DAG_id_tag_update(snode->id, 0);
360 }
361
362 void snode_notify(bContext *C, SpaceNode *snode)
363 {
364         WM_event_add_notifier(C, NC_NODE | NA_EDITED, NULL);
365
366         if (ED_node_is_shader(snode))
367                 WM_event_add_notifier(C, NC_MATERIAL | ND_NODES, snode->id);
368         else if (ED_node_is_compositor(snode))
369                 WM_event_add_notifier(C, NC_SCENE | ND_NODES, snode->id);
370         else if (ED_node_is_texture(snode))
371                 WM_event_add_notifier(C, NC_TEXTURE | ND_NODES, snode->id);
372 }
373
374 void ED_node_set_tree_type(SpaceNode *snode, bNodeTreeType *typeinfo)
375 {
376         if (typeinfo)
377                 BLI_strncpy(snode->tree_idname, typeinfo->idname, sizeof(snode->tree_idname));
378         else
379                 snode->tree_idname[0] = '\0';
380 }
381
382 int ED_node_is_compositor(struct SpaceNode *snode)
383 {
384         return STREQ(snode->tree_idname, ntreeType_Composite->idname);
385 }
386
387 int ED_node_is_shader(struct SpaceNode *snode)
388 {
389         return STREQ(snode->tree_idname, ntreeType_Shader->idname);
390 }
391
392 int ED_node_is_texture(struct SpaceNode *snode)
393 {
394         return STREQ(snode->tree_idname, ntreeType_Texture->idname);
395 }
396
397 /* assumes nothing being done in ntree yet, sets the default in/out node */
398 /* called from shading buttons or header */
399 void ED_node_shader_default(const bContext *C, ID *id)
400 {
401         Scene *scene = CTX_data_scene(C);
402         bNode *in, *out;
403         bNodeSocket *fromsock, *tosock, *sock;
404         bNodeTree *ntree;
405         int output_type, shader_type;
406         float color[4] = { 0.0f, 0.0f, 0.0f, 1.0f }, strength = 1.0f;
407         
408         ntree = ntreeAddTree(NULL, "Shader Nodetree", ntreeType_Shader->idname);
409
410         switch (GS(id->name)) {
411                 case ID_MA:
412                 {
413                         Material *ma = (Material *)id;
414                         ma->nodetree = ntree;
415
416                         if (BKE_scene_use_new_shading_nodes(scene)) {
417                                 output_type = SH_NODE_OUTPUT_MATERIAL;
418                                 shader_type = SH_NODE_BSDF_DIFFUSE;
419                         }
420                         else {
421                                 output_type = SH_NODE_OUTPUT;
422                                 shader_type = SH_NODE_MATERIAL;
423                         }
424
425                         copy_v3_v3(color, &ma->r);
426                         strength = 0.0f;
427                         break;
428                 }
429                 case ID_WO:
430                 {
431                         World *wo = (World *)id;
432                         wo->nodetree = ntree;
433
434                         output_type = SH_NODE_OUTPUT_WORLD;
435                         shader_type = SH_NODE_BACKGROUND;
436
437                         copy_v3_v3(color, &wo->horr);
438                         strength = 1.0f;
439                         break;
440                 }
441                 case ID_LA:
442                 {
443                         Lamp *la = (Lamp *)id;
444                         la->nodetree = ntree;
445
446                         output_type = SH_NODE_OUTPUT_LAMP;
447                         shader_type = SH_NODE_EMISSION;
448
449                         copy_v3_v3(color, &la->r);
450                         if (la->type == LA_LOCAL || la->type == LA_SPOT || la->type == LA_AREA)
451                                 strength = 100.0f;
452                         else
453                                 strength = 1.0f;
454                         break;
455                 }
456                 default:
457                         printf("ED_node_shader_default called on wrong ID type.\n");
458                         return;
459         }
460         
461         out = nodeAddStaticNode(C, ntree, output_type);
462         out->locx = 300.0f; out->locy = 300.0f;
463         
464         in = nodeAddStaticNode(C, ntree, shader_type);
465         in->locx = 10.0f; in->locy = 300.0f;
466         nodeSetActive(ntree, in);
467         
468         /* only a link from color to color */
469         fromsock = in->outputs.first;
470         tosock = out->inputs.first;
471         nodeAddLink(ntree, in, fromsock, out, tosock);
472
473         /* default values */
474         if (BKE_scene_use_new_shading_nodes(scene)) {
475                 PointerRNA sockptr;
476                 sock = in->inputs.first;
477                 RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, sock, &sockptr);
478                 
479                 RNA_float_set_array(&sockptr, "default_value", color);
480
481                 if (strength != 0.0f) {
482                         sock = in->inputs.last;
483                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, sock, &sockptr);
484                         RNA_float_set(&sockptr, "default_value", strength);
485                 }
486         }
487         
488         ntreeUpdateTree(CTX_data_main(C), ntree);
489 }
490
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_composit_default(const bContext *C, struct Scene *sce)
494 {
495         bNode *in, *out;
496         bNodeSocket *fromsock, *tosock;
497         
498         /* but lets check it anyway */
499         if (sce->nodetree) {
500                 if (G.debug & G_DEBUG)
501                         printf("error in composite initialize\n");
502                 return;
503         }
504         
505         sce->nodetree = ntreeAddTree(NULL, "Compositing Nodetree", ntreeType_Composite->idname);
506         
507         sce->nodetree->chunksize = 256;
508         sce->nodetree->edit_quality = NTREE_QUALITY_HIGH;
509         sce->nodetree->render_quality = NTREE_QUALITY_HIGH;
510         
511         out = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_COMPOSITE);
512         out->locx = 300.0f; out->locy = 400.0f;
513         out->id = &sce->id;
514         id_us_plus(out->id);
515         
516         in = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_R_LAYERS);
517         in->locx = 10.0f; in->locy = 400.0f;
518         in->id = &sce->id;
519         id_us_plus(in->id);
520         nodeSetActive(sce->nodetree, in);
521         
522         /* links from color to color */
523         fromsock = in->outputs.first;
524         tosock = out->inputs.first;
525         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
526         
527         ntreeUpdateTree(CTX_data_main(C), sce->nodetree);
528         
529         // XXX ntreeCompositForceHidden(sce->nodetree);
530 }
531
532 /* assumes nothing being done in ntree yet, sets the default in/out node */
533 /* called from shading buttons or header */
534 void ED_node_texture_default(const bContext *C, Tex *tx)
535 {
536         bNode *in, *out;
537         bNodeSocket *fromsock, *tosock;
538         
539         /* but lets check it anyway */
540         if (tx->nodetree) {
541                 if (G.debug & G_DEBUG)
542                         printf("error in texture initialize\n");
543                 return;
544         }
545         
546         tx->nodetree = ntreeAddTree(NULL, "Texture Nodetree", ntreeType_Texture->idname);
547         
548         out = nodeAddStaticNode(C, tx->nodetree, TEX_NODE_OUTPUT);
549         out->locx = 300.0f; out->locy = 300.0f;
550         
551         in = nodeAddStaticNode(C, tx->nodetree, TEX_NODE_CHECKER);
552         in->locx = 10.0f; in->locy = 300.0f;
553         nodeSetActive(tx->nodetree, in);
554         
555         fromsock = in->outputs.first;
556         tosock = out->inputs.first;
557         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
558         
559         ntreeUpdateTree(CTX_data_main(C), tx->nodetree);
560 }
561
562 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
563 void snode_set_context(const bContext *C)
564 {
565         SpaceNode *snode = CTX_wm_space_node(C);
566         bNodeTreeType *treetype = ntreeTypeFind(snode->tree_idname);
567         bNodeTree *ntree = snode->nodetree;
568         ID *id = snode->id, *from = snode->from;
569         
570         /* we use this to signal warnings, when node shaders are drawn in wrong render engine */
571         if (BKE_scene_use_new_shading_nodes(CTX_data_scene(C)))
572                 snode->flag |= SNODE_NEW_SHADERS;
573         else
574                 snode->flag &= ~SNODE_NEW_SHADERS;
575         
576         /* check the tree type */
577         if (!treetype ||
578             (treetype->poll && !treetype->poll(C, treetype)))
579         {
580                 /* invalid tree type, skip
581                  * NB: not resetting the node path here, invalid bNodeTreeType
582                  * may still be registered at a later point.
583                  */
584                 return;
585         }
586         
587         if (snode->nodetree && strcmp(snode->nodetree->idname, snode->tree_idname) != 0) {
588                 /* current tree does not match selected type, clear tree path */
589                 ntree = NULL;
590                 id = NULL;
591                 from = NULL;
592         }
593         
594         if (!(snode->flag & SNODE_PIN) || ntree == NULL) {
595                 if (treetype->get_from_context) {
596                         /* reset and update from context */
597                         ntree = NULL;
598                         id = NULL;
599                         from = NULL;
600                         
601                         treetype->get_from_context(C, treetype, &ntree, &id, &from);
602                 }
603         }
604         
605         if (snode->nodetree != ntree || snode->id != id || snode->from != from) {
606                 ED_node_tree_start(snode, ntree, id, from);
607         }
608 }
609
610 void snode_update(SpaceNode *snode, bNode *node)
611 {
612         bNodeTreePath *path;
613         
614         /* XXX this only updates nodes in the current node space tree path.
615          * The function supposedly should update any potential group node linking to changed tree,
616          * this really requires a working depsgraph ...
617          */
618         
619         /* update all edited group nodes */
620         path = snode->treepath.last;
621         if (path) {
622                 bNodeTree *ngroup = path->nodetree;
623                 for (path = path->prev; path; path = path->prev) {
624                         nodeUpdateID(path->nodetree, (ID *)ngroup);
625                         ngroup = path->nodetree;
626                 }
627         }
628
629         if (node)
630                 nodeUpdate(snode->edittree, node);
631 }
632
633 void ED_node_set_active(Main *bmain, bNodeTree *ntree, bNode *node)
634 {
635         int was_active_texture = (node->flag & NODE_ACTIVE_TEXTURE);
636
637         nodeSetActive(ntree, node);
638         
639         if (node->type != NODE_GROUP) {
640                 int was_output = (node->flag & NODE_DO_OUTPUT);
641                 int do_update = 0;
642                 
643                 /* generic node group output: set node as active output */
644                 if (node->type == NODE_GROUP_OUTPUT) {
645                         bNode *tnode;
646                         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
647                                 if (tnode->type == NODE_GROUP_OUTPUT)
648                                         tnode->flag &= ~NODE_DO_OUTPUT;
649                         
650                         node->flag |= NODE_DO_OUTPUT;
651                         if (!was_output)
652                                 do_update = 1;
653                 }
654                 
655                 /* tree specific activate calls */
656                 if (ntree->type == NTREE_SHADER) {
657                         /* when we select a material, active texture is cleared, for buttons */
658                         if (node->id && ELEM3(GS(node->id->name), ID_MA, ID_LA, ID_WO))
659                                 nodeClearActiveID(ntree, ID_TE);
660                         
661                         if (node->type == SH_NODE_OUTPUT) {
662                                 bNode *tnode;
663                                 
664                                 for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
665                                         if (tnode->type == SH_NODE_OUTPUT)
666                                                 tnode->flag &= ~NODE_DO_OUTPUT;
667                                 
668                                 node->flag |= NODE_DO_OUTPUT;
669                                 if (was_output == 0)
670                                         ED_node_tag_update_nodetree(bmain, ntree);
671                         }
672                         else if (do_update)
673                                 ED_node_tag_update_nodetree(bmain, ntree);
674
675                         /* if active texture changed, free glsl materials */
676                         if ((node->flag & NODE_ACTIVE_TEXTURE) && !was_active_texture) {
677                                 Material *ma;
678
679                                 for (ma = bmain->mat.first; ma; ma = ma->id.next)
680                                         if (ma->nodetree && ma->use_nodes && has_nodetree(ma->nodetree, ntree))
681                                                 GPU_material_free(ma);
682
683                                 WM_main_add_notifier(NC_IMAGE, NULL);
684                         }
685
686                         WM_main_add_notifier(NC_MATERIAL | ND_NODES, node->id);
687                 }
688                 else if (ntree->type == NTREE_COMPOSIT) {
689                         /* make active viewer, currently only 1 supported... */
690                         if (ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
691                                 bNode *tnode;
692                                 
693
694                                 for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
695                                         if (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
696                                                 tnode->flag &= ~NODE_DO_OUTPUT;
697                                 
698                                 node->flag |= NODE_DO_OUTPUT;
699                                 if (was_output == 0)
700                                         ED_node_tag_update_nodetree(bmain, ntree);
701                                 
702                                 /* addnode() doesnt link this yet... */
703                                 node->id = (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
704                         }
705                         else if (node->type == CMP_NODE_R_LAYERS) {
706                                 Scene *scene;
707
708                                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
709                                         if (scene->nodetree && scene->use_nodes && has_nodetree(scene->nodetree, ntree)) {
710                                                 if (node->id == NULL || node->id == (ID *)scene) {
711                                                         scene->r.actlay = node->custom1;
712                                                 }
713                                         }
714                                 }
715                         }
716                         else if (node->type == CMP_NODE_COMPOSITE) {
717                                 if (was_output == 0) {
718                                         bNode *tnode;
719                                         
720                                         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
721                                                 if (tnode->type == CMP_NODE_COMPOSITE)
722                                                         tnode->flag &= ~NODE_DO_OUTPUT;
723                                         
724                                         node->flag |= NODE_DO_OUTPUT;
725                                         ED_node_tag_update_nodetree(bmain, ntree);
726                                 }
727                         }
728                         else if (do_update)
729                                 ED_node_tag_update_nodetree(bmain, ntree);
730                 }
731                 else if (ntree->type == NTREE_TEXTURE) {
732                         // XXX
733 #if 0
734                         if (node->id)
735                                 ;  // XXX BIF_preview_changed(-1);
736                         // allqueue(REDRAWBUTSSHADING, 1);
737                         // allqueue(REDRAWIPO, 0);
738 #endif
739                 }
740         }
741 }
742
743 void ED_node_post_apply_transform(bContext *UNUSED(C), bNodeTree *UNUSED(ntree))
744 {
745         /* XXX This does not work due to layout functions relying on node->block,
746          * which only exists during actual drawing. Can we rely on valid totr rects?
747          */
748         /* make sure nodes have correct bounding boxes after transform */
749         /* node_update_nodetree(C, ntree, 0.0f, 0.0f); */
750 }
751
752 /* ***************** generic operator functions for nodes ***************** */
753
754 #if 0 /* UNUSED */
755
756 static int edit_node_poll(bContext *C)
757 {
758         return ED_operator_node_active(C);
759 }
760
761 static void edit_node_properties(wmOperatorType *ot)
762 {
763         /* XXX could node be a context pointer? */
764         RNA_def_string(ot->srna, "node", "", MAX_NAME, "Node", "");
765         RNA_def_int(ot->srna, "socket", 0, 0, MAX_SOCKET, "Socket", "", 0, MAX_SOCKET);
766         RNA_def_enum(ot->srna, "in_out", node_socket_in_out_items, SOCK_IN, "Socket Side", "");
767 }
768
769 static int edit_node_invoke_properties(bContext *C, wmOperator *op)
770 {
771         if (!RNA_struct_property_is_set(op->ptr, "node")) {
772                 bNode *node = CTX_data_pointer_get_type(C, "node", &RNA_Node).data;
773                 if (!node)
774                         return 0;
775                 else
776                         RNA_string_set(op->ptr, "node", node->name);
777         }
778         
779         if (!RNA_struct_property_is_set(op->ptr, "in_out"))
780                 RNA_enum_set(op->ptr, "in_out", SOCK_IN);
781         
782         if (!RNA_struct_property_is_set(op->ptr, "socket"))
783                 RNA_int_set(op->ptr, "socket", 0);
784         
785         return 1;
786 }
787
788 static void edit_node_properties_get(wmOperator *op, bNodeTree *ntree, bNode **rnode, bNodeSocket **rsock, int *rin_out)
789 {
790         bNode *node;
791         bNodeSocket *sock = NULL;
792         char nodename[MAX_NAME];
793         int sockindex;
794         int in_out;
795         
796         RNA_string_get(op->ptr, "node", nodename);
797         node = nodeFindNodebyName(ntree, nodename);
798         
799         in_out = RNA_enum_get(op->ptr, "in_out");
800         
801         sockindex = RNA_int_get(op->ptr, "socket");
802         switch (in_out) {
803                 case SOCK_IN:   sock = BLI_findlink(&node->inputs, sockindex);  break;
804                 case SOCK_OUT:  sock = BLI_findlink(&node->outputs, sockindex); break;
805         }
806         
807         if (rnode)
808                 *rnode = node;
809         if (rsock)
810                 *rsock = sock;
811         if (rin_out)
812                 *rin_out = in_out;
813 }
814 #endif
815
816 /* ************************** Node generic ************** */
817
818 /* is rct in visible part of node? */
819 static bNode *visible_node(SpaceNode *snode, const rctf *rct)
820 {
821         bNode *node;
822         
823         for (node = snode->edittree->nodes.last; node; node = node->prev) {
824                 if (BLI_rctf_isect(&node->totr, rct, NULL))
825                         break;
826         }
827         return node;
828 }
829
830 /* ********************** size widget operator ******************** */
831
832 typedef struct NodeSizeWidget {
833         float mxstart, mystart;
834         float oldlocx, oldlocy;
835         float oldoffsetx, oldoffsety;
836         float oldwidth, oldheight;
837         float oldminiwidth;
838         int directions;
839 } NodeSizeWidget;
840
841 static void node_resize_init(bContext *C, wmOperator *op, const wmEvent *UNUSED(event), bNode *node, int dir)
842 {
843         SpaceNode *snode = CTX_wm_space_node(C);
844         
845         NodeSizeWidget *nsw = MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
846         
847         op->customdata = nsw;
848         nsw->mxstart = snode->cursor[0];
849         nsw->mystart = snode->cursor[1];
850         
851         /* store old */
852         nsw->oldlocx = node->locx;
853         nsw->oldlocy = node->locy;
854         nsw->oldoffsetx = node->offsetx;
855         nsw->oldoffsety = node->offsety;
856         nsw->oldwidth = node->width;
857         nsw->oldheight = node->height;
858         nsw->oldminiwidth = node->miniwidth;
859         nsw->directions = dir;
860         
861         WM_cursor_modal(CTX_wm_window(C), node_get_resize_cursor(dir));
862         /* add modal handler */
863         WM_event_add_modal_handler(C, op);
864 }
865
866 static void node_resize_exit(bContext *C, wmOperator *op, int UNUSED(cancel))
867 {
868         WM_cursor_restore(CTX_wm_window(C));
869         
870         MEM_freeN(op->customdata);
871         op->customdata = NULL;
872 }
873
874 static int node_resize_modal(bContext *C, wmOperator *op, const wmEvent *event)
875 {
876         SpaceNode *snode = CTX_wm_space_node(C);
877         ARegion *ar = CTX_wm_region(C);
878         bNode *node = nodeGetActive(snode->edittree);
879         NodeSizeWidget *nsw = op->customdata;
880         float mx, my, dx, dy;
881         
882         switch (event->type) {
883                 case MOUSEMOVE:
884                         
885                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &mx, &my);
886                         dx = (mx - nsw->mxstart) / UI_DPI_FAC;
887                         dy = (my - nsw->mystart) / UI_DPI_FAC;
888                         
889                         if (node) {
890                                 if (node->flag & NODE_HIDDEN) {
891                                         float widthmin = 0.0f;
892                                         float widthmax = 100.0f;
893                                         if (nsw->directions & NODE_RESIZE_RIGHT) {
894                                                 node->miniwidth = nsw->oldminiwidth + dx;
895                                                 CLAMP(node->miniwidth, widthmin, widthmax);
896                                         }
897                                         if (nsw->directions & NODE_RESIZE_LEFT) {
898                                                 float locmax = nsw->oldlocx + nsw->oldminiwidth;
899                                                 
900                                                 node->locx = nsw->oldlocx + dx;
901                                                 CLAMP(node->locx, locmax - widthmax, locmax - widthmin);
902                                                 node->miniwidth = locmax - node->locx;
903                                         }
904                                 }
905                                 else {
906                                         float widthmin = node->typeinfo->minwidth;
907                                         float widthmax = node->typeinfo->maxwidth;
908                                         if (nsw->directions & NODE_RESIZE_RIGHT) {
909                                                 node->width = nsw->oldwidth + dx;
910                                                 CLAMP(node->width, widthmin, widthmax);
911                                         }
912                                         if (nsw->directions & NODE_RESIZE_LEFT) {
913                                                 float locmax = nsw->oldlocx + nsw->oldwidth;
914                                                 
915                                                 node->locx = nsw->oldlocx + dx;
916                                                 CLAMP(node->locx, locmax - widthmax, locmax - widthmin);
917                                                 node->width = locmax - node->locx;
918                                         }
919                                 }
920                         
921                                 /* height works the other way round ... */
922                                 {
923                                         float heightmin = UI_DPI_FAC * node->typeinfo->minheight;
924                                         float heightmax = UI_DPI_FAC * node->typeinfo->maxheight;
925                                         if (nsw->directions & NODE_RESIZE_TOP) {
926                                                 float locmin = nsw->oldlocy - nsw->oldheight;
927                                                 
928                                                 node->locy = nsw->oldlocy + dy;
929                                                 CLAMP(node->locy, locmin + heightmin, locmin + heightmax);
930                                                 node->height = node->locy - locmin;
931                                         }
932                                         if (nsw->directions & NODE_RESIZE_BOTTOM) {
933                                                 node->height = nsw->oldheight - dy;
934                                                 CLAMP(node->height, heightmin, heightmax);
935                                         }
936                                 }
937                                 
938                                 /* XXX make callback? */
939                                 if (node->type == NODE_FRAME) {
940                                         /* keep the offset symmetric around center point */
941                                         if (nsw->directions & NODE_RESIZE_LEFT) {
942                                                 node->locx = nsw->oldlocx + 0.5f * dx;
943                                                 node->offsetx = nsw->oldoffsetx + 0.5f * dx;
944                                         }
945                                         if (nsw->directions & NODE_RESIZE_RIGHT) {
946                                                 node->locx = nsw->oldlocx + 0.5f * dx;
947                                                 node->offsetx = nsw->oldoffsetx - 0.5f * dx;
948                                         }
949                                         if (nsw->directions & NODE_RESIZE_TOP) {
950                                                 node->locy = nsw->oldlocy + 0.5f * dy;
951                                                 node->offsety = nsw->oldoffsety + 0.5f * dy;
952                                         }
953                                         if (nsw->directions & NODE_RESIZE_BOTTOM) {
954                                                 node->locy = nsw->oldlocy + 0.5f * dy;
955                                                 node->offsety = nsw->oldoffsety - 0.5f * dy;
956                                         }
957                                 }
958                         }
959                                 
960                         ED_region_tag_redraw(ar);
961
962                         break;
963                         
964                 case LEFTMOUSE:
965                 case MIDDLEMOUSE:
966                 case RIGHTMOUSE:
967                         
968                         node_resize_exit(C, op, 0);
969                         ED_node_post_apply_transform(C, snode->edittree);
970                         
971                         return OPERATOR_FINISHED;
972         }
973         
974         return OPERATOR_RUNNING_MODAL;
975 }
976
977 static int node_resize_invoke(bContext *C, wmOperator *op, const wmEvent *event)
978 {
979         SpaceNode *snode = CTX_wm_space_node(C);
980         ARegion *ar = CTX_wm_region(C);
981         bNode *node = nodeGetActive(snode->edittree);
982         int dir;
983         
984         if (node) {
985                 /* convert mouse coordinates to v2d space */
986                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
987                                          &snode->cursor[0], &snode->cursor[1]);
988                 dir = node->typeinfo->resize_area_func(node, snode->cursor[0], snode->cursor[1]);
989                 if (dir != 0) {
990                         node_resize_init(C, op, event, node, dir);
991                         return OPERATOR_RUNNING_MODAL;
992                 }
993         }
994         return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
995 }
996
997 static int node_resize_cancel(bContext *C, wmOperator *op)
998 {
999         node_resize_exit(C, op, 1);
1000
1001         return OPERATOR_CANCELLED;
1002 }
1003
1004 void NODE_OT_resize(wmOperatorType *ot)
1005 {
1006         /* identifiers */
1007         ot->name = "Resize Node";
1008         ot->idname = "NODE_OT_resize";
1009         ot->description = "Resize a node";
1010         
1011         /* api callbacks */
1012         ot->invoke = node_resize_invoke;
1013         ot->modal = node_resize_modal;
1014         ot->poll = ED_operator_node_active;
1015         ot->cancel = node_resize_cancel;
1016         
1017         /* flags */
1018         ot->flag = OPTYPE_BLOCKING;
1019 }
1020
1021
1022 /* ********************** hidden sockets ******************** */
1023
1024 int node_has_hidden_sockets(bNode *node)
1025 {
1026         bNodeSocket *sock;
1027         
1028         for (sock = node->inputs.first; sock; sock = sock->next)
1029                 if (sock->flag & SOCK_HIDDEN)
1030                         return 1;
1031         for (sock = node->outputs.first; sock; sock = sock->next)
1032                 if (sock->flag & SOCK_HIDDEN)
1033                         return 1;
1034         return 0;
1035 }
1036
1037 void node_set_hidden_sockets(SpaceNode *snode, bNode *node, int set)
1038 {
1039         bNodeSocket *sock;
1040
1041         if (set == 0) {
1042                 for (sock = node->inputs.first; sock; sock = sock->next)
1043                         sock->flag &= ~SOCK_HIDDEN;
1044                 for (sock = node->outputs.first; sock; sock = sock->next)
1045                         sock->flag &= ~SOCK_HIDDEN;
1046         }
1047         else {
1048                 /* hide unused sockets */
1049                 for (sock = node->inputs.first; sock; sock = sock->next) {
1050                         if (sock->link == NULL)
1051                                 sock->flag |= SOCK_HIDDEN;
1052                 }
1053                 for (sock = node->outputs.first; sock; sock = sock->next) {
1054                         if (nodeCountSocketLinks(snode->edittree, sock) == 0)
1055                                 sock->flag |= SOCK_HIDDEN;
1056                 }
1057         }
1058 }
1059
1060
1061 /* checks snode->mouse position, and returns found node/socket */
1062 /* type is SOCK_IN and/or SOCK_OUT */
1063 int node_find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1064 {
1065         bNode *node;
1066         bNodeSocket *sock;
1067         rctf rect;
1068         
1069         *nodep = NULL;
1070         *sockp = NULL;
1071         
1072         /* check if we click in a socket */
1073         for (node = snode->edittree->nodes.first; node; node = node->next) {
1074                 
1075                 rect.xmin = snode->cursor[0] - (NODE_SOCKSIZE + 4);
1076                 rect.ymin = snode->cursor[1] - (NODE_SOCKSIZE + 4);
1077                 rect.xmax = snode->cursor[0] + (NODE_SOCKSIZE + 4);
1078                 rect.ymax = snode->cursor[1] + (NODE_SOCKSIZE + 4);
1079                 
1080                 if (!(node->flag & NODE_HIDDEN)) {
1081                         /* extra padding inside and out - allow dragging on the text areas too */
1082                         if (in_out == SOCK_IN) {
1083                                 rect.xmax += NODE_SOCKSIZE;
1084                                 rect.xmin -= NODE_SOCKSIZE * 4;
1085                         }
1086                         else if (in_out == SOCK_OUT) {
1087                                 rect.xmax += NODE_SOCKSIZE * 4;
1088                                 rect.xmin -= NODE_SOCKSIZE;
1089                         }
1090                 }
1091                 
1092                 if (in_out & SOCK_IN) {
1093                         for (sock = node->inputs.first; sock; sock = sock->next) {
1094                                 if (!nodeSocketIsHidden(sock)) {
1095                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1096                                                 if (node == visible_node(snode, &rect)) {
1097                                                         *nodep = node;
1098                                                         *sockp = sock;
1099                                                         return 1;
1100                                                 }
1101                                         }
1102                                 }
1103                         }
1104                 }
1105                 if (in_out & SOCK_OUT) {
1106                         for (sock = node->outputs.first; sock; sock = sock->next) {
1107                                 if (!nodeSocketIsHidden(sock)) {
1108                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1109                                                 if (node == visible_node(snode, &rect)) {
1110                                                         *nodep = node;
1111                                                         *sockp = sock;
1112                                                         return 1;
1113                                                 }
1114                                         }
1115                                 }
1116                         }
1117                 }
1118         }
1119         
1120         return 0;
1121 }
1122
1123 /* ****************** Duplicate *********************** */
1124
1125 static void node_duplicate_reparent_recursive(bNode *node)
1126 {
1127         bNode *parent;
1128         
1129         node->flag |= NODE_TEST;
1130         
1131         /* find first selected parent */
1132         for (parent = node->parent; parent; parent = parent->parent) {
1133                 if (parent->flag & SELECT) {
1134                         if (!(parent->flag & NODE_TEST))
1135                                 node_duplicate_reparent_recursive(parent);
1136                         break;
1137                 }
1138         }
1139         /* reparent node copy to parent copy */
1140         if (parent) {
1141                 nodeDetachNode(node->new_node);
1142                 nodeAttachNode(node->new_node, parent->new_node);
1143         }
1144 }
1145
1146 static int node_duplicate_exec(bContext *C, wmOperator *op)
1147 {
1148         SpaceNode *snode = CTX_wm_space_node(C);
1149         bNodeTree *ntree = snode->edittree;
1150         bNode *node, *newnode, *lastnode;
1151         bNodeLink *link, *newlink, *lastlink;
1152         int keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
1153         
1154         ED_preview_kill_jobs(C);
1155         
1156         lastnode = ntree->nodes.last;
1157         for (node = ntree->nodes.first; node; node = node->next) {
1158                 if (node->flag & SELECT) {
1159                         newnode = nodeCopyNode(ntree, node);
1160                         
1161                         if (newnode->id) {
1162                                 /* simple id user adjustment, node internal functions don't touch this
1163                                  * but operators and readfile.c do. */
1164                                 id_us_plus(newnode->id);
1165                                 /* to ensure redraws or rerenders happen */
1166                                 ED_node_tag_update_id(snode->id);
1167                         }
1168                 }
1169                 
1170                 /* make sure we don't copy new nodes again! */
1171                 if (node == lastnode)
1172                         break;
1173         }
1174         
1175         /* copy links between selected nodes
1176          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
1177          */
1178         lastlink = ntree->links.last;
1179         for (link = ntree->links.first; link; link = link->next) {
1180                 /* This creates new links between copied nodes.
1181                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
1182                  */
1183                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
1184                     (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT))))
1185                 {
1186                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
1187                         newlink->flag = link->flag;
1188                         newlink->tonode = link->tonode->new_node;
1189                         newlink->tosock = link->tosock->new_sock;
1190                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
1191                                 newlink->fromnode = link->fromnode->new_node;
1192                                 newlink->fromsock = link->fromsock->new_sock;
1193                         }
1194                         else {
1195                                 /* input node not copied, this keeps the original input linked */
1196                                 newlink->fromnode = link->fromnode;
1197                                 newlink->fromsock = link->fromsock;
1198                         }
1199                         
1200                         BLI_addtail(&ntree->links, newlink);
1201                 }
1202                 
1203                 /* make sure we don't copy new links again! */
1204                 if (link == lastlink)
1205                         break;
1206         }
1207         
1208         /* clear flags for recursive depth-first iteration */
1209         for (node = ntree->nodes.first; node; node = node->next)
1210                 node->flag &= ~NODE_TEST;
1211         /* reparent copied nodes */
1212         for (node = ntree->nodes.first; node; node = node->next) {
1213                 if ((node->flag & SELECT) && !(node->flag & NODE_TEST))
1214                         node_duplicate_reparent_recursive(node);
1215                 
1216                 /* only has to check old nodes */
1217                 if (node == lastnode)
1218                         break;
1219         }
1220         
1221         /* deselect old nodes, select the copies instead */
1222         for (node = ntree->nodes.first; node; node = node->next) {
1223                 if (node->flag & SELECT) {
1224                         /* has been set during copy above */
1225                         newnode = node->new_node;
1226                         
1227                         nodeSetSelected(node, FALSE);
1228                         node->flag &= ~NODE_ACTIVE;
1229                         nodeSetSelected(newnode, TRUE);
1230                 }
1231                 
1232                 /* make sure we don't copy new nodes again! */
1233                 if (node == lastnode)
1234                         break;
1235         }
1236         
1237         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1238         
1239         snode_notify(C, snode);
1240         snode_dag_update(C, snode);
1241
1242         return OPERATOR_FINISHED;
1243 }
1244
1245 void NODE_OT_duplicate(wmOperatorType *ot)
1246 {
1247         /* identifiers */
1248         ot->name = "Duplicate Nodes";
1249         ot->description = "Duplicate selected nodes";
1250         ot->idname = "NODE_OT_duplicate";
1251         
1252         /* api callbacks */
1253         ot->exec = node_duplicate_exec;
1254         ot->poll = ED_operator_node_editable;
1255         
1256         /* flags */
1257         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1258         
1259         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
1260 }
1261
1262 int ED_node_select_check(ListBase *lb)
1263
1264
1265 {
1266         bNode *node;
1267
1268         for (node = lb->first; node; node = node->next) {
1269                 if (node->flag & NODE_SELECT) {
1270                         return TRUE;
1271                 }
1272         }
1273
1274         return FALSE;
1275 }
1276
1277 /* ******************************** */
1278 // XXX some code needing updating to operators...
1279
1280
1281 /* goes over all scenes, reads render layers */
1282 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
1283 {
1284         Main *bmain = CTX_data_main(C);
1285         SpaceNode *snode = CTX_wm_space_node(C);
1286         Scene *curscene = CTX_data_scene(C), *scene;
1287         bNode *node;
1288
1289         ED_preview_kill_jobs(C);
1290
1291         /* first tag scenes unread */
1292         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1293                 scene->id.flag |= LIB_DOIT;
1294
1295         for (node = snode->edittree->nodes.first; node; node = node->next) {
1296                 if (node->type == CMP_NODE_R_LAYERS) {
1297                         ID *id = node->id;
1298                         if (id->flag & LIB_DOIT) {
1299                                 RE_ReadRenderResult(curscene, (Scene *)id);
1300                                 ntreeCompositTagRender((Scene *)id);
1301                                 id->flag &= ~LIB_DOIT;
1302                         }
1303                 }
1304         }
1305         
1306         snode_notify(C, snode);
1307         snode_dag_update(C, snode);
1308
1309         return OPERATOR_FINISHED;
1310 }
1311
1312 void NODE_OT_read_renderlayers(wmOperatorType *ot)
1313 {
1314         
1315         ot->name = "Read Render Layers";
1316         ot->idname = "NODE_OT_read_renderlayers";
1317         ot->description = "Read all render layers of all used scenes";
1318         
1319         ot->exec = node_read_renderlayers_exec;
1320         
1321         ot->poll = composite_node_active;
1322         
1323         /* flags */
1324         ot->flag = 0;
1325 }
1326
1327 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
1328 {
1329         Main *bmain = CTX_data_main(C);
1330         SpaceNode *snode = CTX_wm_space_node(C);
1331         Scene *curscene = CTX_data_scene(C);
1332         Render *re = RE_NewRender(curscene->id.name);
1333
1334         WM_cursor_wait(1);
1335         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
1336         WM_cursor_wait(0);
1337
1338         /* note we are careful to send the right notifier, as otherwise the
1339          * compositor would reexecute and overwrite the full sample result */
1340         WM_event_add_notifier(C, NC_SCENE | ND_COMPO_RESULT, NULL);
1341
1342         return OPERATOR_FINISHED;
1343 }
1344
1345
1346 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
1347 {
1348         
1349         ot->name = "Read Full Sample Layers";
1350         ot->idname = "NODE_OT_read_fullsamplelayers";
1351         ot->description = "Read all render layers of current scene, in full sample";
1352         
1353         ot->exec = node_read_fullsamplelayers_exec;
1354         
1355         ot->poll = composite_node_active;
1356         
1357         /* flags */
1358         ot->flag = 0;
1359 }
1360
1361 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
1362 {
1363         Scene *sce = CTX_data_scene(C);
1364         bNode *node;
1365         
1366         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1367                 if (node->id == (ID *)sce && node->need_exec) {
1368                         break;
1369                 }
1370         }
1371         if (node) {
1372                 SceneRenderLayer *srl = BLI_findlink(&sce->r.layers, node->custom1);
1373                 
1374                 if (srl) {
1375                         PointerRNA op_ptr;
1376                         
1377                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
1378                         RNA_string_set(&op_ptr, "layer", srl->name);
1379                         RNA_string_set(&op_ptr, "scene", sce->id.name + 2);
1380                         
1381                         /* to keep keypositions */
1382                         sce->r.scemode |= R_NO_FRAME_UPDATE;
1383                         
1384                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
1385
1386                         WM_operator_properties_free(&op_ptr);
1387                         
1388                         return OPERATOR_FINISHED;
1389                 }
1390                    
1391         }
1392         return OPERATOR_CANCELLED;
1393 }
1394
1395 void NODE_OT_render_changed(wmOperatorType *ot)
1396 {
1397         ot->name = "Render Changed Layer";
1398         ot->idname = "NODE_OT_render_changed";
1399         ot->description = "Render current scene, when input node's layer has been changed";
1400         
1401         ot->exec = node_render_changed_exec;
1402         
1403         ot->poll = composite_node_active;
1404         
1405         /* flags */
1406         ot->flag = 0;
1407 }
1408
1409
1410 /* ****************** Hide operator *********************** */
1411
1412 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
1413 {
1414         bNode *node;
1415         int tot_eq = 0, tot_neq = 0;
1416
1417         /* Toggles the flag on all selected nodes.
1418          * If the flag is set on all nodes it is unset.
1419          * If the flag is not set on all nodes, it is set.
1420          */
1421         for (node = snode->edittree->nodes.first; node; node = node->next) {
1422                 if (node->flag & SELECT) {
1423                         
1424                         if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0)
1425                                 continue;
1426                         if (toggle_flag == NODE_OPTIONS && !(node->typeinfo->uifunc || node->typeinfo->uifuncbut))
1427                                 continue;
1428                         
1429                         if (node->flag & toggle_flag)
1430                                 tot_eq++;
1431                         else
1432                                 tot_neq++;
1433                 }
1434         }
1435         for (node = snode->edittree->nodes.first; node; node = node->next) {
1436                 if (node->flag & SELECT) {
1437                         
1438                         if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0)
1439                                 continue;
1440                         if (toggle_flag == NODE_OPTIONS && !(node->typeinfo->uifunc || node->typeinfo->uifuncbut))
1441                                 continue;
1442                         
1443                         if ((tot_eq && tot_neq) || tot_eq == 0)
1444                                 node->flag |= toggle_flag;
1445                         else
1446                                 node->flag &= ~toggle_flag;
1447                 }
1448         }
1449 }
1450
1451 static int node_hide_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1452 {
1453         SpaceNode *snode = CTX_wm_space_node(C);
1454         
1455         /* sanity checking (poll callback checks this already) */
1456         if ((snode == NULL) || (snode->edittree == NULL))
1457                 return OPERATOR_CANCELLED;
1458         
1459         node_flag_toggle_exec(snode, NODE_HIDDEN);
1460
1461         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1462
1463         return OPERATOR_FINISHED;
1464 }
1465
1466 void NODE_OT_hide_toggle(wmOperatorType *ot)
1467 {
1468         /* identifiers */
1469         ot->name = "Hide";
1470         ot->description = "Toggle hiding of selected nodes";
1471         ot->idname = "NODE_OT_hide_toggle";
1472         
1473         /* callbacks */
1474         ot->exec = node_hide_toggle_exec;
1475         ot->poll = ED_operator_node_active;
1476
1477         /* flags */
1478         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1479 }
1480
1481 static int node_preview_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1482 {
1483         SpaceNode *snode = CTX_wm_space_node(C);
1484
1485         /* sanity checking (poll callback checks this already) */
1486         if ((snode == NULL) || (snode->edittree == NULL))
1487                 return OPERATOR_CANCELLED;
1488
1489         ED_preview_kill_jobs(C);
1490
1491         node_flag_toggle_exec(snode, NODE_PREVIEW);
1492
1493         snode_notify(C, snode);
1494
1495         return OPERATOR_FINISHED;
1496 }
1497
1498 void NODE_OT_preview_toggle(wmOperatorType *ot)
1499 {
1500         /* identifiers */
1501         ot->name = "Toggle Node Preview";
1502         ot->description = "Toggle preview display for selected nodes";
1503         ot->idname = "NODE_OT_preview_toggle";
1504
1505         /* callbacks */
1506         ot->exec = node_preview_toggle_exec;
1507         ot->poll = ED_operator_node_active;
1508
1509         /* flags */
1510         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1511 }
1512
1513 static int node_options_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1514 {
1515         SpaceNode *snode = CTX_wm_space_node(C);
1516
1517         /* sanity checking (poll callback checks this already) */
1518         if ((snode == NULL) || (snode->edittree == NULL))
1519                 return OPERATOR_CANCELLED;
1520
1521         node_flag_toggle_exec(snode, NODE_OPTIONS);
1522
1523         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1524
1525         return OPERATOR_FINISHED;
1526 }
1527
1528 void NODE_OT_options_toggle(wmOperatorType *ot)
1529 {
1530         /* identifiers */
1531         ot->name = "Toggle Node Options";
1532         ot->description = "Toggle option buttons display for selected nodes";
1533         ot->idname = "NODE_OT_options_toggle";
1534
1535         /* callbacks */
1536         ot->exec = node_options_toggle_exec;
1537         ot->poll = ED_operator_node_active;
1538
1539         /* flags */
1540         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1541 }
1542
1543 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1544 {
1545         SpaceNode *snode = CTX_wm_space_node(C);
1546         bNode *node;
1547         int hidden;
1548
1549         /* sanity checking (poll callback checks this already) */
1550         if ((snode == NULL) || (snode->edittree == NULL))
1551                 return OPERATOR_CANCELLED;
1552
1553         ED_preview_kill_jobs(C);
1554
1555         /* Toggle for all selected nodes */
1556         hidden = 0;
1557         for (node = snode->edittree->nodes.first; node; node = node->next) {
1558                 if (node->flag & SELECT) {
1559                         if (node_has_hidden_sockets(node)) {
1560                                 hidden = 1;
1561                                 break;
1562                         }
1563                 }
1564         }
1565         
1566         for (node = snode->edittree->nodes.first; node; node = node->next) {
1567                 if (node->flag & SELECT) {
1568                         node_set_hidden_sockets(snode, node, !hidden);
1569                 }
1570         }
1571
1572         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1573
1574         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1575
1576         return OPERATOR_FINISHED;
1577 }
1578
1579 void NODE_OT_hide_socket_toggle(wmOperatorType *ot)
1580 {
1581         /* identifiers */
1582         ot->name = "Toggle Hidden Node Sockets";
1583         ot->description = "Toggle unused node socket display";
1584         ot->idname = "NODE_OT_hide_socket_toggle";
1585
1586         /* callbacks */
1587         ot->exec = node_socket_toggle_exec;
1588         ot->poll = ED_operator_node_active;
1589
1590         /* flags */
1591         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1592 }
1593
1594 /* ****************** Mute operator *********************** */
1595
1596 static int node_mute_exec(bContext *C, wmOperator *UNUSED(op))
1597 {
1598         SpaceNode *snode = CTX_wm_space_node(C);
1599         bNode *node;
1600
1601         ED_preview_kill_jobs(C);
1602
1603         for (node = snode->edittree->nodes.first; node; node = node->next) {
1604                 /* Only allow muting of nodes having a mute func! */
1605                 if ((node->flag & SELECT) && node->typeinfo->update_internal_links) {
1606                         node->flag ^= NODE_MUTED;
1607                         snode_update(snode, node);
1608                 }
1609         }
1610         
1611         snode_notify(C, snode);
1612         snode_dag_update(C, snode);
1613         
1614         return OPERATOR_FINISHED;
1615 }
1616
1617 void NODE_OT_mute_toggle(wmOperatorType *ot)
1618 {
1619         /* identifiers */
1620         ot->name = "Toggle Node Mute";
1621         ot->description = "Toggle muting of the nodes";
1622         ot->idname = "NODE_OT_mute_toggle";
1623         
1624         /* callbacks */
1625         ot->exec = node_mute_exec;
1626         ot->poll = ED_operator_node_editable;
1627         
1628         /* flags */
1629         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1630 }
1631
1632 /* ****************** Delete operator ******************* */
1633
1634 static int node_delete_exec(bContext *C, wmOperator *UNUSED(op))
1635 {
1636         SpaceNode *snode = CTX_wm_space_node(C);
1637         bNode *node, *next;
1638         
1639         ED_preview_kill_jobs(C);
1640
1641         for (node = snode->edittree->nodes.first; node; node = next) {
1642                 next = node->next;
1643                 if (node->flag & SELECT) {
1644                         /* check id user here, nodeFreeNode is called for free dbase too */
1645                         if (node->id)
1646                                 node->id->us--;
1647                         nodeFreeNode(snode->edittree, node);
1648                 }
1649         }
1650         
1651         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1652
1653         snode_notify(C, snode);
1654         snode_dag_update(C, snode);
1655         
1656         return OPERATOR_FINISHED;
1657 }
1658
1659 void NODE_OT_delete(wmOperatorType *ot)
1660 {
1661         /* identifiers */
1662         ot->name = "Delete";
1663         ot->description = "Delete selected nodes";
1664         ot->idname = "NODE_OT_delete";
1665         
1666         /* api callbacks */
1667         ot->exec = node_delete_exec;
1668         ot->poll = ED_operator_node_editable;
1669         
1670         /* flags */
1671         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1672 }
1673
1674 /* ****************** Delete with reconnect ******************* */
1675 static int node_delete_reconnect_exec(bContext *C, wmOperator *UNUSED(op))
1676 {
1677         SpaceNode *snode = CTX_wm_space_node(C);
1678         bNode *node, *next;
1679
1680         ED_preview_kill_jobs(C);
1681
1682         for (node = snode->edittree->nodes.first; node; node = next) {
1683                 next = node->next;
1684                 if (node->flag & SELECT) {
1685                         nodeInternalRelink(snode->edittree, node);
1686                         
1687                         /* check id user here, nodeFreeNode is called for free dbase too */
1688                         if (node->id)
1689                                 node->id->us--;
1690                         nodeFreeNode(snode->edittree, node);
1691                 }
1692         }
1693
1694         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1695
1696         snode_notify(C, snode);
1697         snode_dag_update(C, snode);
1698
1699         return OPERATOR_FINISHED;
1700 }
1701
1702 void NODE_OT_delete_reconnect(wmOperatorType *ot)
1703 {
1704         /* identifiers */
1705         ot->name = "Delete with Reconnect";
1706         ot->description = "Delete nodes; will reconnect nodes as if deletion was muted";
1707         ot->idname = "NODE_OT_delete_reconnect";
1708
1709         /* api callbacks */
1710         ot->exec = node_delete_reconnect_exec;
1711         ot->poll = ED_operator_node_editable;
1712
1713         /* flags */
1714         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1715 }
1716
1717
1718 /* ****************** File Output Add Socket  ******************* */
1719
1720 static int node_output_file_add_socket_exec(bContext *C, wmOperator *op)
1721 {
1722         Scene *scene = CTX_data_scene(C);
1723         SpaceNode *snode = CTX_wm_space_node(C);
1724         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1725         bNodeTree *ntree = NULL;
1726         bNode *node = NULL;
1727         char file_path[MAX_NAME];
1728
1729         if (ptr.data) {
1730                 node = ptr.data;
1731                 ntree = ptr.id.data;
1732         }
1733         else if (snode && snode->edittree) {
1734                 ntree = snode->edittree;
1735                 node = nodeGetActive(snode->edittree);
1736         }
1737
1738         if (!node)
1739                 return OPERATOR_CANCELLED;
1740
1741         RNA_string_get(op->ptr, "file_path", file_path);
1742         ntreeCompositOutputFileAddSocket(ntree, node, file_path, &scene->r.im_format);
1743
1744         snode_notify(C, snode);
1745
1746         return OPERATOR_FINISHED;
1747 }
1748
1749 void NODE_OT_output_file_add_socket(wmOperatorType *ot)
1750 {
1751         /* identifiers */
1752         ot->name = "Add File Node Socket";
1753         ot->description = "Add a new input to a file output node";
1754         ot->idname = "NODE_OT_output_file_add_socket";
1755
1756         /* callbacks */
1757         ot->exec = node_output_file_add_socket_exec;
1758         ot->poll = composite_node_editable;
1759
1760         /* flags */
1761         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1762
1763         RNA_def_string(ot->srna, "file_path", "Image", MAX_NAME, "File Path", "Sub-path of the output file");
1764 }
1765
1766 /* ****************** Multi File Output Remove Socket  ******************* */
1767
1768 static int node_output_file_remove_active_socket_exec(bContext *C, wmOperator *UNUSED(op))
1769 {
1770         SpaceNode *snode = CTX_wm_space_node(C);
1771         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1772         bNodeTree *ntree = NULL;
1773         bNode *node = NULL;
1774         
1775         if (ptr.data) {
1776                 node = ptr.data;
1777                 ntree = ptr.id.data;
1778         }
1779         else if (snode && snode->edittree) {
1780                 ntree = snode->edittree;
1781                 node = nodeGetActive(snode->edittree);
1782         }
1783
1784         if (!node)
1785                 return OPERATOR_CANCELLED;
1786         
1787         if (!ntreeCompositOutputFileRemoveActiveSocket(ntree, node))
1788                 return OPERATOR_CANCELLED;
1789         
1790         snode_notify(C, snode);
1791         
1792         return OPERATOR_FINISHED;
1793 }
1794
1795 void NODE_OT_output_file_remove_active_socket(wmOperatorType *ot)
1796 {
1797         /* identifiers */
1798         ot->name = "Remove File Node Socket";
1799         ot->description = "Remove active input from a file output node";
1800         ot->idname = "NODE_OT_output_file_remove_active_socket";
1801         
1802         /* callbacks */
1803         ot->exec = node_output_file_remove_active_socket_exec;
1804         ot->poll = composite_node_editable;
1805         
1806         /* flags */
1807         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1808 }
1809
1810 /* ****************** Multi File Output Move Socket  ******************* */
1811
1812 static int node_output_file_move_active_socket_exec(bContext *C, wmOperator *op)
1813 {
1814         SpaceNode *snode = CTX_wm_space_node(C);
1815         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1816         bNode *node = NULL;
1817         NodeImageMultiFile *nimf;
1818         bNodeSocket *sock;
1819         int direction;
1820         
1821         if (ptr.data)
1822                 node = ptr.data;
1823         else if (snode && snode->edittree)
1824                 node = nodeGetActive(snode->edittree);
1825
1826         if (!node)
1827                 return OPERATOR_CANCELLED;
1828
1829         nimf = node->storage;
1830         
1831         sock = BLI_findlink(&node->inputs, nimf->active_input);
1832         if (!sock)
1833                 return OPERATOR_CANCELLED;
1834         
1835         direction = RNA_enum_get(op->ptr, "direction");
1836         
1837         if (direction == 1) {
1838                 bNodeSocket *before = sock->prev;
1839                 if (!before)
1840                         return OPERATOR_CANCELLED;
1841                 BLI_remlink(&node->inputs, sock);
1842                 BLI_insertlinkbefore(&node->inputs, before, sock);
1843                 nimf->active_input--;
1844         }
1845         else {
1846                 bNodeSocket *after = sock->next;
1847                 if (!after)
1848                         return OPERATOR_CANCELLED;
1849                 BLI_remlink(&node->inputs, sock);
1850                 BLI_insertlinkafter(&node->inputs, after, sock);
1851                 nimf->active_input++;
1852         }
1853         
1854         snode_notify(C, snode);
1855         
1856         return OPERATOR_FINISHED;
1857 }
1858
1859 void NODE_OT_output_file_move_active_socket(wmOperatorType *ot)
1860 {
1861         static EnumPropertyItem direction_items[] = {
1862                 {1, "UP", 0, "Up", ""},
1863                 {2, "DOWN", 0, "Down", ""},
1864                 { 0, NULL, 0, NULL, NULL }
1865         };
1866         
1867         /* identifiers */
1868         ot->name = "Move File Node Socket";
1869         ot->description = "Move the active input of a file output node up or down the list";
1870         ot->idname = "NODE_OT_output_file_move_active_socket";
1871         
1872         /* callbacks */
1873         ot->exec = node_output_file_move_active_socket_exec;
1874         ot->poll = composite_node_editable;
1875         
1876         /* flags */
1877         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1878         
1879         RNA_def_enum(ot->srna, "direction", direction_items, 2, "Direction", "");
1880 }
1881
1882 /* ****************** Copy Node Color ******************* */
1883
1884 static int node_copy_color_exec(bContext *C, wmOperator *UNUSED(op))
1885 {
1886         SpaceNode *snode = CTX_wm_space_node(C);
1887         bNodeTree *ntree = snode->edittree;
1888         bNode *node, *tnode;
1889         
1890         if (!ntree)
1891                 return OPERATOR_CANCELLED;
1892         node = nodeGetActive(ntree);
1893         if (!node)
1894                 return OPERATOR_CANCELLED;
1895         
1896         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) {
1897                 if (tnode->flag & NODE_SELECT && tnode != node) {
1898                         if (node->flag & NODE_CUSTOM_COLOR) {
1899                                 tnode->flag |= NODE_CUSTOM_COLOR;
1900                                 copy_v3_v3(tnode->color, node->color);
1901                         }
1902                         else
1903                                 tnode->flag &= ~NODE_CUSTOM_COLOR;
1904                 }
1905         }
1906
1907         ED_node_sort(ntree);
1908         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1909
1910         return OPERATOR_FINISHED;
1911 }
1912
1913 void NODE_OT_node_copy_color(wmOperatorType *ot)
1914 {
1915         /* identifiers */
1916         ot->name = "Copy Color";
1917         ot->description = "Copy color to all selected nodes";
1918         ot->idname = "NODE_OT_node_copy_color";
1919
1920         /* api callbacks */
1921         ot->exec = node_copy_color_exec;
1922         ot->poll = ED_operator_node_editable;
1923
1924         /* flags */
1925         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1926 }
1927
1928 /* ****************** Copy to clipboard ******************* */
1929
1930 static int node_clipboard_copy_exec(bContext *C, wmOperator *UNUSED(op))
1931 {
1932         SpaceNode *snode = CTX_wm_space_node(C);
1933         bNodeTree *ntree = snode->edittree;
1934         bNode *node;
1935         bNodeLink *link, *newlink;
1936
1937         ED_preview_kill_jobs(C);
1938
1939         /* clear current clipboard */
1940         BKE_node_clipboard_clear();
1941         BKE_node_clipboard_init(ntree);
1942
1943         for (node = ntree->nodes.first; node; node = node->next) {
1944                 if (node->flag & SELECT) {
1945                         bNode *new_node;
1946                         new_node = nodeCopyNode(NULL, node);
1947                         BKE_node_clipboard_add_node(new_node);
1948                 }
1949         }
1950
1951         for (node = ntree->nodes.first; node; node = node->next) {
1952                 if (node->flag & SELECT) {
1953                         bNode *new_node = node->new_node;
1954                         
1955                         /* ensure valid pointers */
1956                         if (new_node->parent) {
1957                                 /* parent pointer must be redirected to new node or detached if parent is not copied */
1958                                 if (new_node->parent->flag & NODE_SELECT) {
1959                                         new_node->parent = new_node->parent->new_node;
1960                                 }
1961                                 else {
1962                                         nodeDetachNode(new_node);
1963                                 }
1964                         }
1965                 }
1966         }
1967
1968         /* copy links between selected nodes
1969          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
1970          */
1971         for (link = ntree->links.first; link; link = link->next) {
1972                 /* This creates new links between copied nodes. */
1973                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
1974                     link->fromnode && (link->fromnode->flag & NODE_SELECT))
1975                 {
1976                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
1977                         newlink->flag = link->flag;
1978                         newlink->tonode = link->tonode->new_node;
1979                         newlink->tosock = link->tosock->new_sock;
1980                         newlink->fromnode = link->fromnode->new_node;
1981                         newlink->fromsock = link->fromsock->new_sock;
1982
1983                         BKE_node_clipboard_add_link(newlink);
1984                 }
1985         }
1986
1987         return OPERATOR_FINISHED;
1988 }
1989
1990 void NODE_OT_clipboard_copy(wmOperatorType *ot)
1991 {
1992         /* identifiers */
1993         ot->name = "Copy to Clipboard";
1994         ot->description = "Copies selected nodes to the clipboard";
1995         ot->idname = "NODE_OT_clipboard_copy";
1996
1997         /* api callbacks */
1998         ot->exec = node_clipboard_copy_exec;
1999         ot->poll = ED_operator_node_active;
2000
2001         /* flags */
2002         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2003 }
2004
2005 /* ****************** Paste from clipboard ******************* */
2006
2007 static int node_clipboard_paste_exec(bContext *C, wmOperator *op)
2008 {
2009         SpaceNode *snode = CTX_wm_space_node(C);
2010         bNodeTree *ntree = snode->edittree;
2011         const ListBase *clipboard_nodes_lb;
2012         const ListBase *clipboard_links_lb;
2013         bNode *node;
2014         bNodeLink *link;
2015         int num_nodes;
2016         float center[2];
2017         int is_clipboard_valid, all_nodes_valid;
2018
2019         /* validate pointers in the clipboard */
2020         is_clipboard_valid = BKE_node_clipboard_validate();
2021         clipboard_nodes_lb = BKE_node_clipboard_get_nodes();
2022         clipboard_links_lb = BKE_node_clipboard_get_links();
2023
2024         if (clipboard_nodes_lb->first == NULL) {
2025                 BKE_report(op->reports, RPT_ERROR, "Clipboard is empty");
2026                 return OPERATOR_CANCELLED;
2027         }
2028
2029         if (BKE_node_clipboard_get_type() != ntree->type) {
2030                 BKE_report(op->reports, RPT_ERROR, "Clipboard nodes are an incompatible type");
2031                 return OPERATOR_CANCELLED;
2032         }
2033
2034         /* only warn */
2035         if (is_clipboard_valid == FALSE) {
2036                 BKE_report(op->reports, RPT_WARNING, "Some nodes references could not be restored, will be left empty");
2037         }
2038
2039         /* make sure all clipboard nodes would be valid in the target tree */
2040         all_nodes_valid = TRUE;
2041         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2042                 if (!node->typeinfo->poll_instance(node, ntree)) {
2043                         all_nodes_valid = FALSE;
2044                         BKE_reportf(op->reports, RPT_ERROR, "Cannot add node %s into node tree %s", node->name, ntree->id.name + 2);
2045                 }
2046         }
2047         if (!all_nodes_valid)
2048                 return OPERATOR_CANCELLED;
2049
2050         ED_preview_kill_jobs(C);
2051
2052         /* deselect old nodes */
2053         node_deselect_all(snode);
2054
2055         /* calculate "barycenter" for placing on mouse cursor */
2056         zero_v2(center);
2057         for (node = clipboard_nodes_lb->first, num_nodes = 0; node; node = node->next, num_nodes++) {
2058                 center[0] += BLI_rctf_cent_x(&node->totr);
2059                 center[1] += BLI_rctf_cent_y(&node->totr);
2060         }
2061         mul_v2_fl(center, 1.0 / num_nodes);
2062
2063         /* copy nodes from clipboard */
2064         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2065                 bNode *new_node = nodeCopyNode(ntree, node);
2066
2067                 /* needed since nodeCopyNode() doesn't increase ID's */
2068                 id_us_plus(node->id);
2069
2070                 /* pasted nodes are selected */
2071                 nodeSetSelected(new_node, TRUE);
2072         }
2073         
2074         /* reparent copied nodes */
2075         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2076                 bNode *new_node = node->new_node;
2077                 if (new_node->parent)
2078                         new_node->parent = new_node->parent->new_node;
2079         }
2080
2081         for (link = clipboard_links_lb->first; link; link = link->next) {
2082                 nodeAddLink(ntree, link->fromnode->new_node, link->fromsock->new_sock,
2083                             link->tonode->new_node, link->tosock->new_sock);
2084         }
2085
2086         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
2087
2088         snode_notify(C, snode);
2089         snode_dag_update(C, snode);
2090
2091         return OPERATOR_FINISHED;
2092 }
2093
2094 static int node_clipboard_paste_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2095 {
2096         ARegion *ar = CTX_wm_region(C);
2097         SpaceNode *snode = CTX_wm_space_node(C);
2098
2099         /* convert mouse coordinates to v2d space */
2100         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &snode->cursor[0], &snode->cursor[1]);
2101
2102         return node_clipboard_paste_exec(C, op);
2103 }
2104
2105 void NODE_OT_clipboard_paste(wmOperatorType *ot)
2106 {
2107         /* identifiers */
2108         ot->name = "Paste from Clipboard";
2109         ot->description = "Pastes nodes from the clipboard to the active node tree";
2110         ot->idname = "NODE_OT_clipboard_paste";
2111
2112         /* api callbacks */
2113         ot->exec = node_clipboard_paste_exec;
2114         ot->invoke = node_clipboard_paste_invoke;
2115         ot->poll = ED_operator_node_editable;
2116
2117         /* flags */
2118         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2119 }
2120
2121 /********************** Add interface socket operator *********************/
2122
2123 static bNodeSocket *ntree_get_active_interface_socket(ListBase *lb)
2124 {
2125         bNodeSocket *sock;
2126         for (sock = lb->first; sock; sock = sock->next)
2127                 if (sock->flag & SELECT)
2128                         return sock;
2129         return NULL;
2130 }
2131
2132 static int ntree_socket_add_exec(bContext *C, wmOperator *op)
2133 {
2134         SpaceNode *snode = CTX_wm_space_node(C);
2135         bNodeTree *ntree = snode->edittree;
2136         int in_out = RNA_enum_get(op->ptr, "in_out");
2137         PointerRNA ntree_ptr;
2138         bNodeSocket *sock, *tsock, *active_sock;
2139         const char *default_name;
2140         
2141         RNA_id_pointer_create((ID *)ntree, &ntree_ptr);
2142         
2143         if (in_out == SOCK_IN) {
2144                 active_sock = ntree_get_active_interface_socket(&ntree->inputs);
2145                 default_name = "Input";
2146         }
2147         else {
2148                 active_sock = ntree_get_active_interface_socket(&ntree->outputs);
2149                 default_name = "Output";
2150         }
2151         
2152         if (active_sock) {
2153                 /* insert a copy of the active socket right after it */
2154                 sock = ntreeInsertSocketInterface(ntree, in_out, active_sock->idname, active_sock->next, active_sock->name);
2155                 /* XXX this only works for actual sockets, not interface templates! */
2156                 /*nodeSocketCopyValue(sock, &ntree_ptr, active_sock, &ntree_ptr);*/
2157         }
2158         else {
2159                 /* XXX TODO define default socket type for a tree! */
2160                 sock = ntreeAddSocketInterface(ntree, in_out, "NodeSocketFloat", default_name);
2161         }
2162         
2163         /* deactivate sockets (has to check both lists) */
2164         for (tsock = ntree->inputs.first; tsock; tsock = tsock->next)
2165                 tsock->flag &= ~SELECT;
2166         for (tsock = ntree->outputs.first; tsock; tsock = tsock->next)
2167                 tsock->flag &= ~SELECT;
2168         /* make the new socket active */
2169         sock->flag |= SELECT;
2170         
2171         ntreeUpdateTree(CTX_data_main(C), ntree);
2172
2173         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2174         
2175         return OPERATOR_FINISHED;
2176 }
2177
2178 void NODE_OT_tree_socket_add(wmOperatorType *ot)
2179 {
2180         /* identifiers */
2181         ot->name = "Add Node Tree Interface Socket";
2182         ot->description = "Add an input or output socket to the current node tree";
2183         ot->idname = "NODE_OT_tree_socket_add";
2184         
2185         /* api callbacks */
2186         ot->exec = ntree_socket_add_exec;
2187         ot->poll = ED_operator_node_editable;
2188         
2189         /* flags */
2190         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2191         
2192         RNA_def_enum(ot->srna, "in_out", node_socket_in_out_items, SOCK_IN, "Socket Type", "");
2193 }
2194
2195 /********************** Remove interface socket operator *********************/
2196
2197 static int ntree_socket_remove_exec(bContext *C, wmOperator *UNUSED(op))
2198 {
2199         SpaceNode *snode = CTX_wm_space_node(C);
2200         bNodeTree *ntree = snode->edittree;
2201         bNodeSocket *iosock, *active_sock;
2202         
2203         iosock = ntree_get_active_interface_socket(&ntree->inputs);
2204         if (!iosock)
2205                 iosock = ntree_get_active_interface_socket(&ntree->outputs);
2206         if (!iosock)
2207                 return OPERATOR_CANCELLED;
2208         
2209         /* preferably next socket becomes active, otherwise try previous socket */
2210         active_sock = (iosock->next ? iosock->next : iosock->prev);
2211         ntreeRemoveSocketInterface(ntree, iosock);
2212         
2213         /* set active socket */
2214         if (active_sock)
2215                 active_sock->flag |= SELECT;
2216         
2217         ntreeUpdateTree(CTX_data_main(C), ntree);
2218
2219         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2220         
2221         return OPERATOR_FINISHED;
2222 }
2223
2224 void NODE_OT_tree_socket_remove(wmOperatorType *ot)
2225 {
2226         /* identifiers */
2227         ot->name = "Remove Node Tree Interface Socket";
2228         ot->description = "Remove an input or output socket to the current node tree";
2229         ot->idname = "NODE_OT_tree_socket_remove";
2230         
2231         /* api callbacks */
2232         ot->exec = ntree_socket_remove_exec;
2233         ot->poll = ED_operator_node_editable;
2234         
2235         /* flags */
2236         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2237 }
2238
2239 /********************** Move interface socket operator *********************/
2240
2241 static EnumPropertyItem move_direction_items[] = {
2242         { 1, "UP", 0, "Up", "" },
2243         { 2, "DOWN", 0, "Down", "" },
2244         { 0, NULL, 0, NULL, NULL },
2245 };
2246
2247 static int ntree_socket_move_exec(bContext *C, wmOperator *op)
2248 {
2249         SpaceNode *snode = CTX_wm_space_node(C);
2250         bNodeTree *ntree = snode->edittree;
2251         int direction = RNA_enum_get(op->ptr, "direction");
2252         bNodeSocket *iosock;
2253         ListBase *lb;
2254         
2255         lb = &ntree->inputs;
2256         iosock = ntree_get_active_interface_socket(lb);
2257         if (!iosock) {
2258                 lb = &ntree->outputs;
2259                 iosock = ntree_get_active_interface_socket(lb);
2260         }
2261         if (!iosock)
2262                 return OPERATOR_CANCELLED;
2263         
2264         switch (direction) {
2265                 case 1:
2266                 {       /* up */
2267                         bNodeSocket *before = iosock->prev;
2268                         BLI_remlink(lb, iosock);
2269                         if (before)
2270                                 BLI_insertlinkbefore(lb, before, iosock);
2271                         else
2272                                 BLI_addhead(lb, iosock);
2273                         break;
2274                 }
2275                 case 2:
2276                 {       /* down */
2277                         bNodeSocket *after = iosock->next;
2278                         BLI_remlink(lb, iosock);
2279                         if (after)
2280                                 BLI_insertlinkafter(lb, after, iosock);
2281                         else
2282                                 BLI_addtail(lb, iosock);
2283                         break;
2284                 }
2285         }
2286         
2287         ntreeUpdateTree(CTX_data_main(C), ntree);
2288
2289         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2290         
2291         return OPERATOR_FINISHED;
2292 }
2293
2294 void NODE_OT_tree_socket_move(wmOperatorType *ot)
2295 {
2296         /* identifiers */
2297         ot->name = "Move Node Tree Socket";
2298         ot->description = "Move a socket up or down in the current node tree's sockets stack";
2299         ot->idname = "NODE_OT_tree_socket_move";
2300         
2301         /* api callbacks */
2302         ot->exec = ntree_socket_move_exec;
2303         ot->poll = ED_operator_node_editable;
2304         
2305         /* flags */
2306         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2307         
2308         RNA_def_enum(ot->srna, "direction", move_direction_items, 1, "Direction", "");
2309 }
2310
2311 /* ********************** Shader Script Update ******************/
2312
2313 static int node_shader_script_update_poll(bContext *C)
2314 {
2315         Scene *scene = CTX_data_scene(C);
2316         RenderEngineType *type = RE_engines_find(scene->r.engine);
2317         SpaceNode *snode = CTX_wm_space_node(C);
2318         bNode *node;
2319         Text *text;
2320
2321         /* test if we have a render engine that supports shaders scripts */
2322         if (!(type && type->update_script_node))
2323                 return 0;
2324
2325         /* see if we have a shader script node in context */
2326         node = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript).data;
2327
2328         if (!node && snode && snode->edittree)
2329                 node = nodeGetActive(snode->edittree);
2330
2331         if (node && node->type == SH_NODE_SCRIPT) {
2332                 NodeShaderScript *nss = node->storage;
2333
2334                 if (node->id || nss->filepath[0]) {
2335                         return ED_operator_node_editable(C);
2336                 }
2337         }
2338
2339         /* see if we have a text datablock in context */
2340         text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2341         if (text)
2342                 return 1;
2343
2344         /* we don't check if text datablock is actually in use, too slow for poll */
2345
2346         return 0;
2347 }
2348
2349 /* recursively check for script nodes in groups using this text and update */
2350 static int node_shader_script_update_text_recursive(RenderEngine *engine, RenderEngineType *type, bNodeTree *ntree, Text *text)
2351 {
2352         int found = FALSE;
2353         bNode *node;
2354         
2355         ntree->done = TRUE;
2356         
2357         /* update each script that is using this text datablock */
2358         for (node = ntree->nodes.first; node; node = node->next) {
2359                 if (node->type == NODE_GROUP) {
2360                         bNodeTree *ngroup = (bNodeTree *)node->id;
2361                         if (ngroup && !ngroup->done)
2362                                 found |= node_shader_script_update_text_recursive(engine, type, ngroup, text);
2363                 }
2364                 else if (node->type == SH_NODE_SCRIPT && node->id == &text->id) {
2365                         type->update_script_node(engine, ntree, node);
2366                         found = TRUE;
2367                 }
2368         }
2369         
2370         return found;
2371 }
2372
2373 static int node_shader_script_update_exec(bContext *C, wmOperator *op)
2374 {
2375         Main *bmain = CTX_data_main(C);
2376         Scene *scene = CTX_data_scene(C);
2377         SpaceNode *snode = CTX_wm_space_node(C);
2378         PointerRNA nodeptr = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript);
2379         bNodeTree *ntree = NULL;
2380         bNode *node = NULL;
2381         RenderEngine *engine;
2382         RenderEngineType *type;
2383         int found = FALSE;
2384
2385         /* setup render engine */
2386         type = RE_engines_find(scene->r.engine);
2387         engine = RE_engine_create(type);
2388         engine->reports = op->reports;
2389
2390         /* get node */
2391         if (nodeptr.data) {
2392                 ntree = nodeptr.id.data;
2393                 node = nodeptr.data;
2394         }
2395         else if (snode && snode->edittree) {
2396                 ntree = snode->edittree;
2397                 node = nodeGetActive(snode->edittree);
2398         }
2399
2400         if (node) {
2401                 /* update single node */
2402                 type->update_script_node(engine, ntree, node);
2403
2404                 found = TRUE;
2405         }
2406         else {
2407                 /* update all nodes using text datablock */
2408                 Text *text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2409
2410                 if (text) {
2411                         /* clear flags for recursion check */
2412                         FOREACH_NODETREE(bmain, ntree, id) {
2413                                 if (ntree->type == NTREE_SHADER)
2414                                         ntree->done = FALSE;
2415                         } FOREACH_NODETREE_END
2416                         
2417                         FOREACH_NODETREE(bmain, ntree, id) {
2418                                 if (ntree->type == NTREE_SHADER) {
2419                                         if (!ntree->done)
2420                                                 found |= node_shader_script_update_text_recursive(engine, type, ntree, text);
2421                                 }
2422                         } FOREACH_NODETREE_END
2423
2424                         if (!found)
2425                                 BKE_report(op->reports, RPT_INFO, "Text not used by any node, no update done");
2426                 }
2427         }
2428
2429         RE_engine_free(engine);
2430
2431         return (found) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2432 }
2433
2434 void NODE_OT_shader_script_update(wmOperatorType *ot)
2435 {
2436         /* identifiers */
2437         ot->name = "Script Node Update";
2438         ot->description = "Update shader script node with new sockets and options from the script";
2439         ot->idname = "NODE_OT_shader_script_update";
2440
2441         /* api callbacks */
2442         ot->exec = node_shader_script_update_exec;
2443         ot->poll = node_shader_script_update_poll;
2444
2445         /* flags */
2446         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2447 }
2448
2449 /* ********************** Viewer border ******************/
2450
2451 static void viewer_border_corner_to_backdrop(SpaceNode *snode, ARegion *ar, int x, int y,
2452                                              int backdrop_width, int backdrop_height,
2453                                              float *fx, float *fy)
2454 {
2455         float bufx, bufy;
2456
2457         bufx = backdrop_width * snode->zoom;
2458         bufy = backdrop_height * snode->zoom;
2459
2460         *fx = (bufx > 0.0f ? ((float) x - 0.5f * ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
2461         *fy = (bufy > 0.0f ? ((float) y - 0.5f * ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
2462 }
2463
2464 static int viewer_border_exec(bContext *C, wmOperator *op)
2465 {
2466         Image *ima;
2467         void *lock;
2468         ImBuf *ibuf;
2469
2470         ED_preview_kill_jobs(C);
2471
2472         ima = BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
2473         ibuf = BKE_image_acquire_ibuf(ima, NULL, &lock);
2474
2475         if (ibuf) {
2476                 ARegion *ar = CTX_wm_region(C);
2477                 SpaceNode *snode = CTX_wm_space_node(C);
2478                 bNodeTree *btree = snode->nodetree;
2479                 rcti rect;
2480                 rctf rectf;
2481
2482                 /* get border from operator */
2483                 WM_operator_properties_border_to_rcti(op, &rect);
2484
2485                 /* convert border to unified space within backdrop image */
2486                 viewer_border_corner_to_backdrop(snode, ar, rect.xmin, rect.ymin, ibuf->x, ibuf->y,
2487                                                  &rectf.xmin, &rectf.ymin);
2488
2489                 viewer_border_corner_to_backdrop(snode, ar, rect.xmax, rect.ymax, ibuf->x, ibuf->y,
2490                                                  &rectf.xmax, &rectf.ymax);
2491
2492                 /* clamp coordinates */
2493                 rectf.xmin = max_ff(rectf.xmin, 0.0f);
2494                 rectf.ymin = max_ff(rectf.ymin, 0.0f);
2495                 rectf.xmax = min_ff(rectf.xmax, 1.0f);
2496                 rectf.ymax = min_ff(rectf.ymax, 1.0f);
2497
2498                 if (rectf.xmin < rectf.xmax && rectf.ymin < rectf.ymax) {
2499                         btree->viewer_border = rectf;
2500
2501                         if (rectf.xmin == 0.0f && rectf.ymin == 0.0f &&
2502                             rectf.xmax == 1.0f && rectf.ymax == 1.0f)
2503                         {
2504                                 btree->flag &= ~NTREE_VIEWER_BORDER;
2505                         }
2506                         else {
2507                                 if (ibuf->rect)
2508                                         memset(ibuf->rect, 0, 4 * ibuf->x * ibuf->y);
2509
2510                                 if (ibuf->rect_float)
2511                                         memset(ibuf->rect_float, 0, 4 * ibuf->x * ibuf->y * sizeof(float));
2512
2513                                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
2514
2515                                 btree->flag |= NTREE_VIEWER_BORDER;
2516                         }
2517
2518                         snode_notify(C, snode);
2519                         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2520                 }
2521                 else {
2522                         btree->flag &= ~NTREE_VIEWER_BORDER;
2523                 }
2524         }
2525
2526         BKE_image_release_ibuf(ima, ibuf, lock);
2527
2528         return OPERATOR_FINISHED;
2529 }
2530
2531 void NODE_OT_viewer_border(wmOperatorType *ot)
2532 {
2533         /* identifiers */
2534         ot->name = "Viewer Border";
2535         ot->description = "Set the boundaries for viewer operations";
2536         ot->idname = "NODE_OT_viewer_border";
2537
2538         /* api callbacks */
2539         ot->invoke = WM_border_select_invoke;
2540         ot->exec = viewer_border_exec;
2541         ot->modal = WM_border_select_modal;
2542         ot->cancel = WM_border_select_cancel;
2543         ot->poll = composite_node_active;
2544
2545         /* flags */
2546         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2547
2548         /* properties */
2549         WM_operator_properties_gesture_border(ot, TRUE);
2550 }