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                         if (event->val == KM_RELEASE) {
933                                 node_resize_exit(C, op, false);
934                                 ED_node_post_apply_transform(C, snode->edittree);
935
936                                 return OPERATOR_FINISHED;
937                         }
938                         break;
939         }
940
941         return OPERATOR_RUNNING_MODAL;
942 }
943
944 static int node_resize_invoke(bContext *C, wmOperator *op, const wmEvent *event)
945 {
946         SpaceNode *snode = CTX_wm_space_node(C);
947         ARegion *ar = CTX_wm_region(C);
948         bNode *node = nodeGetActive(snode->edittree);
949         int dir;
950
951         if (node) {
952                 /* convert mouse coordinates to v2d space */
953                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
954                                          &snode->cursor[0], &snode->cursor[1]);
955                 dir = node->typeinfo->resize_area_func(node, snode->cursor[0], snode->cursor[1]);
956                 if (dir != 0) {
957                         node_resize_init(C, op, event, node, dir);
958                         return OPERATOR_RUNNING_MODAL;
959                 }
960         }
961         return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
962 }
963
964 static void node_resize_cancel(bContext *C, wmOperator *op)
965 {
966         node_resize_exit(C, op, true);
967 }
968
969 void NODE_OT_resize(wmOperatorType *ot)
970 {
971         /* identifiers */
972         ot->name = "Resize Node";
973         ot->idname = "NODE_OT_resize";
974         ot->description = "Resize a node";
975
976         /* api callbacks */
977         ot->invoke = node_resize_invoke;
978         ot->modal = node_resize_modal;
979         ot->poll = ED_operator_node_active;
980         ot->cancel = node_resize_cancel;
981
982         /* flags */
983         ot->flag = OPTYPE_BLOCKING;
984 }
985
986
987 /* ********************** hidden sockets ******************** */
988
989 int node_has_hidden_sockets(bNode *node)
990 {
991         bNodeSocket *sock;
992
993         for (sock = node->inputs.first; sock; sock = sock->next)
994                 if (sock->flag & SOCK_HIDDEN)
995                         return 1;
996         for (sock = node->outputs.first; sock; sock = sock->next)
997                 if (sock->flag & SOCK_HIDDEN)
998                         return 1;
999         return 0;
1000 }
1001
1002 void node_set_hidden_sockets(SpaceNode *snode, bNode *node, int set)
1003 {
1004         bNodeSocket *sock;
1005
1006         if (set == 0) {
1007                 for (sock = node->inputs.first; sock; sock = sock->next)
1008                         sock->flag &= ~SOCK_HIDDEN;
1009                 for (sock = node->outputs.first; sock; sock = sock->next)
1010                         sock->flag &= ~SOCK_HIDDEN;
1011         }
1012         else {
1013                 /* hide unused sockets */
1014                 for (sock = node->inputs.first; sock; sock = sock->next) {
1015                         if (sock->link == NULL)
1016                                 sock->flag |= SOCK_HIDDEN;
1017                 }
1018                 for (sock = node->outputs.first; sock; sock = sock->next) {
1019                         if (nodeCountSocketLinks(snode->edittree, sock) == 0)
1020                                 sock->flag |= SOCK_HIDDEN;
1021                 }
1022         }
1023 }
1024
1025
1026 /* checks snode->mouse position, and returns found node/socket */
1027 /* type is SOCK_IN and/or SOCK_OUT */
1028 int node_find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, float cursor[2], int in_out)
1029 {
1030         bNode *node;
1031         bNodeSocket *sock;
1032         rctf rect;
1033
1034         *nodep = NULL;
1035         *sockp = NULL;
1036
1037         /* check if we click in a socket */
1038         for (node = snode->edittree->nodes.first; node; node = node->next) {
1039
1040                 BLI_rctf_init_pt_radius(&rect, cursor, NODE_SOCKSIZE + 4);
1041
1042                 if (!(node->flag & NODE_HIDDEN)) {
1043                         /* extra padding inside and out - allow dragging on the text areas too */
1044                         if (in_out == SOCK_IN) {
1045                                 rect.xmax += NODE_SOCKSIZE;
1046                                 rect.xmin -= NODE_SOCKSIZE * 4;
1047                         }
1048                         else if (in_out == SOCK_OUT) {
1049                                 rect.xmax += NODE_SOCKSIZE * 4;
1050                                 rect.xmin -= NODE_SOCKSIZE;
1051                         }
1052                 }
1053
1054                 if (in_out & SOCK_IN) {
1055                         for (sock = node->inputs.first; sock; sock = sock->next) {
1056                                 if (!nodeSocketIsHidden(sock)) {
1057                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1058                                                 if (node == visible_node(snode, &rect)) {
1059                                                         *nodep = node;
1060                                                         *sockp = sock;
1061                                                         return 1;
1062                                                 }
1063                                         }
1064                                 }
1065                         }
1066                 }
1067                 if (in_out & SOCK_OUT) {
1068                         for (sock = node->outputs.first; sock; sock = sock->next) {
1069                                 if (!nodeSocketIsHidden(sock)) {
1070                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1071                                                 if (node == visible_node(snode, &rect)) {
1072                                                         *nodep = node;
1073                                                         *sockp = sock;
1074                                                         return 1;
1075                                                 }
1076                                         }
1077                                 }
1078                         }
1079                 }
1080         }
1081
1082         return 0;
1083 }
1084
1085 /* ****************** Duplicate *********************** */
1086
1087 static void node_duplicate_reparent_recursive(bNode *node)
1088 {
1089         bNode *parent;
1090
1091         node->flag |= NODE_TEST;
1092
1093         /* find first selected parent */
1094         for (parent = node->parent; parent; parent = parent->parent) {
1095                 if (parent->flag & SELECT) {
1096                         if (!(parent->flag & NODE_TEST))
1097                                 node_duplicate_reparent_recursive(parent);
1098                         break;
1099                 }
1100         }
1101         /* reparent node copy to parent copy */
1102         if (parent) {
1103                 nodeDetachNode(node->new_node);
1104                 nodeAttachNode(node->new_node, parent->new_node);
1105         }
1106 }
1107
1108 static int node_duplicate_exec(bContext *C, wmOperator *op)
1109 {
1110         Main *bmain = CTX_data_main(C);
1111         SpaceNode *snode = CTX_wm_space_node(C);
1112         bNodeTree *ntree = snode->edittree;
1113         bNode *node, *newnode, *lastnode;
1114         bNodeLink *link, *newlink, *lastlink;
1115         const bool keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
1116         bool do_tag_update = false;
1117
1118         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
1119
1120         lastnode = ntree->nodes.last;
1121         for (node = ntree->nodes.first; node; node = node->next) {
1122                 if (node->flag & SELECT) {
1123                         newnode = nodeCopyNode(ntree, node);
1124
1125                         if (newnode->id) {
1126                                 /* simple id user adjustment, node internal functions don't touch this
1127                                  * but operators and readfile.c do. */
1128                                 id_us_plus(newnode->id);
1129                                 /* to ensure redraws or rerenders happen */
1130                                 ED_node_tag_update_id(snode->id);
1131                         }
1132                 }
1133
1134                 /* make sure we don't copy new nodes again! */
1135                 if (node == lastnode)
1136                         break;
1137         }
1138
1139         /* copy links between selected nodes
1140          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
1141          */
1142         lastlink = ntree->links.last;
1143         for (link = ntree->links.first; link; link = link->next) {
1144                 /* This creates new links between copied nodes.
1145                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
1146                  */
1147                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
1148                     (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT))))
1149                 {
1150                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
1151                         newlink->flag = link->flag;
1152                         newlink->tonode = link->tonode->new_node;
1153                         newlink->tosock = link->tosock->new_sock;
1154                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
1155                                 newlink->fromnode = link->fromnode->new_node;
1156                                 newlink->fromsock = link->fromsock->new_sock;
1157                         }
1158                         else {
1159                                 /* input node not copied, this keeps the original input linked */
1160                                 newlink->fromnode = link->fromnode;
1161                                 newlink->fromsock = link->fromsock;
1162                         }
1163
1164                         BLI_addtail(&ntree->links, newlink);
1165                 }
1166
1167                 /* make sure we don't copy new links again! */
1168                 if (link == lastlink)
1169                         break;
1170         }
1171
1172         /* clear flags for recursive depth-first iteration */
1173         for (node = ntree->nodes.first; node; node = node->next)
1174                 node->flag &= ~NODE_TEST;
1175         /* reparent copied nodes */
1176         for (node = ntree->nodes.first; node; node = node->next) {
1177                 if ((node->flag & SELECT) && !(node->flag & NODE_TEST))
1178                         node_duplicate_reparent_recursive(node);
1179
1180                 /* only has to check old nodes */
1181                 if (node == lastnode)
1182                         break;
1183         }
1184
1185         /* deselect old nodes, select the copies instead */
1186         for (node = ntree->nodes.first; node; node = node->next) {
1187                 if (node->flag & SELECT) {
1188                         /* has been set during copy above */
1189                         newnode = node->new_node;
1190
1191                         nodeSetSelected(node, false);
1192                         node->flag &= ~NODE_ACTIVE;
1193                         nodeSetSelected(newnode, true);
1194
1195                         do_tag_update |= (do_tag_update || node_connected_to_output(bmain, ntree, newnode));
1196                 }
1197
1198                 /* make sure we don't copy new nodes again! */
1199                 if (node == lastnode)
1200                         break;
1201         }
1202
1203         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1204
1205         snode_notify(C, snode);
1206         if (do_tag_update) {
1207                 snode_dag_update(C, snode);
1208         }
1209
1210         return OPERATOR_FINISHED;
1211 }
1212
1213 void NODE_OT_duplicate(wmOperatorType *ot)
1214 {
1215         /* identifiers */
1216         ot->name = "Duplicate Nodes";
1217         ot->description = "Duplicate selected nodes";
1218         ot->idname = "NODE_OT_duplicate";
1219
1220         /* api callbacks */
1221         ot->exec = node_duplicate_exec;
1222         ot->poll = ED_operator_node_editable;
1223
1224         /* flags */
1225         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1226
1227         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
1228 }
1229
1230 bool ED_node_select_check(ListBase *lb)
1231
1232
1233 {
1234         bNode *node;
1235
1236         for (node = lb->first; node; node = node->next) {
1237                 if (node->flag & NODE_SELECT) {
1238                         return true;
1239                 }
1240         }
1241
1242         return false;
1243 }
1244
1245 /* ******************************** */
1246 // XXX some code needing updating to operators...
1247
1248
1249 /* goes over all scenes, reads render layers */
1250 static int node_read_viewlayers_exec(bContext *C, wmOperator *UNUSED(op))
1251 {
1252         Main *bmain = CTX_data_main(C);
1253         SpaceNode *snode = CTX_wm_space_node(C);
1254         Scene *curscene = CTX_data_scene(C), *scene;
1255         bNode *node;
1256
1257         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
1258
1259         /* first tag scenes unread */
1260         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1261                 scene->id.tag |= LIB_TAG_DOIT;
1262
1263         for (node = snode->edittree->nodes.first; node; node = node->next) {
1264                 if (node->type == CMP_NODE_R_LAYERS) {
1265                         ID *id = node->id;
1266                         if (id->tag & LIB_TAG_DOIT) {
1267                                 RE_ReadRenderResult(curscene, (Scene *)id);
1268                                 ntreeCompositTagRender((Scene *)id);
1269                                 id->tag &= ~LIB_TAG_DOIT;
1270                         }
1271                 }
1272         }
1273
1274         snode_notify(C, snode);
1275         snode_dag_update(C, snode);
1276
1277         return OPERATOR_FINISHED;
1278 }
1279
1280 void NODE_OT_read_viewlayers(wmOperatorType *ot)
1281 {
1282
1283         ot->name = "Read View Layers";
1284         ot->idname = "NODE_OT_read_viewlayers";
1285         ot->description = "Read all render layers of all used scenes";
1286
1287         ot->exec = node_read_viewlayers_exec;
1288
1289         ot->poll = composite_node_active;
1290
1291         /* flags */
1292         ot->flag = 0;
1293 }
1294
1295 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
1296 {
1297         Scene *sce = CTX_data_scene(C);
1298         bNode *node;
1299
1300         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1301                 if (node->id == (ID *)sce && node->need_exec) {
1302                         break;
1303                 }
1304         }
1305         if (node) {
1306                 ViewLayer *view_layer = BLI_findlink(&sce->view_layers, node->custom1);
1307
1308                 if (view_layer) {
1309                         PointerRNA op_ptr;
1310
1311                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
1312                         RNA_string_set(&op_ptr, "layer", view_layer->name);
1313                         RNA_string_set(&op_ptr, "scene", sce->id.name + 2);
1314
1315                         /* to keep keypositions */
1316                         sce->r.scemode |= R_NO_FRAME_UPDATE;
1317
1318                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
1319
1320                         WM_operator_properties_free(&op_ptr);
1321
1322                         return OPERATOR_FINISHED;
1323                 }
1324         }
1325         return OPERATOR_CANCELLED;
1326 }
1327
1328 void NODE_OT_render_changed(wmOperatorType *ot)
1329 {
1330         ot->name = "Render Changed Layer";
1331         ot->idname = "NODE_OT_render_changed";
1332         ot->description = "Render current scene, when input node's layer has been changed";
1333
1334         ot->exec = node_render_changed_exec;
1335
1336         ot->poll = composite_node_active;
1337
1338         /* flags */
1339         ot->flag = 0;
1340 }
1341
1342
1343 /* ****************** Hide operator *********************** */
1344
1345 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
1346 {
1347         bNode *node;
1348         int tot_eq = 0, tot_neq = 0;
1349
1350         /* Toggles the flag on all selected nodes.
1351          * If the flag is set on all nodes it is unset.
1352          * If the flag is not set on all nodes, it is set.
1353          */
1354         for (node = snode->edittree->nodes.first; node; node = node->next) {
1355                 if (node->flag & SELECT) {
1356
1357                         if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0)
1358                                 continue;
1359                         if (toggle_flag == NODE_OPTIONS && !(node->typeinfo->draw_buttons || node->typeinfo->draw_buttons_ex))
1360                                 continue;
1361
1362                         if (node->flag & toggle_flag)
1363                                 tot_eq++;
1364                         else
1365                                 tot_neq++;
1366                 }
1367         }
1368         for (node = snode->edittree->nodes.first; node; node = node->next) {
1369                 if (node->flag & SELECT) {
1370
1371                         if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0)
1372                                 continue;
1373                         if (toggle_flag == NODE_OPTIONS && !(node->typeinfo->draw_buttons || node->typeinfo->draw_buttons_ex))
1374                                 continue;
1375
1376                         if ((tot_eq && tot_neq) || tot_eq == 0)
1377                                 node->flag |= toggle_flag;
1378                         else
1379                                 node->flag &= ~toggle_flag;
1380                 }
1381         }
1382 }
1383
1384 static int node_hide_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1385 {
1386         SpaceNode *snode = CTX_wm_space_node(C);
1387
1388         /* sanity checking (poll callback checks this already) */
1389         if ((snode == NULL) || (snode->edittree == NULL))
1390                 return OPERATOR_CANCELLED;
1391
1392         node_flag_toggle_exec(snode, NODE_HIDDEN);
1393
1394         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1395
1396         return OPERATOR_FINISHED;
1397 }
1398
1399 void NODE_OT_hide_toggle(wmOperatorType *ot)
1400 {
1401         /* identifiers */
1402         ot->name = "Hide";
1403         ot->description = "Toggle hiding of selected nodes";
1404         ot->idname = "NODE_OT_hide_toggle";
1405
1406         /* callbacks */
1407         ot->exec = node_hide_toggle_exec;
1408         ot->poll = ED_operator_node_active;
1409
1410         /* flags */
1411         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1412 }
1413
1414 static int node_preview_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1415 {
1416         SpaceNode *snode = CTX_wm_space_node(C);
1417
1418         /* sanity checking (poll callback checks this already) */
1419         if ((snode == NULL) || (snode->edittree == NULL))
1420                 return OPERATOR_CANCELLED;
1421
1422         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1423
1424         node_flag_toggle_exec(snode, NODE_PREVIEW);
1425
1426         snode_notify(C, snode);
1427
1428         return OPERATOR_FINISHED;
1429 }
1430
1431 void NODE_OT_preview_toggle(wmOperatorType *ot)
1432 {
1433         /* identifiers */
1434         ot->name = "Toggle Node Preview";
1435         ot->description = "Toggle preview display for selected nodes";
1436         ot->idname = "NODE_OT_preview_toggle";
1437
1438         /* callbacks */
1439         ot->exec = node_preview_toggle_exec;
1440         ot->poll = ED_operator_node_active;
1441
1442         /* flags */
1443         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1444 }
1445
1446 static int node_options_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1447 {
1448         SpaceNode *snode = CTX_wm_space_node(C);
1449
1450         /* sanity checking (poll callback checks this already) */
1451         if ((snode == NULL) || (snode->edittree == NULL))
1452                 return OPERATOR_CANCELLED;
1453
1454         node_flag_toggle_exec(snode, NODE_OPTIONS);
1455
1456         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1457
1458         return OPERATOR_FINISHED;
1459 }
1460
1461 void NODE_OT_options_toggle(wmOperatorType *ot)
1462 {
1463         /* identifiers */
1464         ot->name = "Toggle Node Options";
1465         ot->description = "Toggle option buttons display for selected nodes";
1466         ot->idname = "NODE_OT_options_toggle";
1467
1468         /* callbacks */
1469         ot->exec = node_options_toggle_exec;
1470         ot->poll = ED_operator_node_active;
1471
1472         /* flags */
1473         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1474 }
1475
1476 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1477 {
1478         SpaceNode *snode = CTX_wm_space_node(C);
1479         bNode *node;
1480         int hidden;
1481
1482         /* sanity checking (poll callback checks this already) */
1483         if ((snode == NULL) || (snode->edittree == NULL))
1484                 return OPERATOR_CANCELLED;
1485
1486         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1487
1488         /* Toggle for all selected nodes */
1489         hidden = 0;
1490         for (node = snode->edittree->nodes.first; node; node = node->next) {
1491                 if (node->flag & SELECT) {
1492                         if (node_has_hidden_sockets(node)) {
1493                                 hidden = 1;
1494                                 break;
1495                         }
1496                 }
1497         }
1498
1499         for (node = snode->edittree->nodes.first; node; node = node->next) {
1500                 if (node->flag & SELECT) {
1501                         node_set_hidden_sockets(snode, node, !hidden);
1502                 }
1503         }
1504
1505         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1506
1507         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1508
1509         return OPERATOR_FINISHED;
1510 }
1511
1512 void NODE_OT_hide_socket_toggle(wmOperatorType *ot)
1513 {
1514         /* identifiers */
1515         ot->name = "Toggle Hidden Node Sockets";
1516         ot->description = "Toggle unused node socket display";
1517         ot->idname = "NODE_OT_hide_socket_toggle";
1518
1519         /* callbacks */
1520         ot->exec = node_socket_toggle_exec;
1521         ot->poll = ED_operator_node_active;
1522
1523         /* flags */
1524         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1525 }
1526
1527 /* ****************** Mute operator *********************** */
1528
1529 static int node_mute_exec(bContext *C, wmOperator *UNUSED(op))
1530 {
1531         Main *bmain = CTX_data_main(C);
1532         SpaceNode *snode = CTX_wm_space_node(C);
1533         bNode *node;
1534         bool do_tag_update = false;
1535
1536         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
1537
1538         for (node = snode->edittree->nodes.first; node; node = node->next) {
1539                 /* Only allow muting of nodes having a mute func! */
1540                 if ((node->flag & SELECT) && node->typeinfo->update_internal_links) {
1541                         node->flag ^= NODE_MUTED;
1542                         snode_update(snode, node);
1543                         do_tag_update |= (do_tag_update || node_connected_to_output(bmain, snode->edittree, node));
1544                 }
1545         }
1546
1547         snode_notify(C, snode);
1548         if (do_tag_update) {
1549                 snode_dag_update(C, snode);
1550         }
1551
1552         return OPERATOR_FINISHED;
1553 }
1554
1555 void NODE_OT_mute_toggle(wmOperatorType *ot)
1556 {
1557         /* identifiers */
1558         ot->name = "Toggle Node Mute";
1559         ot->description = "Toggle muting of the nodes";
1560         ot->idname = "NODE_OT_mute_toggle";
1561
1562         /* callbacks */
1563         ot->exec = node_mute_exec;
1564         ot->poll = ED_operator_node_editable;
1565
1566         /* flags */
1567         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1568 }
1569
1570 /* ****************** Delete operator ******************* */
1571
1572 static int node_delete_exec(bContext *C, wmOperator *UNUSED(op))
1573 {
1574         Main *bmain = CTX_data_main(C);
1575         SpaceNode *snode = CTX_wm_space_node(C);
1576         bNode *node, *next;
1577         bool do_tag_update = false;
1578
1579         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
1580
1581         for (node = snode->edittree->nodes.first; node; node = next) {
1582                 next = node->next;
1583                 if (node->flag & SELECT) {
1584                         /* check id user here, nodeFreeNode is called for free dbase too */
1585                         do_tag_update |= (do_tag_update || node_connected_to_output(bmain, snode->edittree, node));
1586                         if (node->id)
1587                                 id_us_min(node->id);
1588                         nodeFreeNode(snode->edittree, node);
1589                 }
1590         }
1591
1592         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1593
1594         snode_notify(C, snode);
1595         if (do_tag_update) {
1596                 snode_dag_update(C, snode);
1597         }
1598
1599         return OPERATOR_FINISHED;
1600 }
1601
1602 void NODE_OT_delete(wmOperatorType *ot)
1603 {
1604         /* identifiers */
1605         ot->name = "Delete";
1606         ot->description = "Delete selected nodes";
1607         ot->idname = "NODE_OT_delete";
1608
1609         /* api callbacks */
1610         ot->exec = node_delete_exec;
1611         ot->poll = ED_operator_node_editable;
1612
1613         /* flags */
1614         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1615 }
1616
1617 /* ****************** Switch View ******************* */
1618
1619 static int node_switch_view_poll(bContext *C)
1620 {
1621         SpaceNode *snode = CTX_wm_space_node(C);
1622
1623         if (snode && snode->edittree)
1624                 return true;
1625
1626         return false;
1627 }
1628
1629 static int node_switch_view_exec(bContext *C, wmOperator *UNUSED(op))
1630 {
1631         SpaceNode *snode = CTX_wm_space_node(C);
1632         bNode *node, *next;
1633
1634         for (node = snode->edittree->nodes.first; node; node = next) {
1635                 next = node->next;
1636                 if (node->flag & SELECT) {
1637                         /* call the update function from the Switch View node */
1638                         node->update = NODE_UPDATE_OPERATOR;
1639                 }
1640         }
1641
1642         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1643
1644         snode_notify(C, snode);
1645         snode_dag_update(C, snode);
1646
1647         return OPERATOR_FINISHED;
1648 }
1649
1650 void NODE_OT_switch_view_update(wmOperatorType *ot)
1651 {
1652         /* identifiers */
1653         ot->name = "Update Views";
1654         ot->description = "Update views of selected node";
1655         ot->idname = "NODE_OT_switch_view_update";
1656
1657         /* api callbacks */
1658         ot->exec = node_switch_view_exec;
1659         ot->poll = node_switch_view_poll;
1660
1661         /* flags */
1662         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1663 }
1664
1665 /* ****************** Delete with reconnect ******************* */
1666 static int node_delete_reconnect_exec(bContext *C, wmOperator *UNUSED(op))
1667 {
1668         SpaceNode *snode = CTX_wm_space_node(C);
1669         bNode *node, *next;
1670
1671         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1672
1673         for (node = snode->edittree->nodes.first; node; node = next) {
1674                 next = node->next;
1675                 if (node->flag & SELECT) {
1676                         nodeInternalRelink(snode->edittree, node);
1677
1678                         /* check id user here, nodeFreeNode is called for free dbase too */
1679                         if (node->id)
1680                                 id_us_min(node->id);
1681                         nodeFreeNode(snode->edittree, node);
1682                 }
1683         }
1684
1685         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1686
1687         snode_notify(C, snode);
1688         snode_dag_update(C, snode);
1689
1690         return OPERATOR_FINISHED;
1691 }
1692
1693 void NODE_OT_delete_reconnect(wmOperatorType *ot)
1694 {
1695         /* identifiers */
1696         ot->name = "Delete with Reconnect";
1697         ot->description = "Delete nodes; will reconnect nodes as if deletion was muted";
1698         ot->idname = "NODE_OT_delete_reconnect";
1699
1700         /* api callbacks */
1701         ot->exec = node_delete_reconnect_exec;
1702         ot->poll = ED_operator_node_editable;
1703
1704         /* flags */
1705         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1706 }
1707
1708
1709 /* ****************** File Output Add Socket  ******************* */
1710
1711 static int node_output_file_add_socket_exec(bContext *C, wmOperator *op)
1712 {
1713         Scene *scene = CTX_data_scene(C);
1714         SpaceNode *snode = CTX_wm_space_node(C);
1715         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1716         bNodeTree *ntree = NULL;
1717         bNode *node = NULL;
1718         char file_path[MAX_NAME];
1719
1720         if (ptr.data) {
1721                 node = ptr.data;
1722                 ntree = ptr.id.data;
1723         }
1724         else if (snode && snode->edittree) {
1725                 ntree = snode->edittree;
1726                 node = nodeGetActive(snode->edittree);
1727         }
1728
1729         if (!node || node->type != CMP_NODE_OUTPUT_FILE)
1730                 return OPERATOR_CANCELLED;
1731
1732         RNA_string_get(op->ptr, "file_path", file_path);
1733         ntreeCompositOutputFileAddSocket(ntree, node, file_path, &scene->r.im_format);
1734
1735         snode_notify(C, snode);
1736
1737         return OPERATOR_FINISHED;
1738 }
1739
1740 void NODE_OT_output_file_add_socket(wmOperatorType *ot)
1741 {
1742         /* identifiers */
1743         ot->name = "Add File Node Socket";
1744         ot->description = "Add a new input to a file output node";
1745         ot->idname = "NODE_OT_output_file_add_socket";
1746
1747         /* callbacks */
1748         ot->exec = node_output_file_add_socket_exec;
1749         ot->poll = composite_node_editable;
1750
1751         /* flags */
1752         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1753
1754         RNA_def_string(ot->srna, "file_path", "Image", MAX_NAME, "File Path", "Sub-path of the output file");
1755 }
1756
1757 /* ****************** Multi File Output Remove Socket  ******************* */
1758
1759 static int node_output_file_remove_active_socket_exec(bContext *C, wmOperator *UNUSED(op))
1760 {
1761         SpaceNode *snode = CTX_wm_space_node(C);
1762         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1763         bNodeTree *ntree = NULL;
1764         bNode *node = NULL;
1765
1766         if (ptr.data) {
1767                 node = ptr.data;
1768                 ntree = ptr.id.data;
1769         }
1770         else if (snode && snode->edittree) {
1771                 ntree = snode->edittree;
1772                 node = nodeGetActive(snode->edittree);
1773         }
1774
1775         if (!node || node->type != CMP_NODE_OUTPUT_FILE)
1776                 return OPERATOR_CANCELLED;
1777
1778         if (!ntreeCompositOutputFileRemoveActiveSocket(ntree, node))
1779                 return OPERATOR_CANCELLED;
1780
1781         snode_notify(C, snode);
1782
1783         return OPERATOR_FINISHED;
1784 }
1785
1786 void NODE_OT_output_file_remove_active_socket(wmOperatorType *ot)
1787 {
1788         /* identifiers */
1789         ot->name = "Remove File Node Socket";
1790         ot->description = "Remove active input from a file output node";
1791         ot->idname = "NODE_OT_output_file_remove_active_socket";
1792
1793         /* callbacks */
1794         ot->exec = node_output_file_remove_active_socket_exec;
1795         ot->poll = composite_node_editable;
1796
1797         /* flags */
1798         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1799 }
1800
1801 /* ****************** Multi File Output Move Socket  ******************* */
1802
1803 static int node_output_file_move_active_socket_exec(bContext *C, wmOperator *op)
1804 {
1805         SpaceNode *snode = CTX_wm_space_node(C);
1806         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1807         bNode *node = NULL;
1808         NodeImageMultiFile *nimf;
1809         bNodeSocket *sock;
1810         int direction;
1811
1812         if (ptr.data)
1813                 node = ptr.data;
1814         else if (snode && snode->edittree)
1815                 node = nodeGetActive(snode->edittree);
1816
1817         if (!node || node->type != CMP_NODE_OUTPUT_FILE)
1818                 return OPERATOR_CANCELLED;
1819
1820         nimf = node->storage;
1821
1822         sock = BLI_findlink(&node->inputs, nimf->active_input);
1823         if (!sock)
1824                 return OPERATOR_CANCELLED;
1825
1826         direction = RNA_enum_get(op->ptr, "direction");
1827
1828         if (direction == 1) {
1829                 bNodeSocket *before = sock->prev;
1830                 if (!before)
1831                         return OPERATOR_CANCELLED;
1832                 BLI_remlink(&node->inputs, sock);
1833                 BLI_insertlinkbefore(&node->inputs, before, sock);
1834                 nimf->active_input--;
1835         }
1836         else {
1837                 bNodeSocket *after = sock->next;
1838                 if (!after)
1839                         return OPERATOR_CANCELLED;
1840                 BLI_remlink(&node->inputs, sock);
1841                 BLI_insertlinkafter(&node->inputs, after, sock);
1842                 nimf->active_input++;
1843         }
1844
1845         snode_notify(C, snode);
1846
1847         return OPERATOR_FINISHED;
1848 }
1849
1850 void NODE_OT_output_file_move_active_socket(wmOperatorType *ot)
1851 {
1852         static const EnumPropertyItem direction_items[] = {
1853                 {1, "UP", 0, "Up", ""},
1854                 {2, "DOWN", 0, "Down", ""},
1855                 { 0, NULL, 0, NULL, NULL }
1856         };
1857
1858         /* identifiers */
1859         ot->name = "Move File Node Socket";
1860         ot->description = "Move the active input of a file output node up or down the list";
1861         ot->idname = "NODE_OT_output_file_move_active_socket";
1862
1863         /* callbacks */
1864         ot->exec = node_output_file_move_active_socket_exec;
1865         ot->poll = composite_node_editable;
1866
1867         /* flags */
1868         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1869
1870         RNA_def_enum(ot->srna, "direction", direction_items, 2, "Direction", "");
1871 }
1872
1873 /* ****************** Copy Node Color ******************* */
1874
1875 static int node_copy_color_exec(bContext *C, wmOperator *UNUSED(op))
1876 {
1877         SpaceNode *snode = CTX_wm_space_node(C);
1878         bNodeTree *ntree = snode->edittree;
1879         bNode *node, *tnode;
1880
1881         if (!ntree)
1882                 return OPERATOR_CANCELLED;
1883         node = nodeGetActive(ntree);
1884         if (!node)
1885                 return OPERATOR_CANCELLED;
1886
1887         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) {
1888                 if (tnode->flag & NODE_SELECT && tnode != node) {
1889                         if (node->flag & NODE_CUSTOM_COLOR) {
1890                                 tnode->flag |= NODE_CUSTOM_COLOR;
1891                                 copy_v3_v3(tnode->color, node->color);
1892                         }
1893                         else
1894                                 tnode->flag &= ~NODE_CUSTOM_COLOR;
1895                 }
1896         }
1897
1898         ED_node_sort(ntree);
1899         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1900
1901         return OPERATOR_FINISHED;
1902 }
1903
1904 void NODE_OT_node_copy_color(wmOperatorType *ot)
1905 {
1906         /* identifiers */
1907         ot->name = "Copy Color";
1908         ot->description = "Copy color to all selected nodes";
1909         ot->idname = "NODE_OT_node_copy_color";
1910
1911         /* api callbacks */
1912         ot->exec = node_copy_color_exec;
1913         ot->poll = ED_operator_node_editable;
1914
1915         /* flags */
1916         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1917 }
1918
1919 /* ****************** Copy to clipboard ******************* */
1920
1921 static int node_clipboard_copy_exec(bContext *C, wmOperator *UNUSED(op))
1922 {
1923         SpaceNode *snode = CTX_wm_space_node(C);
1924         bNodeTree *ntree = snode->edittree;
1925         bNode *node;
1926         bNodeLink *link, *newlink;
1927
1928         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1929
1930         /* clear current clipboard */
1931         BKE_node_clipboard_clear();
1932         BKE_node_clipboard_init(ntree);
1933
1934         for (node = ntree->nodes.first; node; node = node->next) {
1935                 if (node->flag & SELECT) {
1936                         bNode *new_node;
1937                         new_node = nodeCopyNode(NULL, node);
1938                         BKE_node_clipboard_add_node(new_node);
1939                 }
1940         }
1941
1942         for (node = ntree->nodes.first; node; node = node->next) {
1943                 if (node->flag & SELECT) {
1944                         bNode *new_node = node->new_node;
1945
1946                         /* ensure valid pointers */
1947                         if (new_node->parent) {
1948                                 /* parent pointer must be redirected to new node or detached if parent is not copied */
1949                                 if (new_node->parent->flag & NODE_SELECT) {
1950                                         new_node->parent = new_node->parent->new_node;
1951                                 }
1952                                 else {
1953                                         nodeDetachNode(new_node);
1954                                 }
1955                         }
1956                 }
1957         }
1958
1959         /* copy links between selected nodes
1960          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
1961          */
1962         for (link = ntree->links.first; link; link = link->next) {
1963                 /* This creates new links between copied nodes. */
1964                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
1965                     link->fromnode && (link->fromnode->flag & NODE_SELECT))
1966                 {
1967                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
1968                         newlink->flag = link->flag;
1969                         newlink->tonode = link->tonode->new_node;
1970                         newlink->tosock = link->tosock->new_sock;
1971                         newlink->fromnode = link->fromnode->new_node;
1972                         newlink->fromsock = link->fromsock->new_sock;
1973
1974                         BKE_node_clipboard_add_link(newlink);
1975                 }
1976         }
1977
1978         return OPERATOR_FINISHED;
1979 }
1980
1981 void NODE_OT_clipboard_copy(wmOperatorType *ot)
1982 {
1983         /* identifiers */
1984         ot->name = "Copy to Clipboard";
1985         ot->description = "Copies selected nodes to the clipboard";
1986         ot->idname = "NODE_OT_clipboard_copy";
1987
1988         /* api callbacks */
1989         ot->exec = node_clipboard_copy_exec;
1990         ot->poll = ED_operator_node_active;
1991
1992         /* flags */
1993         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1994 }
1995
1996 /* ****************** Paste from clipboard ******************* */
1997
1998 static int node_clipboard_paste_exec(bContext *C, wmOperator *op)
1999 {
2000         SpaceNode *snode = CTX_wm_space_node(C);
2001         bNodeTree *ntree = snode->edittree;
2002         const ListBase *clipboard_nodes_lb;
2003         const ListBase *clipboard_links_lb;
2004         bNode *node;
2005         bNodeLink *link;
2006         int num_nodes;
2007         float center[2];
2008         bool is_clipboard_valid, all_nodes_valid;
2009
2010         /* validate pointers in the clipboard */
2011         is_clipboard_valid = BKE_node_clipboard_validate();
2012         clipboard_nodes_lb = BKE_node_clipboard_get_nodes();
2013         clipboard_links_lb = BKE_node_clipboard_get_links();
2014
2015         if (BLI_listbase_is_empty(clipboard_nodes_lb)) {
2016                 BKE_report(op->reports, RPT_ERROR, "Clipboard is empty");
2017                 return OPERATOR_CANCELLED;
2018         }
2019
2020         if (BKE_node_clipboard_get_type() != ntree->type) {
2021                 BKE_report(op->reports, RPT_ERROR, "Clipboard nodes are an incompatible type");
2022                 return OPERATOR_CANCELLED;
2023         }
2024
2025         /* only warn */
2026         if (is_clipboard_valid == false) {
2027                 BKE_report(op->reports, RPT_WARNING, "Some nodes references could not be restored, will be left empty");
2028         }
2029
2030         /* make sure all clipboard nodes would be valid in the target tree */
2031         all_nodes_valid = true;
2032         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2033                 if (!node->typeinfo->poll_instance || !node->typeinfo->poll_instance(node, ntree)) {
2034                         all_nodes_valid = false;
2035                         BKE_reportf(op->reports, RPT_ERROR, "Cannot add node %s into node tree %s", node->name, ntree->id.name + 2);
2036                 }
2037         }
2038         if (!all_nodes_valid)
2039                 return OPERATOR_CANCELLED;
2040
2041         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
2042
2043         /* deselect old nodes */
2044         node_deselect_all(snode);
2045
2046         /* calculate "barycenter" for placing on mouse cursor */
2047         zero_v2(center);
2048         for (node = clipboard_nodes_lb->first, num_nodes = 0; node; node = node->next, num_nodes++) {
2049                 center[0] += BLI_rctf_cent_x(&node->totr);
2050                 center[1] += BLI_rctf_cent_y(&node->totr);
2051         }
2052         mul_v2_fl(center, 1.0 / num_nodes);
2053
2054         /* copy nodes from clipboard */
2055         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2056                 bNode *new_node = nodeCopyNode(ntree, node);
2057
2058                 /* needed since nodeCopyNode() doesn't increase ID's */
2059                 id_us_plus(node->id);
2060
2061                 /* pasted nodes are selected */
2062                 nodeSetSelected(new_node, true);
2063         }
2064
2065         /* reparent copied nodes */
2066         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2067                 bNode *new_node = node->new_node;
2068                 if (new_node->parent)
2069                         new_node->parent = new_node->parent->new_node;
2070         }
2071
2072         for (link = clipboard_links_lb->first; link; link = link->next) {
2073                 nodeAddLink(ntree, link->fromnode->new_node, link->fromsock->new_sock,
2074                             link->tonode->new_node, link->tosock->new_sock);
2075         }
2076
2077         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
2078
2079         snode_notify(C, snode);
2080         snode_dag_update(C, snode);
2081
2082         return OPERATOR_FINISHED;
2083 }
2084
2085 void NODE_OT_clipboard_paste(wmOperatorType *ot)
2086 {
2087         /* identifiers */
2088         ot->name = "Paste from Clipboard";
2089         ot->description = "Pastes nodes from the clipboard to the active node tree";
2090         ot->idname = "NODE_OT_clipboard_paste";
2091
2092         /* api callbacks */
2093         ot->exec = node_clipboard_paste_exec;
2094         ot->poll = ED_operator_node_editable;
2095
2096         /* flags */
2097         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2098 }
2099
2100 /********************** Add interface socket operator *********************/
2101
2102 static bNodeSocket *ntree_get_active_interface_socket(ListBase *lb)
2103 {
2104         bNodeSocket *sock;
2105         for (sock = lb->first; sock; sock = sock->next)
2106                 if (sock->flag & SELECT)
2107                         return sock;
2108         return NULL;
2109 }
2110
2111 static int ntree_socket_add_exec(bContext *C, wmOperator *op)
2112 {
2113         SpaceNode *snode = CTX_wm_space_node(C);
2114         bNodeTree *ntree = snode->edittree;
2115         int in_out = RNA_enum_get(op->ptr, "in_out");
2116         PointerRNA ntree_ptr;
2117         bNodeSocket *sock, *tsock, *active_sock;
2118         const char *default_name;
2119
2120         RNA_id_pointer_create((ID *)ntree, &ntree_ptr);
2121
2122         if (in_out == SOCK_IN) {
2123                 active_sock = ntree_get_active_interface_socket(&ntree->inputs);
2124                 default_name = "Input";
2125         }
2126         else {
2127                 active_sock = ntree_get_active_interface_socket(&ntree->outputs);
2128                 default_name = "Output";
2129         }
2130
2131         if (active_sock) {
2132                 /* insert a copy of the active socket right after it */
2133                 sock = ntreeInsertSocketInterface(ntree, in_out, active_sock->idname, active_sock->next, active_sock->name);
2134                 /* XXX this only works for actual sockets, not interface templates! */
2135                 /*nodeSocketCopyValue(sock, &ntree_ptr, active_sock, &ntree_ptr);*/
2136         }
2137         else {
2138                 /* XXX TODO define default socket type for a tree! */
2139                 sock = ntreeAddSocketInterface(ntree, in_out, "NodeSocketFloat", default_name);
2140         }
2141
2142         /* deactivate sockets (has to check both lists) */
2143         for (tsock = ntree->inputs.first; tsock; tsock = tsock->next)
2144                 tsock->flag &= ~SELECT;
2145         for (tsock = ntree->outputs.first; tsock; tsock = tsock->next)
2146                 tsock->flag &= ~SELECT;
2147         /* make the new socket active */
2148         sock->flag |= SELECT;
2149
2150         ntreeUpdateTree(CTX_data_main(C), ntree);
2151
2152         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2153
2154         return OPERATOR_FINISHED;
2155 }
2156
2157 void NODE_OT_tree_socket_add(wmOperatorType *ot)
2158 {
2159         /* identifiers */
2160         ot->name = "Add Node Tree Interface Socket";
2161         ot->description = "Add an input or output socket to the current node tree";
2162         ot->idname = "NODE_OT_tree_socket_add";
2163
2164         /* api callbacks */
2165         ot->exec = ntree_socket_add_exec;
2166         ot->poll = ED_operator_node_editable;
2167
2168         /* flags */
2169         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2170
2171         RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Type", "");
2172 }
2173
2174 /********************** Remove interface socket operator *********************/
2175
2176 static int ntree_socket_remove_exec(bContext *C, wmOperator *UNUSED(op))
2177 {
2178         SpaceNode *snode = CTX_wm_space_node(C);
2179         bNodeTree *ntree = snode->edittree;
2180         bNodeSocket *iosock, *active_sock;
2181
2182         iosock = ntree_get_active_interface_socket(&ntree->inputs);
2183         if (!iosock)
2184                 iosock = ntree_get_active_interface_socket(&ntree->outputs);
2185         if (!iosock)
2186                 return OPERATOR_CANCELLED;
2187
2188         /* preferably next socket becomes active, otherwise try previous socket */
2189         active_sock = (iosock->next ? iosock->next : iosock->prev);
2190         ntreeRemoveSocketInterface(ntree, iosock);
2191
2192         /* set active socket */
2193         if (active_sock)
2194                 active_sock->flag |= SELECT;
2195
2196         ntreeUpdateTree(CTX_data_main(C), ntree);
2197
2198         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2199
2200         return OPERATOR_FINISHED;
2201 }
2202
2203 void NODE_OT_tree_socket_remove(wmOperatorType *ot)
2204 {
2205         /* identifiers */
2206         ot->name = "Remove Node Tree Interface Socket";
2207         ot->description = "Remove an input or output socket to the current node tree";
2208         ot->idname = "NODE_OT_tree_socket_remove";
2209
2210         /* api callbacks */
2211         ot->exec = ntree_socket_remove_exec;
2212         ot->poll = ED_operator_node_editable;
2213
2214         /* flags */
2215         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2216 }
2217
2218 /********************** Move interface socket operator *********************/
2219
2220 static const EnumPropertyItem move_direction_items[] = {
2221         { 1, "UP", 0, "Up", "" },
2222         { 2, "DOWN", 0, "Down", "" },
2223         { 0, NULL, 0, NULL, NULL },
2224 };
2225
2226 static int ntree_socket_move_exec(bContext *C, wmOperator *op)
2227 {
2228         SpaceNode *snode = CTX_wm_space_node(C);
2229         bNodeTree *ntree = snode->edittree;
2230         int direction = RNA_enum_get(op->ptr, "direction");
2231         bNodeSocket *iosock;
2232         ListBase *lb;
2233
2234         lb = &ntree->inputs;
2235         iosock = ntree_get_active_interface_socket(lb);
2236         if (!iosock) {
2237                 lb = &ntree->outputs;
2238                 iosock = ntree_get_active_interface_socket(lb);
2239         }
2240         if (!iosock)
2241                 return OPERATOR_CANCELLED;
2242
2243         switch (direction) {
2244                 case 1:
2245                 {       /* up */
2246                         bNodeSocket *before = iosock->prev;
2247                         BLI_remlink(lb, iosock);
2248                         if (before)
2249                                 BLI_insertlinkbefore(lb, before, iosock);
2250                         else
2251                                 BLI_addhead(lb, iosock);
2252                         break;
2253                 }
2254                 case 2:
2255                 {       /* down */
2256                         bNodeSocket *after = iosock->next;
2257                         BLI_remlink(lb, iosock);
2258                         if (after)
2259                                 BLI_insertlinkafter(lb, after, iosock);
2260                         else
2261                                 BLI_addtail(lb, iosock);
2262                         break;
2263                 }
2264         }
2265
2266         ntreeUpdateTree(CTX_data_main(C), ntree);
2267
2268         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2269
2270         return OPERATOR_FINISHED;
2271 }
2272
2273 void NODE_OT_tree_socket_move(wmOperatorType *ot)
2274 {
2275         /* identifiers */
2276         ot->name = "Move Node Tree Socket";
2277         ot->description = "Move a socket up or down in the current node tree's sockets stack";
2278         ot->idname = "NODE_OT_tree_socket_move";
2279
2280         /* api callbacks */
2281         ot->exec = ntree_socket_move_exec;
2282         ot->poll = ED_operator_node_editable;
2283
2284         /* flags */
2285         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2286
2287         RNA_def_enum(ot->srna, "direction", move_direction_items, 1, "Direction", "");
2288 }
2289
2290 /* ********************** Shader Script Update ******************/
2291
2292 static int node_shader_script_update_poll(bContext *C)
2293 {
2294         Scene *scene = CTX_data_scene(C);
2295         RenderEngineType *type = RE_engines_find(scene->r.engine);
2296         SpaceNode *snode = CTX_wm_space_node(C);
2297         bNode *node;
2298         Text *text;
2299
2300         /* test if we have a render engine that supports shaders scripts */
2301         if (!(type && type->update_script_node))
2302                 return 0;
2303
2304         /* see if we have a shader script node in context */
2305         node = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript).data;
2306
2307         if (!node && snode && snode->edittree)
2308                 node = nodeGetActive(snode->edittree);
2309
2310         if (node && node->type == SH_NODE_SCRIPT) {
2311                 NodeShaderScript *nss = node->storage;
2312
2313                 if (node->id || nss->filepath[0]) {
2314                         return ED_operator_node_editable(C);
2315                 }
2316         }
2317
2318         /* see if we have a text datablock in context */
2319         text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2320         if (text)
2321                 return 1;
2322
2323         /* we don't check if text datablock is actually in use, too slow for poll */
2324
2325         return 0;
2326 }
2327
2328 /* recursively check for script nodes in groups using this text and update */
2329 static bool node_shader_script_update_text_recursive(RenderEngine *engine, RenderEngineType *type, bNodeTree *ntree, Text *text)
2330 {
2331         bool found = false;
2332         bNode *node;
2333
2334         ntree->done = true;
2335
2336         /* update each script that is using this text datablock */
2337         for (node = ntree->nodes.first; node; node = node->next) {
2338                 if (node->type == NODE_GROUP) {
2339                         bNodeTree *ngroup = (bNodeTree *)node->id;
2340                         if (ngroup && !ngroup->done)
2341                                 found |= node_shader_script_update_text_recursive(engine, type, ngroup, text);
2342                 }
2343                 else if (node->type == SH_NODE_SCRIPT && node->id == &text->id) {
2344                         type->update_script_node(engine, ntree, node);
2345                         found = true;
2346                 }
2347         }
2348
2349         return found;
2350 }
2351
2352 static int node_shader_script_update_exec(bContext *C, wmOperator *op)
2353 {
2354         Main *bmain = CTX_data_main(C);
2355         Scene *scene = CTX_data_scene(C);
2356         SpaceNode *snode = CTX_wm_space_node(C);
2357         PointerRNA nodeptr = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript);
2358         bNodeTree *ntree_base = NULL;
2359         bNode *node = NULL;
2360         RenderEngine *engine;
2361         RenderEngineType *type;
2362         bool found = false;
2363
2364         /* setup render engine */
2365         type = RE_engines_find(scene->r.engine);
2366         engine = RE_engine_create(type);
2367         engine->reports = op->reports;
2368
2369         /* get node */
2370         if (nodeptr.data) {
2371                 ntree_base = nodeptr.id.data;
2372                 node = nodeptr.data;
2373         }
2374         else if (snode && snode->edittree) {
2375                 ntree_base = snode->edittree;
2376                 node = nodeGetActive(snode->edittree);
2377         }
2378
2379         if (node) {
2380                 /* update single node */
2381                 type->update_script_node(engine, ntree_base, node);
2382
2383                 found = true;
2384         }
2385         else {
2386                 /* update all nodes using text datablock */
2387                 Text *text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2388
2389                 if (text) {
2390                         /* clear flags for recursion check */
2391                         FOREACH_NODETREE(bmain, ntree, id) {
2392                                 if (ntree->type == NTREE_SHADER)
2393                                         ntree->done = false;
2394                         } FOREACH_NODETREE_END
2395
2396                         FOREACH_NODETREE(bmain, ntree, id) {
2397                                 if (ntree->type == NTREE_SHADER) {
2398                                         if (!ntree->done)
2399                                                 found |= node_shader_script_update_text_recursive(engine, type, ntree, text);
2400                                 }
2401                         } FOREACH_NODETREE_END
2402
2403                         if (!found)
2404                                 BKE_report(op->reports, RPT_INFO, "Text not used by any node, no update done");
2405                 }
2406         }
2407
2408         RE_engine_free(engine);
2409
2410         return (found) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2411 }
2412
2413 void NODE_OT_shader_script_update(wmOperatorType *ot)
2414 {
2415         /* identifiers */
2416         ot->name = "Script Node Update";
2417         ot->description = "Update shader script node with new sockets and options from the script";
2418         ot->idname = "NODE_OT_shader_script_update";
2419
2420         /* api callbacks */
2421         ot->exec = node_shader_script_update_exec;
2422         ot->poll = node_shader_script_update_poll;
2423
2424         /* flags */
2425         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2426 }
2427
2428 /* ********************** Viewer border ******************/
2429
2430 static void viewer_border_corner_to_backdrop(SpaceNode *snode, ARegion *ar, int x, int y,
2431                                              int backdrop_width, int backdrop_height,
2432                                              float *fx, float *fy)
2433 {
2434         float bufx, bufy;
2435
2436         bufx = backdrop_width * snode->zoom;
2437         bufy = backdrop_height * snode->zoom;
2438
2439         *fx = (bufx > 0.0f ? ((float) x - 0.5f * ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
2440         *fy = (bufy > 0.0f ? ((float) y - 0.5f * ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
2441 }
2442
2443 static int viewer_border_exec(bContext *C, wmOperator *op)
2444 {
2445         Main *bmain = CTX_data_main(C);
2446         Image *ima;
2447         void *lock;
2448         ImBuf *ibuf;
2449
2450         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
2451
2452         ima = BKE_image_verify_viewer(bmain, IMA_TYPE_COMPOSITE, "Viewer Node");
2453         ibuf = BKE_image_acquire_ibuf(ima, NULL, &lock);
2454
2455         if (ibuf) {
2456                 ARegion *ar = CTX_wm_region(C);
2457                 SpaceNode *snode = CTX_wm_space_node(C);
2458                 bNodeTree *btree = snode->nodetree;
2459                 rcti rect;
2460                 rctf rectf;
2461
2462                 /* get border from operator */
2463                 WM_operator_properties_border_to_rcti(op, &rect);
2464
2465                 /* convert border to unified space within backdrop image */
2466                 viewer_border_corner_to_backdrop(snode, ar, rect.xmin, rect.ymin, ibuf->x, ibuf->y,
2467                                                  &rectf.xmin, &rectf.ymin);
2468
2469                 viewer_border_corner_to_backdrop(snode, ar, rect.xmax, rect.ymax, ibuf->x, ibuf->y,
2470                                                  &rectf.xmax, &rectf.ymax);
2471
2472                 /* clamp coordinates */
2473                 rectf.xmin = max_ff(rectf.xmin, 0.0f);
2474                 rectf.ymin = max_ff(rectf.ymin, 0.0f);
2475                 rectf.xmax = min_ff(rectf.xmax, 1.0f);
2476                 rectf.ymax = min_ff(rectf.ymax, 1.0f);
2477
2478                 if (rectf.xmin < rectf.xmax && rectf.ymin < rectf.ymax) {
2479                         btree->viewer_border = rectf;
2480
2481                         if (rectf.xmin == 0.0f && rectf.ymin == 0.0f &&
2482                             rectf.xmax == 1.0f && rectf.ymax == 1.0f)
2483                         {
2484                                 btree->flag &= ~NTREE_VIEWER_BORDER;
2485                         }
2486                         else {
2487                                 btree->flag |= NTREE_VIEWER_BORDER;
2488                         }
2489
2490                         snode_notify(C, snode);
2491                         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2492                 }
2493                 else {
2494                         btree->flag &= ~NTREE_VIEWER_BORDER;
2495                 }
2496         }
2497
2498         BKE_image_release_ibuf(ima, ibuf, lock);
2499
2500         return OPERATOR_FINISHED;
2501 }
2502
2503 void NODE_OT_viewer_border(wmOperatorType *ot)
2504 {
2505         /* identifiers */
2506         ot->name = "Viewer Border";
2507         ot->description = "Set the boundaries for viewer operations";
2508         ot->idname = "NODE_OT_viewer_border";
2509
2510         /* api callbacks */
2511         ot->invoke = WM_gesture_border_invoke;
2512         ot->exec = viewer_border_exec;
2513         ot->modal = WM_gesture_border_modal;
2514         ot->cancel = WM_gesture_border_cancel;
2515         ot->poll = composite_node_active;
2516
2517         /* flags */
2518         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2519
2520         /* properties */
2521         WM_operator_properties_gesture_border_select(ot);
2522 }
2523
2524 static int clear_viewer_border_exec(bContext *C, wmOperator *UNUSED(op))
2525 {
2526         SpaceNode *snode = CTX_wm_space_node(C);
2527         bNodeTree *btree = snode->nodetree;
2528
2529         btree->flag &= ~NTREE_VIEWER_BORDER;
2530         snode_notify(C, snode);
2531         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2532
2533         return OPERATOR_FINISHED;
2534 }
2535
2536 void NODE_OT_clear_viewer_border(wmOperatorType *ot)
2537 {
2538         /* identifiers */
2539         ot->name = "Clear Viewer Border";
2540         ot->description = "Clear the boundaries for viewer operations";
2541         ot->idname = "NODE_OT_clear_viewer_border";
2542
2543         /* api callbacks */
2544         ot->exec = clear_viewer_border_exec;
2545         ot->poll = composite_node_active;
2546
2547         /* flags */
2548         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2549 }