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