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