f79d6e26f22bd779286cf276889c518918ba6f5c
[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_lamp_types.h"
35 #include "DNA_material_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_text_types.h"
38 #include "DNA_world_types.h"
39
40 #include "BLI_math.h"
41 #include "BLI_blenlib.h"
42
43 #include "BKE_context.h"
44 #include "BKE_depsgraph.h"
45 #include "BKE_global.h"
46 #include "BKE_image.h"
47 #include "BKE_library.h"
48 #include "BKE_main.h"
49 #include "BKE_node.h"
50 #include "BKE_report.h"
51 #include "BKE_scene.h"
52
53 #include "RE_engine.h"
54 #include "RE_pipeline.h"
55
56
57 #include "ED_node.h"  /* own include */
58 #include "ED_screen.h"
59 #include "ED_render.h"
60
61 #include "RNA_access.h"
62 #include "RNA_define.h"
63 #include "RNA_enum_types.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "UI_view2d.h"
69
70 #include "GPU_material.h"
71
72 #include "IMB_imbuf_types.h"
73
74 #include "node_intern.h"  /* own include */
75 #include "NOD_composite.h"
76 #include "NOD_shader.h"
77 #include "NOD_texture.h"
78
79
80 #define USE_ESC_COMPO
81
82 /* ***************** composite job manager ********************** */
83
84 enum {
85         COM_RECALC_COMPOSITE = 1,
86         COM_RECALC_VIEWER    = 2
87 };
88
89 typedef struct CompoJob {
90         Scene *scene;
91         bNodeTree *ntree;
92         bNodeTree *localtree;
93         const short *stop;
94         short *do_update;
95         float *progress;
96         short need_sync;
97         int recalc_flags;
98 } CompoJob;
99
100 static void compo_tag_output_nodes(bNodeTree *nodetree, int recalc_flags)
101 {
102         bNode *node;
103
104         for (node = nodetree->nodes.first; node; node = node->next) {
105                 if (node->type == CMP_NODE_COMPOSITE) {
106                         if (recalc_flags & COM_RECALC_COMPOSITE)
107                                 node->flag |= NODE_DO_OUTPUT_RECALC;
108                 }
109                 else if (node->type == CMP_NODE_VIEWER || node->type == CMP_NODE_SPLITVIEWER) {
110                         if (recalc_flags & COM_RECALC_VIEWER)
111                                 node->flag |= NODE_DO_OUTPUT_RECALC;
112                 }
113                 else if (node->type == NODE_GROUP) {
114                         if (node->id)
115                                 compo_tag_output_nodes((bNodeTree *)node->id, recalc_flags);
116                 }
117         }
118 }
119
120 static int compo_get_recalc_flags(const bContext *C)
121 {
122         wmWindowManager *wm = CTX_wm_manager(C);
123         wmWindow *win;
124         int recalc_flags = 0;
125
126         for (win = wm->windows.first; win; win = win->next) {
127                 bScreen *sc = win->screen;
128                 ScrArea *sa;
129
130                 for (sa = sc->areabase.first; sa; sa = sa->next) {
131                         if (sa->spacetype == SPACE_IMAGE) {
132                                 SpaceImage *sima = sa->spacedata.first;
133                                 if (sima->image) {
134                                         if (sima->image->type == IMA_TYPE_R_RESULT)
135                                                 recalc_flags |= COM_RECALC_COMPOSITE;
136                                         else if (sima->image->type == IMA_TYPE_COMPOSITE)
137                                                 recalc_flags |= COM_RECALC_VIEWER;
138                                 }
139                         }
140                         else if (sa->spacetype == SPACE_NODE) {
141                                 SpaceNode *snode = sa->spacedata.first;
142                                 if (snode->flag & SNODE_BACKDRAW)
143                                         recalc_flags |= COM_RECALC_VIEWER;
144                         }
145                 }
146         }
147
148         return recalc_flags;
149 }
150
151 /* called by compo, only to check job 'stop' value */
152 static int compo_breakjob(void *cjv)
153 {
154         CompoJob *cj = cjv;
155         
156         /* without G.is_break 'ESC' wont quit - which annoys users */
157         return (*(cj->stop)
158 #ifdef USE_ESC_COMPO
159                 ||
160                 G.is_break
161 #endif
162                 );
163 }
164
165 /* called by compo, wmJob sends notifier, old compositor system only */
166 static void compo_statsdrawjob(void *cjv, char *UNUSED(str))
167 {
168         CompoJob *cj = cjv;
169         
170         *(cj->do_update) = true;
171         cj->need_sync = true;
172 }
173
174 /* called by compo, wmJob sends notifier */
175 static void compo_redrawjob(void *cjv)
176 {
177         CompoJob *cj = cjv;
178         
179         *(cj->do_update) = true;
180 }
181
182 static void compo_freejob(void *cjv)
183 {
184         CompoJob *cj = cjv;
185
186         if (cj->localtree) {
187                 ntreeLocalMerge(cj->localtree, cj->ntree);
188         }
189         MEM_freeN(cj);
190 }
191
192 /* only now we copy the nodetree, so adding many jobs while
193  * sliding buttons doesn't frustrate */
194 static void compo_initjob(void *cjv)
195 {
196         CompoJob *cj = cjv;
197
198         cj->localtree = ntreeLocalize(cj->ntree);
199
200         if (cj->recalc_flags)
201                 compo_tag_output_nodes(cj->localtree, cj->recalc_flags);
202 }
203
204 /* called before redraw notifiers, it moves finished previews over */
205 static void compo_updatejob(void *cjv)
206 {
207         CompoJob *cj = cjv;
208
209         if (cj->need_sync) {
210                 /* was used by old compositor system only */
211                 ntreeLocalSync(cj->localtree, cj->ntree);
212
213                 cj->need_sync = false;
214         }
215
216         WM_main_add_notifier(NC_SCENE | ND_COMPO_RESULT, NULL);
217 }
218
219 static void compo_progressjob(void *cjv, float progress)
220 {
221         CompoJob *cj = cjv;
222         
223         *(cj->progress) = progress;
224 }
225
226
227 /* only this runs inside thread */
228 static void compo_startjob(void *cjv, short *stop, short *do_update, float *progress)
229 {
230         CompoJob *cj = cjv;
231         bNodeTree *ntree = cj->localtree;
232         Scene *scene = cj->scene;
233
234         if (scene->use_nodes == false)
235                 return;
236         
237         cj->stop = stop;
238         cj->do_update = do_update;
239         cj->progress = progress;
240
241         ntree->test_break = compo_breakjob;
242         ntree->tbh = cj;
243         ntree->stats_draw = compo_statsdrawjob;
244         ntree->sdh = cj;
245         ntree->progress = compo_progressjob;
246         ntree->prh = cj;
247         ntree->update_draw = compo_redrawjob;
248         ntree->udh = cj;
249
250         // XXX BIF_store_spare();
251         /* 1 is do_previews */
252         ntreeCompositExecTree(cj->scene, ntree, &cj->scene->r, false, true, &scene->view_settings, &scene->display_settings);
253
254         ntree->test_break = NULL;
255         ntree->stats_draw = NULL;
256         ntree->progress = NULL;
257
258 }
259
260 /**
261  * \param scene_owner is the owner of the job,
262  * we don't use it for anything else currently so could also be a void pointer,
263  * but for now keep it an 'Scene' for consistency.
264  *
265  * \note only call from spaces `refresh` callbacks, not direct! - use with care.
266  */
267 void ED_node_composite_job(const bContext *C, struct bNodeTree *nodetree, Scene *scene_owner)
268 {
269         wmJob *wm_job;
270         CompoJob *cj;
271         Scene *scene = CTX_data_scene(C);
272
273         /* to fix bug: [#32272] */
274         if (G.is_rendering) {
275                 return;
276         }
277
278 #ifdef USE_ESC_COMPO
279         G.is_break = false;
280 #endif
281
282         BKE_image_backup_render(scene, BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result"));
283
284         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene_owner, "Compositing",
285                              WM_JOB_EXCL_RENDER | WM_JOB_PROGRESS, WM_JOB_TYPE_COMPOSITE);
286         cj = MEM_callocN(sizeof(CompoJob), "compo job");
287
288         /* customdata for preview thread */
289         cj->scene = scene;
290         cj->ntree = nodetree;
291         cj->recalc_flags = compo_get_recalc_flags(C);
292
293         /* setup job */
294         WM_jobs_customdata_set(wm_job, cj, compo_freejob);
295         WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_COMPO_RESULT, NC_SCENE | ND_COMPO_RESULT);
296         WM_jobs_callbacks(wm_job, compo_startjob, compo_initjob, compo_updatejob, NULL);
297
298         WM_jobs_start(CTX_wm_manager(C), wm_job);
299 }
300
301 /* ***************************************** */
302
303 /* operator poll callback */
304 int composite_node_active(bContext *C)
305 {
306         if (ED_operator_node_active(C)) {
307                 SpaceNode *snode = CTX_wm_space_node(C);
308                 if (ED_node_is_compositor(snode))
309                         return 1;
310         }
311         return 0;
312 }
313
314 /* operator poll callback */
315 int composite_node_editable(bContext *C)
316 {
317         if (ED_operator_node_editable(C)) {
318                 SpaceNode *snode = CTX_wm_space_node(C);
319                 if (ED_node_is_compositor(snode))
320                         return 1;
321         }
322         return 0;
323 }
324
325 void snode_dag_update(bContext *C, SpaceNode *snode)
326 {
327         Main *bmain = CTX_data_main(C);
328
329         /* for groups, update all ID's using this */
330         if (snode->edittree != snode->nodetree) {
331                 FOREACH_NODETREE(bmain, tntree, id) {
332                         if (ntreeHasTree(tntree, snode->edittree))
333                                 DAG_id_tag_update(id, 0);
334                 } FOREACH_NODETREE_END
335         }
336
337         DAG_id_tag_update(snode->id, 0);
338 }
339
340 void snode_notify(bContext *C, SpaceNode *snode)
341 {
342         ID *id = snode->id;
343
344         WM_event_add_notifier(C, NC_NODE | NA_EDITED, NULL);
345
346         if (ED_node_is_shader(snode)) {
347                 if (GS(id->name) == ID_MA)
348                         WM_main_add_notifier(NC_MATERIAL | ND_SHADING, id);
349                 else if (GS(id->name) == ID_LA)
350                         WM_main_add_notifier(NC_LAMP | ND_LIGHTING, id);
351                 else if (GS(id->name) == ID_WO)
352                         WM_main_add_notifier(NC_WORLD | ND_WORLD, id);
353         }
354         else if (ED_node_is_compositor(snode))
355                 WM_event_add_notifier(C, NC_SCENE | ND_NODES, id);
356         else if (ED_node_is_texture(snode))
357                 WM_event_add_notifier(C, NC_TEXTURE | ND_NODES, id);
358 }
359
360 void ED_node_set_tree_type(SpaceNode *snode, bNodeTreeType *typeinfo)
361 {
362         if (typeinfo)
363                 BLI_strncpy(snode->tree_idname, typeinfo->idname, sizeof(snode->tree_idname));
364         else
365                 snode->tree_idname[0] = '\0';
366 }
367
368 bool ED_node_is_compositor(struct SpaceNode *snode)
369 {
370         return STREQ(snode->tree_idname, ntreeType_Composite->idname);
371 }
372
373 bool ED_node_is_shader(struct SpaceNode *snode)
374 {
375         return STREQ(snode->tree_idname, ntreeType_Shader->idname);
376 }
377
378 bool ED_node_is_texture(struct SpaceNode *snode)
379 {
380         return STREQ(snode->tree_idname, ntreeType_Texture->idname);
381 }
382
383 /* assumes nothing being done in ntree yet, sets the default in/out node */
384 /* called from shading buttons or header */
385 void ED_node_shader_default(const bContext *C, ID *id)
386 {
387         Scene *scene = CTX_data_scene(C);
388         bNode *in, *out;
389         bNodeSocket *fromsock, *tosock, *sock;
390         bNodeTree *ntree;
391         int output_type, shader_type;
392         float color[4] = { 0.0f, 0.0f, 0.0f, 1.0f }, strength = 1.0f;
393         
394         ntree = ntreeAddTree(NULL, "Shader Nodetree", ntreeType_Shader->idname);
395
396         switch (GS(id->name)) {
397                 case ID_MA:
398                 {
399                         Material *ma = (Material *)id;
400                         ma->nodetree = ntree;
401
402                         if (BKE_scene_use_new_shading_nodes(scene)) {
403                                 output_type = SH_NODE_OUTPUT_MATERIAL;
404                                 shader_type = SH_NODE_BSDF_DIFFUSE;
405                         }
406                         else {
407                                 output_type = SH_NODE_OUTPUT;
408                                 shader_type = SH_NODE_MATERIAL;
409                         }
410
411                         copy_v3_v3(color, &ma->r);
412                         strength = 0.0f;
413                         break;
414                 }
415                 case ID_WO:
416                 {
417                         World *wo = (World *)id;
418                         wo->nodetree = ntree;
419
420                         output_type = SH_NODE_OUTPUT_WORLD;
421                         shader_type = SH_NODE_BACKGROUND;
422
423                         copy_v3_v3(color, &wo->horr);
424                         strength = 1.0f;
425                         break;
426                 }
427                 case ID_LA:
428                 {
429                         Lamp *la = (Lamp *)id;
430                         la->nodetree = ntree;
431
432                         output_type = SH_NODE_OUTPUT_LAMP;
433                         shader_type = SH_NODE_EMISSION;
434
435                         copy_v3_v3(color, &la->r);
436                         if (la->type == LA_LOCAL || la->type == LA_SPOT || la->type == LA_AREA)
437                                 strength = 100.0f;
438                         else
439                                 strength = 1.0f;
440                         break;
441                 }
442                 default:
443                         printf("ED_node_shader_default called on wrong ID type.\n");
444                         return;
445         }
446         
447         out = nodeAddStaticNode(C, ntree, output_type);
448         out->locx = 300.0f; out->locy = 300.0f;
449         
450         in = nodeAddStaticNode(C, ntree, shader_type);
451         in->locx = 10.0f; in->locy = 300.0f;
452         nodeSetActive(ntree, in);
453         
454         /* only a link from color to color */
455         fromsock = in->outputs.first;
456         tosock = out->inputs.first;
457         nodeAddLink(ntree, in, fromsock, out, tosock);
458
459         /* default values */
460         if (BKE_scene_use_new_shading_nodes(scene)) {
461                 PointerRNA sockptr;
462                 sock = in->inputs.first;
463                 RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, sock, &sockptr);
464                 
465                 RNA_float_set_array(&sockptr, "default_value", color);
466
467                 if (strength != 0.0f) {
468                         sock = in->inputs.last;
469                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, sock, &sockptr);
470                         RNA_float_set(&sockptr, "default_value", strength);
471                 }
472         }
473         
474         ntreeUpdateTree(CTX_data_main(C), ntree);
475 }
476
477 /* assumes nothing being done in ntree yet, sets the default in/out node */
478 /* called from shading buttons or header */
479 void ED_node_composit_default(const bContext *C, struct Scene *sce)
480 {
481         bNode *in, *out;
482         bNodeSocket *fromsock, *tosock;
483         
484         /* but lets check it anyway */
485         if (sce->nodetree) {
486                 if (G.debug & G_DEBUG)
487                         printf("error in composite initialize\n");
488                 return;
489         }
490         
491         sce->nodetree = ntreeAddTree(NULL, "Compositing Nodetree", ntreeType_Composite->idname);
492         
493         sce->nodetree->chunksize = 256;
494         sce->nodetree->edit_quality = NTREE_QUALITY_HIGH;
495         sce->nodetree->render_quality = NTREE_QUALITY_HIGH;
496         
497         out = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_COMPOSITE);
498         out->locx = 300.0f; out->locy = 400.0f;
499         
500         in = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_R_LAYERS);
501         in->locx = 10.0f; in->locy = 400.0f;
502         nodeSetActive(sce->nodetree, in);
503         
504         /* links from color to color */
505         fromsock = in->outputs.first;
506         tosock = out->inputs.first;
507         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
508         
509         ntreeUpdateTree(CTX_data_main(C), sce->nodetree);
510         
511         // XXX ntreeCompositForceHidden(sce->nodetree);
512 }
513
514 /* assumes nothing being done in ntree yet, sets the default in/out node */
515 /* called from shading buttons or header */
516 void ED_node_texture_default(const bContext *C, Tex *tx)
517 {
518         bNode *in, *out;
519         bNodeSocket *fromsock, *tosock;
520         
521         /* but lets check it anyway */
522         if (tx->nodetree) {
523                 if (G.debug & G_DEBUG)
524                         printf("error in texture initialize\n");
525                 return;
526         }
527         
528         tx->nodetree = ntreeAddTree(NULL, "Texture Nodetree", ntreeType_Texture->idname);
529         
530         out = nodeAddStaticNode(C, tx->nodetree, TEX_NODE_OUTPUT);
531         out->locx = 300.0f; out->locy = 300.0f;
532         
533         in = nodeAddStaticNode(C, tx->nodetree, TEX_NODE_CHECKER);
534         in->locx = 10.0f; in->locy = 300.0f;
535         nodeSetActive(tx->nodetree, in);
536         
537         fromsock = in->outputs.first;
538         tosock = out->inputs.first;
539         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
540         
541         ntreeUpdateTree(CTX_data_main(C), tx->nodetree);
542 }
543
544 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
545 void snode_set_context(const bContext *C)
546 {
547         SpaceNode *snode = CTX_wm_space_node(C);
548         bNodeTreeType *treetype = ntreeTypeFind(snode->tree_idname);
549         bNodeTree *ntree = snode->nodetree;
550         ID *id = snode->id, *from = snode->from;
551         
552         /* we use this to signal warnings, when node shaders are drawn in wrong render engine */
553         if (BKE_scene_use_new_shading_nodes(CTX_data_scene(C)))
554                 snode->flag |= SNODE_NEW_SHADERS;
555         else
556                 snode->flag &= ~SNODE_NEW_SHADERS;
557         
558         /* check the tree type */
559         if (!treetype ||
560             (treetype->poll && !treetype->poll(C, treetype)))
561         {
562                 /* invalid tree type, skip
563                  * NB: not resetting the node path here, invalid bNodeTreeType
564                  * may still be registered at a later point.
565                  */
566                 return;
567         }
568         
569         if (snode->nodetree && !STREQ(snode->nodetree->idname, snode->tree_idname)) {
570                 /* current tree does not match selected type, clear tree path */
571                 ntree = NULL;
572                 id = NULL;
573                 from = NULL;
574         }
575         
576         if (!(snode->flag & SNODE_PIN) || ntree == NULL) {
577                 if (treetype->get_from_context) {
578                         /* reset and update from context */
579                         ntree = NULL;
580                         id = NULL;
581                         from = NULL;
582                         
583                         treetype->get_from_context(C, treetype, &ntree, &id, &from);
584                 }
585         }
586         
587         if (snode->nodetree != ntree || snode->id != id || snode->from != from) {
588                 ED_node_tree_start(snode, ntree, id, from);
589         }
590         
591         /* XXX Legacy hack to update render layer node outputs.
592          * This should be handled by the depsgraph eventually ...
593          */
594         if (ED_node_is_compositor(snode) && snode->nodetree) {
595                 /* update output sockets based on available layers */
596                 ntreeCompositForceHidden(snode->nodetree);
597         }
598 }
599
600 void snode_update(SpaceNode *snode, bNode *node)
601 {
602         bNodeTreePath *path;
603         
604         /* XXX this only updates nodes in the current node space tree path.
605          * The function supposedly should update any potential group node linking to changed tree,
606          * this really requires a working depsgraph ...
607          */
608         
609         /* update all edited group nodes */
610         path = snode->treepath.last;
611         if (path) {
612                 bNodeTree *ngroup = path->nodetree;
613                 for (path = path->prev; path; path = path->prev) {
614                         nodeUpdateID(path->nodetree, (ID *)ngroup);
615                         ngroup = path->nodetree;
616                 }
617         }
618
619         if (node)
620                 nodeUpdate(snode->edittree, node);
621 }
622
623 void ED_node_set_active(Main *bmain, bNodeTree *ntree, bNode *node)
624 {
625         const bool was_active_texture = (node->flag & NODE_ACTIVE_TEXTURE) != 0;
626
627         nodeSetActive(ntree, node);
628         
629         if (node->type != NODE_GROUP) {
630                 const bool was_output = (node->flag & NODE_DO_OUTPUT) != 0;
631                 bool do_update = false;
632                 
633                 /* generic node group output: set node as active output */
634                 if (node->type == NODE_GROUP_OUTPUT) {
635                         bNode *tnode;
636                         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
637                                 if (tnode->type == NODE_GROUP_OUTPUT)
638                                         tnode->flag &= ~NODE_DO_OUTPUT;
639                         
640                         node->flag |= NODE_DO_OUTPUT;
641                         if (!was_output)
642                                 do_update = 1;
643                 }
644                 
645                 /* tree specific activate calls */
646                 if (ntree->type == NTREE_SHADER) {
647                         /* when we select a material, active texture is cleared, for buttons */
648                         if (node->id && ELEM(GS(node->id->name), ID_MA, ID_LA, ID_WO))
649                                 nodeClearActiveID(ntree, ID_TE);
650                         
651                         if (ELEM(node->type, SH_NODE_OUTPUT, SH_NODE_OUTPUT_MATERIAL,
652                                  SH_NODE_OUTPUT_WORLD, SH_NODE_OUTPUT_LAMP, SH_NODE_OUTPUT_LINESTYLE))
653                         {
654                                 bNode *tnode;
655                                 
656                                 for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
657                                         if (tnode->type == node->type)
658                                                 tnode->flag &= ~NODE_DO_OUTPUT;
659                                 
660                                 node->flag |= NODE_DO_OUTPUT;
661                                 if (was_output == 0)
662                                         ED_node_tag_update_nodetree(bmain, ntree);
663                         }
664                         else if (do_update)
665                                 ED_node_tag_update_nodetree(bmain, ntree);
666
667                         /* if active texture changed, free glsl materials */
668                         if ((node->flag & NODE_ACTIVE_TEXTURE) && !was_active_texture) {
669                                 Material *ma;
670                                 World *wo;
671
672                                 for (ma = bmain->mat.first; ma; ma = ma->id.next)
673                                         if (ma->nodetree && ma->use_nodes && ntreeHasTree(ma->nodetree, ntree))
674                                                 GPU_material_free(&ma->gpumaterial);
675
676                                 for (wo = bmain->world.first; wo; wo = wo->id.next)
677                                         if (wo->nodetree && wo->use_nodes && ntreeHasTree(wo->nodetree, ntree))
678                                                 GPU_material_free(&wo->gpumaterial);
679                                 
680                                 WM_main_add_notifier(NC_IMAGE, NULL);
681                         }
682
683                         WM_main_add_notifier(NC_MATERIAL | ND_NODES, node->id);
684                 }
685                 else if (ntree->type == NTREE_COMPOSIT) {
686                         /* make active viewer, currently only 1 supported... */
687                         if (ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
688                                 bNode *tnode;
689                                 
690
691                                 for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
692                                         if (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
693                                                 tnode->flag &= ~NODE_DO_OUTPUT;
694                                 
695                                 node->flag |= NODE_DO_OUTPUT;
696                                 if (was_output == 0)
697                                         ED_node_tag_update_nodetree(bmain, ntree);
698                                 
699                                 /* addnode() doesnt link this yet... */
700                                 node->id = (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
701                         }
702                         else if (node->type == CMP_NODE_R_LAYERS) {
703                                 Scene *scene;
704
705                                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
706                                         if (scene->nodetree && scene->use_nodes && ntreeHasTree(scene->nodetree, ntree)) {
707                                                 if (node->id == NULL || node->id == (ID *)scene) {
708                                                         int num_layers = BLI_listbase_count(&scene->r.layers);
709                                                         scene->r.actlay = node->custom1;
710                                                         /* Clamp the value, because it might have come from a different
711                                                          * scene which could have more render layers than new one.
712                                                          */
713                                                         scene->r.actlay = min_ff(scene->r.actlay, num_layers - 1);
714                                                 }
715                                         }
716                                 }
717                         }
718                         else if (node->type == CMP_NODE_COMPOSITE) {
719                                 if (was_output == 0) {
720                                         bNode *tnode;
721                                         
722                                         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
723                                                 if (tnode->type == CMP_NODE_COMPOSITE)
724                                                         tnode->flag &= ~NODE_DO_OUTPUT;
725                                         
726                                         node->flag |= NODE_DO_OUTPUT;
727                                         ED_node_tag_update_nodetree(bmain, ntree);
728                                 }
729                         }
730                         else if (do_update)
731                                 ED_node_tag_update_nodetree(bmain, ntree);
732                 }
733                 else if (ntree->type == NTREE_TEXTURE) {
734                         // XXX
735 #if 0
736                         if (node->id)
737                                 ;  // XXX BIF_preview_changed(-1);
738                         // allqueue(REDRAWBUTSSHADING, 1);
739                         // allqueue(REDRAWIPO, 0);
740 #endif
741                 }
742         }
743 }
744
745 void ED_node_post_apply_transform(bContext *UNUSED(C), bNodeTree *UNUSED(ntree))
746 {
747         /* XXX This does not work due to layout functions relying on node->block,
748          * which only exists during actual drawing. Can we rely on valid totr rects?
749          */
750         /* make sure nodes have correct bounding boxes after transform */
751         /* node_update_nodetree(C, ntree, 0.0f, 0.0f); */
752 }
753
754 /* ***************** generic operator functions for nodes ***************** */
755
756 #if 0 /* UNUSED */
757
758 static int edit_node_poll(bContext *C)
759 {
760         return ED_operator_node_active(C);
761 }
762
763 static void edit_node_properties(wmOperatorType *ot)
764 {
765         /* XXX could node be a context pointer? */
766         RNA_def_string(ot->srna, "node", NULL, MAX_NAME, "Node", "");
767         RNA_def_int(ot->srna, "socket", 0, 0, MAX_SOCKET, "Socket", "", 0, MAX_SOCKET);
768         RNA_def_enum(ot->srna, "in_out", node_socket_in_out_items, SOCK_IN, "Socket Side", "");
769 }
770
771 static int edit_node_invoke_properties(bContext *C, wmOperator *op)
772 {
773         if (!RNA_struct_property_is_set(op->ptr, "node")) {
774                 bNode *node = CTX_data_pointer_get_type(C, "node", &RNA_Node).data;
775                 if (!node)
776                         return 0;
777                 else
778                         RNA_string_set(op->ptr, "node", node->name);
779         }
780         
781         if (!RNA_struct_property_is_set(op->ptr, "in_out"))
782                 RNA_enum_set(op->ptr, "in_out", SOCK_IN);
783         
784         if (!RNA_struct_property_is_set(op->ptr, "socket"))
785                 RNA_int_set(op->ptr, "socket", 0);
786         
787         return 1;
788 }
789
790 static void edit_node_properties_get(wmOperator *op, bNodeTree *ntree, bNode **rnode, bNodeSocket **rsock, int *rin_out)
791 {
792         bNode *node;
793         bNodeSocket *sock = NULL;
794         char nodename[MAX_NAME];
795         int sockindex;
796         int in_out;
797         
798         RNA_string_get(op->ptr, "node", nodename);
799         node = nodeFindNodebyName(ntree, nodename);
800         
801         in_out = RNA_enum_get(op->ptr, "in_out");
802         
803         sockindex = RNA_int_get(op->ptr, "socket");
804         switch (in_out) {
805                 case SOCK_IN:   sock = BLI_findlink(&node->inputs, sockindex);  break;
806                 case SOCK_OUT:  sock = BLI_findlink(&node->outputs, sockindex); break;
807         }
808         
809         if (rnode)
810                 *rnode = node;
811         if (rsock)
812                 *rsock = sock;
813         if (rin_out)
814                 *rin_out = in_out;
815 }
816 #endif
817
818 /* ************************** Node generic ************** */
819
820 /* is rct in visible part of node? */
821 static bNode *visible_node(SpaceNode *snode, const rctf *rct)
822 {
823         bNode *node;
824         
825         for (node = snode->edittree->nodes.last; node; node = node->prev) {
826                 if (BLI_rctf_isect(&node->totr, rct, NULL))
827                         break;
828         }
829         return node;
830 }
831
832 /* ********************** size widget operator ******************** */
833
834 typedef struct NodeSizeWidget {
835         float mxstart, mystart;
836         float oldlocx, oldlocy;
837         float oldoffsetx, oldoffsety;
838         float oldwidth, oldheight;
839         float oldminiwidth;
840         int directions;
841 } NodeSizeWidget;
842
843 static void node_resize_init(bContext *C, wmOperator *op, const wmEvent *UNUSED(event), bNode *node, int dir)
844 {
845         SpaceNode *snode = CTX_wm_space_node(C);
846         
847         NodeSizeWidget *nsw = MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
848         
849         op->customdata = nsw;
850         nsw->mxstart = snode->cursor[0];
851         nsw->mystart = snode->cursor[1];
852         
853         /* store old */
854         nsw->oldlocx = node->locx;
855         nsw->oldlocy = node->locy;
856         nsw->oldoffsetx = node->offsetx;
857         nsw->oldoffsety = node->offsety;
858         nsw->oldwidth = node->width;
859         nsw->oldheight = node->height;
860         nsw->oldminiwidth = node->miniwidth;
861         nsw->directions = dir;
862         
863         WM_cursor_modal_set(CTX_wm_window(C), node_get_resize_cursor(dir));
864         /* add modal handler */
865         WM_event_add_modal_handler(C, op);
866 }
867
868 static void node_resize_exit(bContext *C, wmOperator *op, bool UNUSED(cancel))
869 {
870         WM_cursor_modal_restore(CTX_wm_window(C));
871         
872         MEM_freeN(op->customdata);
873         op->customdata = NULL;
874 }
875
876 static int node_resize_modal(bContext *C, wmOperator *op, const wmEvent *event)
877 {
878         SpaceNode *snode = CTX_wm_space_node(C);
879         ARegion *ar = CTX_wm_region(C);
880         bNode *node = nodeGetActive(snode->edittree);
881         NodeSizeWidget *nsw = op->customdata;
882         float mx, my, dx, dy;
883         
884         switch (event->type) {
885                 case MOUSEMOVE:
886                         
887                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &mx, &my);
888                         dx = (mx - nsw->mxstart) / UI_DPI_FAC;
889                         dy = (my - nsw->mystart) / UI_DPI_FAC;
890                         
891                         if (node) {
892                                 /* width can use node->width or node->miniwidth (hidden nodes) */
893                                 float *pwidth;
894                                 float oldwidth, widthmin, widthmax;
895                                 /* ignore hidden flag for frame nodes */
896                                 bool use_hidden = (node->type != NODE_FRAME);
897                                 if (use_hidden && node->flag & NODE_HIDDEN) {
898                                         pwidth = &node->miniwidth;
899                                         oldwidth = nsw->oldminiwidth;
900                                         widthmin = 0.0f;
901                                         widthmax = 100.0f;
902                                 }
903                                 else {
904                                         pwidth = &node->width;
905                                         oldwidth = nsw->oldwidth;
906                                         widthmin = node->typeinfo->minwidth;
907                                         widthmax = node->typeinfo->maxwidth;
908                                 }
909                                 
910                                 {
911                                         if (nsw->directions & NODE_RESIZE_RIGHT) {
912                                                 *pwidth = oldwidth + dx;
913                                                 CLAMP(*pwidth, widthmin, widthmax);
914                                         }
915                                         if (nsw->directions & NODE_RESIZE_LEFT) {
916                                                 float locmax = nsw->oldlocx + oldwidth;
917                                                 
918                                                 node->locx = nsw->oldlocx + dx;
919                                                 CLAMP(node->locx, locmax - widthmax, locmax - widthmin);
920                                                 *pwidth = locmax - node->locx;
921                                         }
922                                 }
923                                 
924                                 /* height works the other way round ... */
925                                 {
926                                         float heightmin = UI_DPI_FAC * node->typeinfo->minheight;
927                                         float heightmax = UI_DPI_FAC * node->typeinfo->maxheight;
928                                         if (nsw->directions & NODE_RESIZE_TOP) {
929                                                 float locmin = nsw->oldlocy - nsw->oldheight;
930                                                 
931                                                 node->locy = nsw->oldlocy + dy;
932                                                 CLAMP(node->locy, locmin + heightmin, locmin + heightmax);
933                                                 node->height = node->locy - locmin;
934                                         }
935                                         if (nsw->directions & NODE_RESIZE_BOTTOM) {
936                                                 node->height = nsw->oldheight - dy;
937                                                 CLAMP(node->height, heightmin, heightmax);
938                                         }
939                                 }
940                                 
941                                 /* XXX make callback? */
942                                 if (node->type == NODE_FRAME) {
943                                         /* keep the offset symmetric around center point */
944                                         if (nsw->directions & NODE_RESIZE_LEFT) {
945                                                 node->locx = nsw->oldlocx + 0.5f * dx;
946                                                 node->offsetx = nsw->oldoffsetx + 0.5f * dx;
947                                         }
948                                         if (nsw->directions & NODE_RESIZE_RIGHT) {
949                                                 node->locx = nsw->oldlocx + 0.5f * dx;
950                                                 node->offsetx = nsw->oldoffsetx - 0.5f * dx;
951                                         }
952                                         if (nsw->directions & NODE_RESIZE_TOP) {
953                                                 node->locy = nsw->oldlocy + 0.5f * dy;
954                                                 node->offsety = nsw->oldoffsety + 0.5f * dy;
955                                         }
956                                         if (nsw->directions & NODE_RESIZE_BOTTOM) {
957                                                 node->locy = nsw->oldlocy + 0.5f * dy;
958                                                 node->offsety = nsw->oldoffsety - 0.5f * dy;
959                                         }
960                                 }
961                         }
962                                 
963                         ED_region_tag_redraw(ar);
964
965                         break;
966                         
967                 case LEFTMOUSE:
968                 case MIDDLEMOUSE:
969                 case RIGHTMOUSE:
970                         
971                         node_resize_exit(C, op, false);
972                         ED_node_post_apply_transform(C, snode->edittree);
973                         
974                         return OPERATOR_FINISHED;
975         }
976         
977         return OPERATOR_RUNNING_MODAL;
978 }
979
980 static int node_resize_invoke(bContext *C, wmOperator *op, const wmEvent *event)
981 {
982         SpaceNode *snode = CTX_wm_space_node(C);
983         ARegion *ar = CTX_wm_region(C);
984         bNode *node = nodeGetActive(snode->edittree);
985         int dir;
986         
987         if (node) {
988                 /* convert mouse coordinates to v2d space */
989                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
990                                          &snode->cursor[0], &snode->cursor[1]);
991                 dir = node->typeinfo->resize_area_func(node, snode->cursor[0], snode->cursor[1]);
992                 if (dir != 0) {
993                         node_resize_init(C, op, event, node, dir);
994                         return OPERATOR_RUNNING_MODAL;
995                 }
996         }
997         return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
998 }
999
1000 static void node_resize_cancel(bContext *C, wmOperator *op)
1001 {
1002         node_resize_exit(C, op, true);
1003 }
1004
1005 void NODE_OT_resize(wmOperatorType *ot)
1006 {
1007         /* identifiers */
1008         ot->name = "Resize Node";
1009         ot->idname = "NODE_OT_resize";
1010         ot->description = "Resize a node";
1011         
1012         /* api callbacks */
1013         ot->invoke = node_resize_invoke;
1014         ot->modal = node_resize_modal;
1015         ot->poll = ED_operator_node_active;
1016         ot->cancel = node_resize_cancel;
1017         
1018         /* flags */
1019         ot->flag = OPTYPE_BLOCKING;
1020 }
1021
1022
1023 /* ********************** hidden sockets ******************** */
1024
1025 int node_has_hidden_sockets(bNode *node)
1026 {
1027         bNodeSocket *sock;
1028         
1029         for (sock = node->inputs.first; sock; sock = sock->next)
1030                 if (sock->flag & SOCK_HIDDEN)
1031                         return 1;
1032         for (sock = node->outputs.first; sock; sock = sock->next)
1033                 if (sock->flag & SOCK_HIDDEN)
1034                         return 1;
1035         return 0;
1036 }
1037
1038 void node_set_hidden_sockets(SpaceNode *snode, bNode *node, int set)
1039 {
1040         bNodeSocket *sock;
1041
1042         if (set == 0) {
1043                 for (sock = node->inputs.first; sock; sock = sock->next)
1044                         sock->flag &= ~SOCK_HIDDEN;
1045                 for (sock = node->outputs.first; sock; sock = sock->next)
1046                         sock->flag &= ~SOCK_HIDDEN;
1047         }
1048         else {
1049                 /* hide unused sockets */
1050                 for (sock = node->inputs.first; sock; sock = sock->next) {
1051                         if (sock->link == NULL)
1052                                 sock->flag |= SOCK_HIDDEN;
1053                 }
1054                 for (sock = node->outputs.first; sock; sock = sock->next) {
1055                         if (nodeCountSocketLinks(snode->edittree, sock) == 0)
1056                                 sock->flag |= SOCK_HIDDEN;
1057                 }
1058         }
1059 }
1060
1061
1062 /* checks snode->mouse position, and returns found node/socket */
1063 /* type is SOCK_IN and/or SOCK_OUT */
1064 int node_find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, float cursor[2], int in_out)
1065 {
1066         bNode *node;
1067         bNodeSocket *sock;
1068         rctf rect;
1069         
1070         *nodep = NULL;
1071         *sockp = NULL;
1072         
1073         /* check if we click in a socket */
1074         for (node = snode->edittree->nodes.first; node; node = node->next) {
1075                 
1076                 rect.xmin = cursor[0] - (NODE_SOCKSIZE + 4);
1077                 rect.ymin = cursor[1] - (NODE_SOCKSIZE + 4);
1078                 rect.xmax = cursor[0] + (NODE_SOCKSIZE + 4);
1079                 rect.ymax = cursor[1] + (NODE_SOCKSIZE + 4);
1080                 
1081                 if (!(node->flag & NODE_HIDDEN)) {
1082                         /* extra padding inside and out - allow dragging on the text areas too */
1083                         if (in_out == SOCK_IN) {
1084                                 rect.xmax += NODE_SOCKSIZE;
1085                                 rect.xmin -= NODE_SOCKSIZE * 4;
1086                         }
1087                         else if (in_out == SOCK_OUT) {
1088                                 rect.xmax += NODE_SOCKSIZE * 4;
1089                                 rect.xmin -= NODE_SOCKSIZE;
1090                         }
1091                 }
1092                 
1093                 if (in_out & SOCK_IN) {
1094                         for (sock = node->inputs.first; sock; sock = sock->next) {
1095                                 if (!nodeSocketIsHidden(sock)) {
1096                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1097                                                 if (node == visible_node(snode, &rect)) {
1098                                                         *nodep = node;
1099                                                         *sockp = sock;
1100                                                         return 1;
1101                                                 }
1102                                         }
1103                                 }
1104                         }
1105                 }
1106                 if (in_out & SOCK_OUT) {
1107                         for (sock = node->outputs.first; sock; sock = sock->next) {
1108                                 if (!nodeSocketIsHidden(sock)) {
1109                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1110                                                 if (node == visible_node(snode, &rect)) {
1111                                                         *nodep = node;
1112                                                         *sockp = sock;
1113                                                         return 1;
1114                                                 }
1115                                         }
1116                                 }
1117                         }
1118                 }
1119         }
1120         
1121         return 0;
1122 }
1123
1124 /* ****************** Duplicate *********************** */
1125
1126 static void node_duplicate_reparent_recursive(bNode *node)
1127 {
1128         bNode *parent;
1129         
1130         node->flag |= NODE_TEST;
1131         
1132         /* find first selected parent */
1133         for (parent = node->parent; parent; parent = parent->parent) {
1134                 if (parent->flag & SELECT) {
1135                         if (!(parent->flag & NODE_TEST))
1136                                 node_duplicate_reparent_recursive(parent);
1137                         break;
1138                 }
1139         }
1140         /* reparent node copy to parent copy */
1141         if (parent) {
1142                 nodeDetachNode(node->new_node);
1143                 nodeAttachNode(node->new_node, parent->new_node);
1144         }
1145 }
1146
1147 static int node_duplicate_exec(bContext *C, wmOperator *op)
1148 {
1149         SpaceNode *snode = CTX_wm_space_node(C);
1150         bNodeTree *ntree = snode->edittree;
1151         bNode *node, *newnode, *lastnode;
1152         bNodeLink *link, *newlink, *lastlink;
1153         const bool keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
1154         
1155         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1156         
1157         lastnode = ntree->nodes.last;
1158         for (node = ntree->nodes.first; node; node = node->next) {
1159                 if (node->flag & SELECT) {
1160                         newnode = nodeCopyNode(ntree, node);
1161                         
1162                         if (newnode->id) {
1163                                 /* simple id user adjustment, node internal functions don't touch this
1164                                  * but operators and readfile.c do. */
1165                                 id_us_plus(newnode->id);
1166                                 /* to ensure redraws or rerenders happen */
1167                                 ED_node_tag_update_id(snode->id);
1168                         }
1169                 }
1170                 
1171                 /* make sure we don't copy new nodes again! */
1172                 if (node == lastnode)
1173                         break;
1174         }
1175         
1176         /* copy links between selected nodes
1177          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
1178          */
1179         lastlink = ntree->links.last;
1180         for (link = ntree->links.first; link; link = link->next) {
1181                 /* This creates new links between copied nodes.
1182                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
1183                  */
1184                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
1185                     (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT))))
1186                 {
1187                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
1188                         newlink->flag = link->flag;
1189                         newlink->tonode = link->tonode->new_node;
1190                         newlink->tosock = link->tosock->new_sock;
1191                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
1192                                 newlink->fromnode = link->fromnode->new_node;
1193                                 newlink->fromsock = link->fromsock->new_sock;
1194                         }
1195                         else {
1196                                 /* input node not copied, this keeps the original input linked */
1197                                 newlink->fromnode = link->fromnode;
1198                                 newlink->fromsock = link->fromsock;
1199                         }
1200                         
1201                         BLI_addtail(&ntree->links, newlink);
1202                 }
1203                 
1204                 /* make sure we don't copy new links again! */
1205                 if (link == lastlink)
1206                         break;
1207         }
1208         
1209         /* clear flags for recursive depth-first iteration */
1210         for (node = ntree->nodes.first; node; node = node->next)
1211                 node->flag &= ~NODE_TEST;
1212         /* reparent copied nodes */
1213         for (node = ntree->nodes.first; node; node = node->next) {
1214                 if ((node->flag & SELECT) && !(node->flag & NODE_TEST))
1215                         node_duplicate_reparent_recursive(node);
1216                 
1217                 /* only has to check old nodes */
1218                 if (node == lastnode)
1219                         break;
1220         }
1221         
1222         /* deselect old nodes, select the copies instead */
1223         for (node = ntree->nodes.first; node; node = node->next) {
1224                 if (node->flag & SELECT) {
1225                         /* has been set during copy above */
1226                         newnode = node->new_node;
1227                         
1228                         nodeSetSelected(node, false);
1229                         node->flag &= ~NODE_ACTIVE;
1230                         nodeSetSelected(newnode, true);
1231                 }
1232                 
1233                 /* make sure we don't copy new nodes again! */
1234                 if (node == lastnode)
1235                         break;
1236         }
1237         
1238         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1239         
1240         snode_notify(C, snode);
1241         snode_dag_update(C, snode);
1242
1243         return OPERATOR_FINISHED;
1244 }
1245
1246 void NODE_OT_duplicate(wmOperatorType *ot)
1247 {
1248         /* identifiers */
1249         ot->name = "Duplicate Nodes";
1250         ot->description = "Duplicate selected nodes";
1251         ot->idname = "NODE_OT_duplicate";
1252         
1253         /* api callbacks */
1254         ot->exec = node_duplicate_exec;
1255         ot->poll = ED_operator_node_editable;
1256         
1257         /* flags */
1258         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1259         
1260         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
1261 }
1262
1263 bool ED_node_select_check(ListBase *lb)
1264
1265
1266 {
1267         bNode *node;
1268
1269         for (node = lb->first; node; node = node->next) {
1270                 if (node->flag & NODE_SELECT) {
1271                         return true;
1272                 }
1273         }
1274
1275         return false;
1276 }
1277
1278 /* ******************************** */
1279 // XXX some code needing updating to operators...
1280
1281
1282 /* goes over all scenes, reads render layers */
1283 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
1284 {
1285         Main *bmain = CTX_data_main(C);
1286         SpaceNode *snode = CTX_wm_space_node(C);
1287         Scene *curscene = CTX_data_scene(C), *scene;
1288         bNode *node;
1289
1290         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
1291
1292         /* first tag scenes unread */
1293         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1294                 scene->id.flag |= LIB_DOIT;
1295
1296         for (node = snode->edittree->nodes.first; node; node = node->next) {
1297                 if (node->type == CMP_NODE_R_LAYERS) {
1298                         ID *id = node->id;
1299                         if (id->flag & LIB_DOIT) {
1300                                 RE_ReadRenderResult(curscene, (Scene *)id);
1301                                 ntreeCompositTagRender((Scene *)id);
1302                                 id->flag &= ~LIB_DOIT;
1303                         }
1304                 }
1305         }
1306         
1307         snode_notify(C, snode);
1308         snode_dag_update(C, snode);
1309
1310         return OPERATOR_FINISHED;
1311 }
1312
1313 void NODE_OT_read_renderlayers(wmOperatorType *ot)
1314 {
1315         
1316         ot->name = "Read Render Layers";
1317         ot->idname = "NODE_OT_read_renderlayers";
1318         ot->description = "Read all render layers of all used scenes";
1319         
1320         ot->exec = node_read_renderlayers_exec;
1321         
1322         ot->poll = composite_node_active;
1323         
1324         /* flags */
1325         ot->flag = 0;
1326 }
1327
1328 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
1329 {
1330         Main *bmain = CTX_data_main(C);
1331         SpaceNode *snode = CTX_wm_space_node(C);
1332         Scene *curscene = CTX_data_scene(C);
1333         Render *re = RE_NewRender(curscene->id.name);
1334
1335         WM_cursor_wait(1);
1336         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
1337         WM_cursor_wait(0);
1338
1339         /* note we are careful to send the right notifier, as otherwise the
1340          * compositor would reexecute and overwrite the full sample result */
1341         WM_event_add_notifier(C, NC_SCENE | ND_COMPO_RESULT, NULL);
1342
1343         return OPERATOR_FINISHED;
1344 }
1345
1346
1347 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
1348 {
1349         
1350         ot->name = "Read Full Sample Layers";
1351         ot->idname = "NODE_OT_read_fullsamplelayers";
1352         ot->description = "Read all render layers of current scene, in full sample";
1353         
1354         ot->exec = node_read_fullsamplelayers_exec;
1355         
1356         ot->poll = composite_node_active;
1357         
1358         /* flags */
1359         ot->flag = 0;
1360 }
1361
1362 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
1363 {
1364         Scene *sce = CTX_data_scene(C);
1365         bNode *node;
1366         
1367         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1368                 if (node->id == (ID *)sce && node->need_exec) {
1369                         break;
1370                 }
1371         }
1372         if (node) {
1373                 SceneRenderLayer *srl = BLI_findlink(&sce->r.layers, node->custom1);
1374                 
1375                 if (srl) {
1376                         PointerRNA op_ptr;
1377                         
1378                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
1379                         RNA_string_set(&op_ptr, "layer", srl->name);
1380                         RNA_string_set(&op_ptr, "scene", sce->id.name + 2);
1381                         
1382                         /* to keep keypositions */
1383                         sce->r.scemode |= R_NO_FRAME_UPDATE;
1384                         
1385                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
1386
1387                         WM_operator_properties_free(&op_ptr);
1388                         
1389                         return OPERATOR_FINISHED;
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->draw_buttons || node->typeinfo->draw_buttons_ex))
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->draw_buttons || node->typeinfo->draw_buttons_ex))
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(CTX_wm_manager(C), CTX_data_main(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(CTX_wm_manager(C), CTX_data_main(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(CTX_wm_manager(C), CTX_data_main(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(CTX_wm_manager(C), CTX_data_main(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(CTX_wm_manager(C), CTX_data_main(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 || node->type != CMP_NODE_OUTPUT_FILE)
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 || node->type != CMP_NODE_OUTPUT_FILE)
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 || node->type != CMP_NODE_OUTPUT_FILE)
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(CTX_wm_manager(C), CTX_data_main(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         bool 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 (BLI_listbase_is_empty(clipboard_nodes_lb)) {
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(CTX_wm_manager(C), CTX_data_main(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 void NODE_OT_clipboard_paste(wmOperatorType *ot)
2095 {
2096         /* identifiers */
2097         ot->name = "Paste from Clipboard";
2098         ot->description = "Pastes nodes from the clipboard to the active node tree";
2099         ot->idname = "NODE_OT_clipboard_paste";
2100
2101         /* api callbacks */
2102         ot->exec = node_clipboard_paste_exec;
2103         ot->poll = ED_operator_node_editable;
2104
2105         /* flags */
2106         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2107 }
2108
2109 /********************** Add interface socket operator *********************/
2110
2111 static bNodeSocket *ntree_get_active_interface_socket(ListBase *lb)
2112 {
2113         bNodeSocket *sock;
2114         for (sock = lb->first; sock; sock = sock->next)
2115                 if (sock->flag & SELECT)
2116                         return sock;
2117         return NULL;
2118 }
2119
2120 static int ntree_socket_add_exec(bContext *C, wmOperator *op)
2121 {
2122         SpaceNode *snode = CTX_wm_space_node(C);
2123         bNodeTree *ntree = snode->edittree;
2124         int in_out = RNA_enum_get(op->ptr, "in_out");
2125         PointerRNA ntree_ptr;
2126         bNodeSocket *sock, *tsock, *active_sock;
2127         const char *default_name;
2128         
2129         RNA_id_pointer_create((ID *)ntree, &ntree_ptr);
2130         
2131         if (in_out == SOCK_IN) {
2132                 active_sock = ntree_get_active_interface_socket(&ntree->inputs);
2133                 default_name = "Input";
2134         }
2135         else {
2136                 active_sock = ntree_get_active_interface_socket(&ntree->outputs);
2137                 default_name = "Output";
2138         }
2139         
2140         if (active_sock) {
2141                 /* insert a copy of the active socket right after it */
2142                 sock = ntreeInsertSocketInterface(ntree, in_out, active_sock->idname, active_sock->next, active_sock->name);
2143                 /* XXX this only works for actual sockets, not interface templates! */
2144                 /*nodeSocketCopyValue(sock, &ntree_ptr, active_sock, &ntree_ptr);*/
2145         }
2146         else {
2147                 /* XXX TODO define default socket type for a tree! */
2148                 sock = ntreeAddSocketInterface(ntree, in_out, "NodeSocketFloat", default_name);
2149         }
2150         
2151         /* deactivate sockets (has to check both lists) */
2152         for (tsock = ntree->inputs.first; tsock; tsock = tsock->next)
2153                 tsock->flag &= ~SELECT;
2154         for (tsock = ntree->outputs.first; tsock; tsock = tsock->next)
2155                 tsock->flag &= ~SELECT;
2156         /* make the new socket active */
2157         sock->flag |= SELECT;
2158         
2159         ntreeUpdateTree(CTX_data_main(C), ntree);
2160
2161         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2162         
2163         return OPERATOR_FINISHED;
2164 }
2165
2166 void NODE_OT_tree_socket_add(wmOperatorType *ot)
2167 {
2168         /* identifiers */
2169         ot->name = "Add Node Tree Interface Socket";
2170         ot->description = "Add an input or output socket to the current node tree";
2171         ot->idname = "NODE_OT_tree_socket_add";
2172         
2173         /* api callbacks */
2174         ot->exec = ntree_socket_add_exec;
2175         ot->poll = ED_operator_node_editable;
2176         
2177         /* flags */
2178         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2179         
2180         RNA_def_enum(ot->srna, "in_out", node_socket_in_out_items, SOCK_IN, "Socket Type", "");
2181 }
2182
2183 /********************** Remove interface socket operator *********************/
2184
2185 static int ntree_socket_remove_exec(bContext *C, wmOperator *UNUSED(op))
2186 {
2187         SpaceNode *snode = CTX_wm_space_node(C);
2188         bNodeTree *ntree = snode->edittree;
2189         bNodeSocket *iosock, *active_sock;
2190         
2191         iosock = ntree_get_active_interface_socket(&ntree->inputs);
2192         if (!iosock)
2193                 iosock = ntree_get_active_interface_socket(&ntree->outputs);
2194         if (!iosock)
2195                 return OPERATOR_CANCELLED;
2196         
2197         /* preferably next socket becomes active, otherwise try previous socket */
2198         active_sock = (iosock->next ? iosock->next : iosock->prev);
2199         ntreeRemoveSocketInterface(ntree, iosock);
2200         
2201         /* set active socket */
2202         if (active_sock)
2203                 active_sock->flag |= SELECT;
2204         
2205         ntreeUpdateTree(CTX_data_main(C), ntree);
2206
2207         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2208         
2209         return OPERATOR_FINISHED;
2210 }
2211
2212 void NODE_OT_tree_socket_remove(wmOperatorType *ot)
2213 {
2214         /* identifiers */
2215         ot->name = "Remove Node Tree Interface Socket";
2216         ot->description = "Remove an input or output socket to the current node tree";
2217         ot->idname = "NODE_OT_tree_socket_remove";
2218         
2219         /* api callbacks */
2220         ot->exec = ntree_socket_remove_exec;
2221         ot->poll = ED_operator_node_editable;
2222         
2223         /* flags */
2224         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2225 }
2226
2227 /********************** Move interface socket operator *********************/
2228
2229 static EnumPropertyItem move_direction_items[] = {
2230         { 1, "UP", 0, "Up", "" },
2231         { 2, "DOWN", 0, "Down", "" },
2232         { 0, NULL, 0, NULL, NULL },
2233 };
2234
2235 static int ntree_socket_move_exec(bContext *C, wmOperator *op)
2236 {
2237         SpaceNode *snode = CTX_wm_space_node(C);
2238         bNodeTree *ntree = snode->edittree;
2239         int direction = RNA_enum_get(op->ptr, "direction");
2240         bNodeSocket *iosock;
2241         ListBase *lb;
2242         
2243         lb = &ntree->inputs;
2244         iosock = ntree_get_active_interface_socket(lb);
2245         if (!iosock) {
2246                 lb = &ntree->outputs;
2247                 iosock = ntree_get_active_interface_socket(lb);
2248         }
2249         if (!iosock)
2250                 return OPERATOR_CANCELLED;
2251         
2252         switch (direction) {
2253                 case 1:
2254                 {       /* up */
2255                         bNodeSocket *before = iosock->prev;
2256                         BLI_remlink(lb, iosock);
2257                         if (before)
2258                                 BLI_insertlinkbefore(lb, before, iosock);
2259                         else
2260                                 BLI_addhead(lb, iosock);
2261                         break;
2262                 }
2263                 case 2:
2264                 {       /* down */
2265                         bNodeSocket *after = iosock->next;
2266                         BLI_remlink(lb, iosock);
2267                         if (after)
2268                                 BLI_insertlinkafter(lb, after, iosock);
2269                         else
2270                                 BLI_addtail(lb, iosock);
2271                         break;
2272                 }
2273         }
2274         
2275         ntreeUpdateTree(CTX_data_main(C), ntree);
2276
2277         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2278         
2279         return OPERATOR_FINISHED;
2280 }
2281
2282 void NODE_OT_tree_socket_move(wmOperatorType *ot)
2283 {
2284         /* identifiers */
2285         ot->name = "Move Node Tree Socket";
2286         ot->description = "Move a socket up or down in the current node tree's sockets stack";
2287         ot->idname = "NODE_OT_tree_socket_move";
2288         
2289         /* api callbacks */
2290         ot->exec = ntree_socket_move_exec;
2291         ot->poll = ED_operator_node_editable;
2292         
2293         /* flags */
2294         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2295         
2296         RNA_def_enum(ot->srna, "direction", move_direction_items, 1, "Direction", "");
2297 }
2298
2299 /* ********************** Shader Script Update ******************/
2300
2301 static int node_shader_script_update_poll(bContext *C)
2302 {
2303         Scene *scene = CTX_data_scene(C);
2304         RenderEngineType *type = RE_engines_find(scene->r.engine);
2305         SpaceNode *snode = CTX_wm_space_node(C);
2306         bNode *node;
2307         Text *text;
2308
2309         /* test if we have a render engine that supports shaders scripts */
2310         if (!(type && type->update_script_node))
2311                 return 0;
2312
2313         /* see if we have a shader script node in context */
2314         node = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript).data;
2315
2316         if (!node && snode && snode->edittree)
2317                 node = nodeGetActive(snode->edittree);
2318
2319         if (node && node->type == SH_NODE_SCRIPT) {
2320                 NodeShaderScript *nss = node->storage;
2321
2322                 if (node->id || nss->filepath[0]) {
2323                         return ED_operator_node_editable(C);
2324                 }
2325         }
2326
2327         /* see if we have a text datablock in context */
2328         text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2329         if (text)
2330                 return 1;
2331
2332         /* we don't check if text datablock is actually in use, too slow for poll */
2333
2334         return 0;
2335 }
2336
2337 /* recursively check for script nodes in groups using this text and update */
2338 static bool node_shader_script_update_text_recursive(RenderEngine *engine, RenderEngineType *type, bNodeTree *ntree, Text *text)
2339 {
2340         bool found = false;
2341         bNode *node;
2342         
2343         ntree->done = true;
2344         
2345         /* update each script that is using this text datablock */
2346         for (node = ntree->nodes.first; node; node = node->next) {
2347                 if (node->type == NODE_GROUP) {
2348                         bNodeTree *ngroup = (bNodeTree *)node->id;
2349                         if (ngroup && !ngroup->done)
2350                                 found |= node_shader_script_update_text_recursive(engine, type, ngroup, text);
2351                 }
2352                 else if (node->type == SH_NODE_SCRIPT && node->id == &text->id) {
2353                         type->update_script_node(engine, ntree, node);
2354                         found = true;
2355                 }
2356         }
2357         
2358         return found;
2359 }
2360
2361 static int node_shader_script_update_exec(bContext *C, wmOperator *op)
2362 {
2363         Main *bmain = CTX_data_main(C);
2364         Scene *scene = CTX_data_scene(C);
2365         SpaceNode *snode = CTX_wm_space_node(C);
2366         PointerRNA nodeptr = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript);
2367         bNodeTree *ntree = NULL;
2368         bNode *node = NULL;
2369         RenderEngine *engine;
2370         RenderEngineType *type;
2371         bool found = false;
2372
2373         /* setup render engine */
2374         type = RE_engines_find(scene->r.engine);
2375         engine = RE_engine_create(type);
2376         engine->reports = op->reports;
2377
2378         /* get node */
2379         if (nodeptr.data) {
2380                 ntree = nodeptr.id.data;
2381                 node = nodeptr.data;
2382         }
2383         else if (snode && snode->edittree) {
2384                 ntree = snode->edittree;
2385                 node = nodeGetActive(snode->edittree);
2386         }
2387
2388         if (node) {
2389                 /* update single node */
2390                 type->update_script_node(engine, ntree, node);
2391
2392                 found = true;
2393         }
2394         else {
2395                 /* update all nodes using text datablock */
2396                 Text *text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2397
2398                 if (text) {
2399                         /* clear flags for recursion check */
2400                         FOREACH_NODETREE(bmain, ntree, id) {
2401                                 if (ntree->type == NTREE_SHADER)
2402                                         ntree->done = false;
2403                         } FOREACH_NODETREE_END
2404                         
2405                         FOREACH_NODETREE(bmain, ntree, id) {
2406                                 if (ntree->type == NTREE_SHADER) {
2407                                         if (!ntree->done)
2408                                                 found |= node_shader_script_update_text_recursive(engine, type, ntree, text);
2409                                 }
2410                         } FOREACH_NODETREE_END
2411
2412                         if (!found)
2413                                 BKE_report(op->reports, RPT_INFO, "Text not used by any node, no update done");
2414                 }
2415         }
2416
2417         RE_engine_free(engine);
2418
2419         return (found) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2420 }
2421
2422 void NODE_OT_shader_script_update(wmOperatorType *ot)
2423 {
2424         /* identifiers */
2425         ot->name = "Script Node Update";
2426         ot->description = "Update shader script node with new sockets and options from the script";
2427         ot->idname = "NODE_OT_shader_script_update";
2428
2429         /* api callbacks */
2430         ot->exec = node_shader_script_update_exec;
2431         ot->poll = node_shader_script_update_poll;
2432
2433         /* flags */
2434         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2435 }
2436
2437 /* ********************** Viewer border ******************/
2438
2439 static void viewer_border_corner_to_backdrop(SpaceNode *snode, ARegion *ar, int x, int y,
2440                                              int backdrop_width, int backdrop_height,
2441                                              float *fx, float *fy)
2442 {
2443         float bufx, bufy;
2444
2445         bufx = backdrop_width * snode->zoom;
2446         bufy = backdrop_height * snode->zoom;
2447
2448         *fx = (bufx > 0.0f ? ((float) x - 0.5f * ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
2449         *fy = (bufy > 0.0f ? ((float) y - 0.5f * ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
2450 }
2451
2452 static int viewer_border_exec(bContext *C, wmOperator *op)
2453 {
2454         Image *ima;
2455         void *lock;
2456         ImBuf *ibuf;
2457
2458         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
2459
2460         ima = BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
2461         ibuf = BKE_image_acquire_ibuf(ima, NULL, &lock);
2462
2463         if (ibuf) {
2464                 ARegion *ar = CTX_wm_region(C);
2465                 SpaceNode *snode = CTX_wm_space_node(C);
2466                 bNodeTree *btree = snode->nodetree;
2467                 rcti rect;
2468                 rctf rectf;
2469
2470                 /* get border from operator */
2471                 WM_operator_properties_border_to_rcti(op, &rect);
2472
2473                 /* convert border to unified space within backdrop image */
2474                 viewer_border_corner_to_backdrop(snode, ar, rect.xmin, rect.ymin, ibuf->x, ibuf->y,
2475                                                  &rectf.xmin, &rectf.ymin);
2476
2477                 viewer_border_corner_to_backdrop(snode, ar, rect.xmax, rect.ymax, ibuf->x, ibuf->y,
2478                                                  &rectf.xmax, &rectf.ymax);
2479
2480                 /* clamp coordinates */
2481                 rectf.xmin = max_ff(rectf.xmin, 0.0f);
2482                 rectf.ymin = max_ff(rectf.ymin, 0.0f);
2483                 rectf.xmax = min_ff(rectf.xmax, 1.0f);
2484                 rectf.ymax = min_ff(rectf.ymax, 1.0f);
2485
2486                 if (rectf.xmin < rectf.xmax && rectf.ymin < rectf.ymax) {
2487                         btree->viewer_border = rectf;
2488
2489                         if (rectf.xmin == 0.0f && rectf.ymin == 0.0f &&
2490                             rectf.xmax == 1.0f && rectf.ymax == 1.0f)
2491                         {
2492                                 btree->flag &= ~NTREE_VIEWER_BORDER;
2493                         }
2494                         else {
2495                                 btree->flag |= NTREE_VIEWER_BORDER;
2496                         }
2497
2498                         snode_notify(C, snode);
2499                         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2500                 }
2501                 else {
2502                         btree->flag &= ~NTREE_VIEWER_BORDER;
2503                 }
2504         }
2505
2506         BKE_image_release_ibuf(ima, ibuf, lock);
2507
2508         return OPERATOR_FINISHED;
2509 }
2510
2511 void NODE_OT_viewer_border(wmOperatorType *ot)
2512 {
2513         /* identifiers */
2514         ot->name = "Viewer Border";
2515         ot->description = "Set the boundaries for viewer operations";
2516         ot->idname = "NODE_OT_viewer_border";
2517
2518         /* api callbacks */
2519         ot->invoke = WM_border_select_invoke;
2520         ot->exec = viewer_border_exec;
2521         ot->modal = WM_border_select_modal;
2522         ot->cancel = WM_border_select_cancel;
2523         ot->poll = composite_node_active;
2524
2525         /* flags */
2526         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2527
2528         /* properties */
2529         WM_operator_properties_gesture_border(ot, true);
2530 }
2531
2532 static int clear_viewer_border_exec(bContext *C, wmOperator *UNUSED(op))
2533 {
2534         SpaceNode *snode = CTX_wm_space_node(C);
2535         bNodeTree *btree = snode->nodetree;
2536
2537         btree->flag &= ~NTREE_VIEWER_BORDER;
2538         snode_notify(C, snode);
2539         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2540
2541         return OPERATOR_FINISHED;
2542 }
2543
2544 void NODE_OT_clear_viewer_border(wmOperatorType *ot)
2545 {
2546         /* identifiers */
2547         ot->name = "Clear Viewer Border";
2548         ot->description = "Clear the boundaries for viewer operations";
2549         ot->idname = "NODE_OT_clear_viewer_border";
2550
2551         /* api callbacks */
2552         ot->exec = clear_viewer_border_exec;
2553         ot->poll = composite_node_active;
2554
2555         /* flags */
2556         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2557 }