Merge branch 'master' into blender2.8
[blender.git] / source / blender / render / intern / source / pipeline.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) 2006 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/render/intern/source/pipeline.c
29  *  \ingroup render
30  */
31
32 #include <math.h>
33 #include <limits.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stddef.h>
37 #include <errno.h>
38
39 #include "DNA_anim_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_image_types.h"
42 #include "DNA_node_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_particle_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_sequence_types.h"
47 #include "DNA_userdef_types.h"
48
49 #include "MEM_guardedalloc.h"
50
51 #include "BLI_math.h"
52 #include "BLI_rect.h"
53 #include "BLI_listbase.h"
54 #include "BLI_string.h"
55 #include "BLI_path_util.h"
56 #include "BLI_timecode.h"
57 #include "BLI_fileops.h"
58 #include "BLI_threads.h"
59 #include "BLI_rand.h"
60 #include "BLI_callbacks.h"
61
62 #include "BLT_translation.h"
63
64 #include "BKE_animsys.h"  /* <------ should this be here?, needed for sequencer update */
65 #include "BKE_camera.h"
66 #include "BKE_colortools.h"
67 #include "BKE_global.h"
68 #include "BKE_image.h"
69 #include "BKE_layer.h"
70 #include "BKE_library.h"
71 #include "BKE_library_remap.h"
72 #include "BKE_main.h"
73 #include "BKE_modifier.h"
74 #include "BKE_node.h"
75 #include "BKE_pointcache.h"
76 #include "BKE_report.h"
77 #include "BKE_scene.h"
78 #include "BKE_sequencer.h"
79 #include "BKE_sound.h"
80 #include "BKE_writeavi.h"  /* <------ should be replaced once with generic movie module */
81 #include "BKE_object.h"
82
83 #include "DEG_depsgraph.h"
84 #include "DEG_depsgraph_build.h"
85 #include "DEG_depsgraph_query.h"
86
87 #include "PIL_time.h"
88 #include "IMB_colormanagement.h"
89 #include "IMB_imbuf.h"
90 #include "IMB_imbuf_types.h"
91 #include "IMB_metadata.h"
92
93 #include "RE_engine.h"
94 #include "RE_pipeline.h"
95 #include "RE_render_ext.h"
96
97 #include "../../../windowmanager/WM_api.h" /* XXX */
98 #include "../../../intern/gawain/gawain/gwn_context.h"
99
100 #ifdef WITH_FREESTYLE
101 #  include "FRS_freestyle.h"
102 #endif
103
104 #include "DEG_depsgraph.h"
105
106 /* internal */
107 #include "initrender.h"
108 #include "renderpipeline.h"
109 #include "render_result.h"
110 #include "render_types.h"
111
112 /* render flow
113  *
114  * 1) Initialize state
115  * - state data, tables
116  * - movie/image file init
117  * - everything that doesn't change during animation
118  *
119  * 2) Initialize data
120  * - camera, world, matrices
121  * - make render verts, faces, halos, strands
122  * - everything can change per frame/field
123  *
124  * 3) Render Processor
125  * - multiple layers
126  * - tiles, rect, baking
127  * - layers/tiles optionally to disk or directly in Render Result
128  *
129  * 4) Composite Render Result
130  * - also read external files etc
131  *
132  * 5) Image Files
133  * - save file or append in movie
134  *
135  */
136
137
138 /* ********* globals ******** */
139
140 /* here we store all renders */
141 static struct {
142         ListBase renderlist;
143 } RenderGlobal = {{NULL, NULL}};
144
145 /* ********* alloc and free ******** */
146
147 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const int totvideos, const char *name_override);
148
149 /* default callbacks, set in each new render */
150 static void result_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr)) {}
151 static void result_rcti_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect)) {}
152 static void current_scene_nothing(void *UNUSED(arg), Scene *UNUSED(scene)) {}
153 static void stats_nothing(void *UNUSED(arg), RenderStats *UNUSED(rs)) {}
154 static void float_nothing(void *UNUSED(arg), float UNUSED(val)) {}
155 static int default_break(void *UNUSED(arg)) { return G.is_break == true; }
156
157 static void stats_background(void *UNUSED(arg), RenderStats *rs)
158 {
159         uintptr_t mem_in_use, mmap_in_use, peak_memory;
160         float megs_used_memory, mmap_used_memory, megs_peak_memory;
161         char info_time_str[32];
162
163         mem_in_use = MEM_get_memory_in_use();
164         mmap_in_use = MEM_get_mapped_memory_in_use();
165         peak_memory = MEM_get_peak_memory();
166
167         megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
168         mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
169         megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
170
171         fprintf(stdout, IFACE_("Fra:%d Mem:%.2fM (%.2fM, Peak %.2fM) "), rs->cfra,
172                 megs_used_memory, mmap_used_memory, megs_peak_memory);
173
174         if (rs->curfield)
175                 fprintf(stdout, IFACE_("Field %d "), rs->curfield);
176         if (rs->curblur)
177                 fprintf(stdout, IFACE_("Blur %d "), rs->curblur);
178
179         BLI_timecode_string_from_time_simple(info_time_str, sizeof(info_time_str), PIL_check_seconds_timer() - rs->starttime);
180         fprintf(stdout, IFACE_("| Time:%s | "), info_time_str);
181
182         if (rs->infostr) {
183                 fprintf(stdout, "%s", rs->infostr);
184         }
185         else {
186                 if (rs->tothalo)
187                         fprintf(stdout, IFACE_("Sce: %s Ve:%d Fa:%d Ha:%d La:%d"),
188                                 rs->scene_name, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
189                 else
190                         fprintf(stdout, IFACE_("Sce: %s Ve:%d Fa:%d La:%d"), rs->scene_name, rs->totvert, rs->totface, rs->totlamp);
191         }
192
193         /* Flush stdout to be sure python callbacks are printing stuff after blender. */
194         fflush(stdout);
195
196         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
197
198         fputc('\n', stdout);
199         fflush(stdout);
200 }
201
202 static void render_print_save_message(
203         ReportList *reports, const char *name, int ok, int err)
204 {
205         if (ok) {
206                 /* no need to report, just some helpful console info */
207                 printf("Saved: '%s'\n", name);
208         }
209         else {
210                 /* report on error since users will want to know what failed */
211                 BKE_reportf(reports, RPT_ERROR, "Render error (%s) cannot save: '%s'", strerror(err), name);
212         }
213 }
214
215 static int render_imbuf_write_stamp_test(
216         ReportList *reports,
217         Scene *scene, struct RenderResult *rr, ImBuf *ibuf, const char *name,
218         const ImageFormatData *imf, bool stamp)
219 {
220         int ok;
221
222         if (stamp) {
223                 /* writes the name of the individual cameras */
224                 ok = BKE_imbuf_write_stamp(scene, rr, ibuf, name, imf);
225         }
226         else {
227                 ok = BKE_imbuf_write(ibuf, name, imf);
228         }
229
230         render_print_save_message(reports, name, ok, errno);
231
232         return ok;
233 }
234
235 void RE_FreeRenderResult(RenderResult *res)
236 {
237         render_result_free(res);
238 }
239
240 float *RE_RenderLayerGetPass(volatile RenderLayer *rl, const char *name, const char *viewname)
241 {
242         RenderPass *rpass = RE_pass_find_by_name(rl, name, viewname);
243         return rpass ? rpass->rect : NULL;
244 }
245
246 RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
247 {
248         if (rr == NULL) {
249                 return NULL;
250         }
251         else {
252                 return BLI_findstring(&rr->layers, name, offsetof(RenderLayer, name));
253         }
254 }
255
256 bool RE_HasSingleLayer(Render *re)
257 {
258         return (re->r.scemode & R_SINGLE_LAYER);
259 }
260
261 RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, bool predivide, int rectx, int recty)
262 {
263         return render_result_new_from_exr(exrhandle, colorspace, predivide, rectx, recty);
264 }
265
266 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
267 {
268         ViewLayer *view_layer = BLI_findlink(&re->view_layers, re->active_view_layer);
269
270         if (view_layer) {
271                 RenderLayer *rl = BLI_findstring(&rr->layers,
272                                                  view_layer->name,
273                                                  offsetof(RenderLayer, name));
274
275                 if (rl) {
276                         return rl;
277                 }
278         }
279
280         return rr->layers.first;
281 }
282
283 static bool render_scene_has_layers_to_render(Scene *scene, ViewLayer *single_layer)
284 {
285         if (single_layer) {
286                 return true;
287         }
288
289         ViewLayer *view_layer;
290         for (view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
291                 if (view_layer->flag & VIEW_LAYER_RENDER) {
292                         return true;
293                 }
294         }
295         return false;
296 }
297
298 /* *************************************************** */
299
300 Render *RE_GetRender(const char *name)
301 {
302         Render *re;
303
304         /* search for existing renders */
305         for (re = RenderGlobal.renderlist.first; re; re = re->next)
306                 if (STREQLEN(re->name, name, RE_MAXNAME))
307                         break;
308
309         return re;
310 }
311
312 /* if you want to know exactly what has been done */
313 RenderResult *RE_AcquireResultRead(Render *re)
314 {
315         if (re) {
316                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
317                 return re->result;
318         }
319
320         return NULL;
321 }
322
323 RenderResult *RE_AcquireResultWrite(Render *re)
324 {
325         if (re) {
326                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
327                 return re->result;
328         }
329
330         return NULL;
331 }
332
333 void RE_ClearResult(Render *re)
334 {
335         if (re) {
336                 render_result_free(re->result);
337                 re->result = NULL;
338         }
339 }
340
341 void RE_SwapResult(Render *re, RenderResult **rr)
342 {
343         /* for keeping render buffers */
344         if (re) {
345                 SWAP(RenderResult *, re->result, *rr);
346         }
347 }
348
349
350 void RE_ReleaseResult(Render *re)
351 {
352         if (re)
353                 BLI_rw_mutex_unlock(&re->resultmutex);
354 }
355
356 /* displist.c util.... */
357 Scene *RE_GetScene(Render *re)
358 {
359         if (re)
360                 return re->scene;
361         return NULL;
362 }
363
364 /**
365  * Same as #RE_AcquireResultImage but creating the necessary views to store the result
366  * fill provided result struct with a copy of thew views of what is done so far the
367  * #RenderResult.views #ListBase needs to be freed after with #RE_ReleaseResultImageViews
368  */
369 void RE_AcquireResultImageViews(Render *re, RenderResult *rr)
370 {
371         memset(rr, 0, sizeof(RenderResult));
372
373         if (re) {
374                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
375
376                 if (re->result) {
377                         RenderLayer *rl;
378                         RenderView *rv, *rview;
379
380                         rr->rectx = re->result->rectx;
381                         rr->recty = re->result->recty;
382
383                         /* creates a temporary duplication of views */
384                         render_result_views_shallowcopy(rr, re->result);
385
386                         rv = rr->views.first;
387                         rr->have_combined = (rv->rectf != NULL);
388
389                         /* active layer */
390                         rl = render_get_active_layer(re, re->result);
391
392                         if (rl) {
393                                 if (rv->rectf == NULL) {
394                                         for (rview = (RenderView *)rr->views.first; rview; rview = rview->next) {
395                                                 rview->rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, rview->name);
396                                         }
397                                 }
398
399                                 if (rv->rectz == NULL) {
400                                         for (rview = (RenderView *)rr->views.first; rview; rview = rview->next) {
401                                                 rview->rectz = RE_RenderLayerGetPass(rl, RE_PASSNAME_Z, rview->name);
402                                         }
403                                 }
404                         }
405
406                         rr->layers = re->result->layers;
407                         rr->xof = re->disprect.xmin;
408                         rr->yof = re->disprect.ymin;
409                         rr->stamp_data = re->result->stamp_data;
410                 }
411         }
412 }
413
414 /* clear temporary renderresult struct */
415 void RE_ReleaseResultImageViews(Render *re, RenderResult *rr)
416 {
417         if (re) {
418                 if (rr) {
419                         render_result_views_shallowdelete(rr);
420                 }
421                 BLI_rw_mutex_unlock(&re->resultmutex);
422         }
423 }
424
425 /* fill provided result struct with what's currently active or done */
426 /* this RenderResult struct is the only exception to the rule of a RenderResult */
427 /* always having at least one RenderView */
428 void RE_AcquireResultImage(Render *re, RenderResult *rr, const int view_id)
429 {
430         memset(rr, 0, sizeof(RenderResult));
431
432         if (re) {
433                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
434
435                 if (re->result) {
436                         RenderLayer *rl;
437                         RenderView *rv;
438
439                         rr->rectx = re->result->rectx;
440                         rr->recty = re->result->recty;
441
442                         /* actview view */
443                         rv = RE_RenderViewGetById(re->result, view_id);
444                         rr->have_combined = (rv->rectf != NULL);
445
446                         rr->rectf = rv->rectf;
447                         rr->rectz = rv->rectz;
448                         rr->rect32 = rv->rect32;
449
450                         /* active layer */
451                         rl = render_get_active_layer(re, re->result);
452
453                         if (rl) {
454                                 if (rv->rectf == NULL)
455                                         rr->rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, rv->name);
456
457                                 if (rv->rectz == NULL)
458                                         rr->rectz = RE_RenderLayerGetPass(rl, RE_PASSNAME_Z, rv->name);
459                         }
460
461                         rr->layers = re->result->layers;
462                         rr->views = re->result->views;
463
464                         rr->xof = re->disprect.xmin;
465                         rr->yof = re->disprect.ymin;
466
467                         rr->stamp_data = re->result->stamp_data;
468                 }
469         }
470 }
471
472 void RE_ReleaseResultImage(Render *re)
473 {
474         if (re)
475                 BLI_rw_mutex_unlock(&re->resultmutex);
476 }
477
478 /* caller is responsible for allocating rect in correct size! */
479 void RE_ResultGet32(Render *re, unsigned int *rect)
480 {
481         RenderResult rres;
482         const int view_id = BKE_scene_multiview_view_id_get(&re->r, re->viewname);
483
484         RE_AcquireResultImageViews(re, &rres);
485         render_result_rect_get_pixels(&rres, rect, re->rectx, re->recty, &re->scene->view_settings, &re->scene->display_settings, view_id);
486         RE_ReleaseResultImageViews(re, &rres);
487 }
488
489 /* caller is responsible for allocating rect in correct size! */
490 /* Only for acquired results, for lock */
491 void RE_AcquiredResultGet32(Render *re, RenderResult *result, unsigned int *rect, const int view_id)
492 {
493         render_result_rect_get_pixels(result, rect, re->rectx, re->recty, &re->scene->view_settings, &re->scene->display_settings, view_id);
494 }
495
496 RenderStats *RE_GetStats(Render *re)
497 {
498         return &re->i;
499 }
500
501 Render *RE_NewRender(const char *name)
502 {
503         Render *re;
504
505         /* only one render per name exists */
506         re = RE_GetRender(name);
507         if (re == NULL) {
508
509                 /* new render data struct */
510                 re = MEM_callocN(sizeof(Render), "new render");
511                 BLI_addtail(&RenderGlobal.renderlist, re);
512                 BLI_strncpy(re->name, name, RE_MAXNAME);
513                 BLI_rw_mutex_init(&re->resultmutex);
514                 BLI_rw_mutex_init(&re->partsmutex);
515         }
516
517         RE_InitRenderCB(re);
518
519         return re;
520 }
521
522 /* MAX_ID_NAME + sizeof(Library->name) + space + null-terminator. */
523 #define MAX_SCENE_RENDER_NAME (MAX_ID_NAME + 1024 + 2)
524
525 static void scene_render_name_get(const Scene *scene,
526                                   const size_t max_size,
527                                   char *render_name)
528 {
529         if (ID_IS_LINKED(scene)) {
530                 BLI_snprintf(render_name, max_size, "%s %s",
531                              scene->id.lib->id.name, scene->id.name);
532         }
533         else {
534                 BLI_snprintf(render_name, max_size, "%s", scene->id.name);
535         }
536 }
537
538 Render *RE_GetSceneRender(const Scene *scene)
539 {
540         char render_name[MAX_SCENE_RENDER_NAME];
541         scene_render_name_get(scene, sizeof(render_name), render_name);
542         return RE_GetRender(render_name);
543 }
544
545 Render *RE_NewSceneRender(const Scene *scene)
546 {
547         char render_name[MAX_SCENE_RENDER_NAME];
548         scene_render_name_get(scene, sizeof(render_name), render_name);
549         return RE_NewRender(render_name);
550 }
551
552 /* called for new renders and when finishing rendering so
553  * we always have valid callbacks on a render */
554 void RE_InitRenderCB(Render *re)
555 {
556         /* set default empty callbacks */
557         re->display_init = result_nothing;
558         re->display_clear = result_nothing;
559         re->display_update = result_rcti_nothing;
560         re->current_scene_update = current_scene_nothing;
561         re->progress = float_nothing;
562         re->test_break = default_break;
563         if (G.background)
564                 re->stats_draw = stats_background;
565         else
566                 re->stats_draw = stats_nothing;
567         /* clear callback handles */
568         re->dih = re->dch = re->duh = re->sdh = re->prh = re->tbh = NULL;
569 }
570
571 /* only call this while you know it will remove the link too */
572 void RE_FreeRender(Render *re)
573 {
574         if (re->engine)
575                 RE_engine_free(re->engine);
576
577         BLI_rw_mutex_end(&re->resultmutex);
578         BLI_rw_mutex_end(&re->partsmutex);
579
580         BLI_freelistN(&re->view_layers);
581         BLI_freelistN(&re->r.views);
582
583         curvemapping_free_data(&re->r.mblur_shutter_curve);
584
585         /* main dbase can already be invalid now, some database-free code checks it */
586         re->main = NULL;
587         re->scene = NULL;
588
589         render_result_free(re->result);
590         render_result_free(re->pushedresult);
591
592         BLI_remlink(&RenderGlobal.renderlist, re);
593         MEM_freeN(re);
594 }
595
596 /* exit blender */
597 void RE_FreeAllRender(void)
598 {
599         while (RenderGlobal.renderlist.first) {
600                 RE_FreeRender(RenderGlobal.renderlist.first);
601         }
602
603 #ifdef WITH_FREESTYLE
604         /* finalize Freestyle */
605         FRS_exit();
606 #endif
607 }
608
609 void RE_FreeAllPersistentData(void)
610 {
611         Render *re;
612         for (re = RenderGlobal.renderlist.first; re != NULL; re = re->next) {
613                 if ((re->r.mode & R_PERSISTENT_DATA) != 0 && re->engine != NULL) {
614                         RE_engine_free(re->engine);
615                         re->engine = NULL;
616                 }
617         }
618 }
619
620 /* on file load, free all re */
621 void RE_FreeAllRenderResults(void)
622 {
623         Render *re;
624
625         for (re = RenderGlobal.renderlist.first; re; re = re->next) {
626                 render_result_free(re->result);
627                 render_result_free(re->pushedresult);
628
629                 re->result = NULL;
630                 re->pushedresult = NULL;
631         }
632 }
633
634 void RE_FreePersistentData(void)
635 {
636         Render *re;
637
638         /* render engines can be kept around for quick re-render, this clears all */
639         for (re = RenderGlobal.renderlist.first; re; re = re->next) {
640                 if (re->engine) {
641                         /* if engine is currently rendering, just tag it to be freed when render is finished */
642                         if (!(re->engine->flag & RE_ENGINE_RENDERING))
643                                 RE_engine_free(re->engine);
644
645                         re->engine = NULL;
646                 }
647         }
648 }
649
650 /* ********* initialize state ******** */
651
652 /* clear full sample and tile flags if needed */
653 static int check_mode_full_sample(RenderData *rd)
654 {
655         int scemode = rd->scemode;
656
657         /* not supported by any current renderer */
658         scemode &= ~R_FULL_SAMPLE;
659
660 #ifdef WITH_OPENEXR
661         if (scemode & R_FULL_SAMPLE)
662                 scemode |= R_EXR_TILE_FILE;   /* enable automatic */
663 #else
664         /* can't do this without openexr support */
665         scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
666 #endif
667
668         return scemode;
669 }
670
671 static void re_init_resolution(Render *re, Render *source,
672                                int winx, int winy, rcti *disprect)
673 {
674         re->winx = winx;
675         re->winy = winy;
676         if (source && (source->r.mode & R_BORDER)) {
677                 /* eeh, doesn't seem original bordered disprect is storing anywhere
678                  * after insertion on black happening in do_render(),
679                  * so for now simply re-calculate disprect using border from source
680                  * renderer (sergey)
681                  */
682
683                 re->disprect.xmin = source->r.border.xmin * winx;
684                 re->disprect.xmax = source->r.border.xmax * winx;
685
686                 re->disprect.ymin = source->r.border.ymin * winy;
687                 re->disprect.ymax = source->r.border.ymax * winy;
688
689                 re->rectx = BLI_rcti_size_x(&re->disprect);
690                 re->recty = BLI_rcti_size_y(&re->disprect);
691
692                 /* copy border itself, since it could be used by external engines */
693                 re->r.border = source->r.border;
694         }
695         else if (disprect) {
696                 re->disprect = *disprect;
697                 re->rectx = BLI_rcti_size_x(&re->disprect);
698                 re->recty = BLI_rcti_size_y(&re->disprect);
699         }
700         else {
701                 re->disprect.xmin = re->disprect.ymin = 0;
702                 re->disprect.xmax = winx;
703                 re->disprect.ymax = winy;
704                 re->rectx = winx;
705                 re->recty = winy;
706         }
707 }
708
709 void render_copy_renderdata(RenderData *to, RenderData *from)
710 {
711         BLI_freelistN(&to->views);
712         curvemapping_free_data(&to->mblur_shutter_curve);
713
714         *to = *from;
715
716         BLI_duplicatelist(&to->views, &from->views);
717         curvemapping_copy_data(&to->mblur_shutter_curve, &from->mblur_shutter_curve);
718 }
719
720 /* what doesn't change during entire render sequence */
721 /* disprect is optional, if NULL it assumes full window render */
722 void RE_InitState(Render *re, Render *source, RenderData *rd,
723                   ListBase *render_layers, ViewLayer *single_layer,
724                   int winx, int winy, rcti *disprect)
725 {
726         bool had_freestyle = (re->r.mode & R_EDGE_FRS) != 0;
727
728         re->ok = true;   /* maybe flag */
729
730         re->i.starttime = PIL_check_seconds_timer();
731
732         /* copy render data and render layers for thread safety */
733         render_copy_renderdata(&re->r, rd);
734         BLI_freelistN(&re->view_layers);
735         BLI_duplicatelist(&re->view_layers, render_layers);
736         re->active_view_layer = 0;
737
738         if (source) {
739                 /* reuse border flags from source renderer */
740                 re->r.mode &= ~(R_BORDER | R_CROP);
741                 re->r.mode |= source->r.mode & (R_BORDER | R_CROP);
742
743                 /* dimensions shall be shared between all renderers */
744                 re->r.xsch = source->r.xsch;
745                 re->r.ysch = source->r.ysch;
746                 re->r.size = source->r.size;
747         }
748
749         re_init_resolution(re, source, winx, winy, disprect);
750
751         /* disable border if it's a full render anyway */
752         if (re->r.border.xmin == 0.0f && re->r.border.xmax == 1.0f &&
753             re->r.border.ymin == 0.0f && re->r.border.ymax == 1.0f)
754         {
755                 re->r.mode &= ~R_BORDER;
756         }
757
758         if (re->rectx < 1 || re->recty < 1 || (BKE_imtype_is_movie(rd->im_format.imtype) &&
759                                                (re->rectx < 16 || re->recty < 16) ))
760         {
761                 BKE_report(re->reports, RPT_ERROR, "Image too small");
762                 re->ok = 0;
763                 return;
764         }
765
766         re->r.scemode = check_mode_full_sample(&re->r);
767
768         if (single_layer) {
769                 int index = BLI_findindex(render_layers, single_layer);
770                 if (index != -1) {
771                         re->active_view_layer = index;
772                         re->r.scemode |= R_SINGLE_LAYER;
773                 }
774         }
775
776         /* if preview render, we try to keep old result */
777         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
778
779         if (re->r.scemode & R_BUTS_PREVIEW) {
780                 if (had_freestyle || (re->r.mode & R_EDGE_FRS)) {
781                         /* freestyle manipulates render layers so always have to free */
782                         render_result_free(re->result);
783                         re->result = NULL;
784                 }
785                 else if (re->result) {
786                         ViewLayer *active_render_layer = BLI_findlink(&re->view_layers, re->active_view_layer);
787                         RenderLayer *rl;
788                         bool have_layer = false;
789
790                         for (rl = re->result->layers.first; rl; rl = rl->next)
791                                 if (STREQ(rl->name, active_render_layer->name))
792                                         have_layer = true;
793
794                         if (re->result->rectx == re->rectx && re->result->recty == re->recty &&
795                             have_layer)
796                         {
797                                 /* keep render result, this avoids flickering black tiles
798                                  * when the preview changes */
799                         }
800                         else {
801                                 /* free because resolution changed */
802                                 render_result_free(re->result);
803                                 re->result = NULL;
804                         }
805                 }
806         }
807         else {
808
809                 /* make empty render result, so display callbacks can initialize */
810                 render_result_free(re->result);
811                 re->result = MEM_callocN(sizeof(RenderResult), "new render result");
812                 re->result->rectx = re->rectx;
813                 re->result->recty = re->recty;
814                 render_result_view_new(re->result, "");
815         }
816
817         /* ensure renderdatabase can use part settings correct */
818         RE_parts_clamp(re);
819
820         BLI_rw_mutex_unlock(&re->resultmutex);
821
822         RE_init_threadcount(re);
823
824         RE_point_density_fix_linking();
825 }
826
827 /* This function is only called by view3d rendering, which doesn't support
828  * multiview at the moment. so handle only one view here */
829 static void render_result_rescale(Render *re)
830 {
831         RenderResult *result = re->result;
832         RenderView *rv;
833         int x, y;
834         float scale_x, scale_y;
835         float *src_rectf;
836
837         rv = RE_RenderViewGetById(result, 0);
838         src_rectf = rv->rectf;
839
840         if (src_rectf == NULL) {
841                 RenderLayer *rl = render_get_active_layer(re, re->result);
842                 if (rl != NULL) {
843                         src_rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, NULL);
844                 }
845         }
846
847         if (src_rectf != NULL) {
848                 float *dst_rectf = NULL;
849                 re->result = render_result_new(re,
850                                                &re->disprect,
851                                                0,
852                                                RR_USE_MEM,
853                                                RR_ALL_LAYERS,
854                                                "");
855
856                 if (re->result != NULL) {
857                         dst_rectf = RE_RenderViewGetById(re->result, 0)->rectf;
858                         if (dst_rectf == NULL) {
859                                 RenderLayer *rl;
860                                 rl = render_get_active_layer(re, re->result);
861                                 if (rl != NULL) {
862                                         dst_rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, NULL);
863                                 }
864                         }
865
866                         scale_x = (float) result->rectx / re->result->rectx;
867                         scale_y = (float) result->recty / re->result->recty;
868                         for (x = 0; x < re->result->rectx; ++x) {
869                                 for (y = 0; y < re->result->recty; ++y) {
870                                         int src_x = x * scale_x;
871                                         int src_y = y * scale_y;
872                                         int dst_index = y * re->result->rectx + x;
873                                         int src_index = src_y * result->rectx + src_x;
874                                         copy_v4_v4(dst_rectf + dst_index * 4,
875                                                    src_rectf + src_index * 4);
876                                 }
877                         }
878                 }
879                 render_result_free(result);
880         }
881 }
882
883 void RE_ChangeResolution(Render *re, int winx, int winy, rcti *disprect)
884 {
885         re_init_resolution(re, NULL, winx, winy, disprect);
886         RE_parts_clamp(re);
887
888         if (re->result) {
889                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
890                 render_result_rescale(re);
891                 BLI_rw_mutex_unlock(&re->resultmutex);
892         }
893 }
894
895 /* TODO(sergey): This is a bit hackish, used to temporary disable freestyle when
896  * doing viewport render. Needs some better integration of BI viewport rendering
897  * into the pipeline.
898  */
899 void RE_ChangeModeFlag(Render *re, int flag, bool clear)
900 {
901         if (clear) {
902                 re->r.mode &= ~flag;
903         }
904         else {
905                 re->r.mode |= flag;
906         }
907 }
908
909 /* update some variables that can be animated, and otherwise wouldn't be due to
910  * RenderData getting copied once at the start of animation render */
911 void render_update_anim_renderdata(Render *re, RenderData *rd, ListBase *render_layers)
912 {
913         /* filter */
914         re->r.gauss = rd->gauss;
915
916         /* motion blur */
917         re->r.blurfac = rd->blurfac;
918
919         /* freestyle */
920         re->r.line_thickness_mode = rd->line_thickness_mode;
921         re->r.unit_line_thickness = rd->unit_line_thickness;
922
923         /* render layers */
924         BLI_freelistN(&re->view_layers);
925         BLI_duplicatelist(&re->view_layers, render_layers);
926
927         /* render views */
928         BLI_freelistN(&re->r.views);
929         BLI_duplicatelist(&re->r.views, &rd->views);
930 }
931
932 void RE_SetWindow(Render *re, const rctf *viewplane, float clipsta, float clipend)
933 {
934         /* re->ok flag? */
935
936         re->viewplane = *viewplane;
937         re->clipsta = clipsta;
938         re->clipend = clipend;
939         re->r.mode &= ~R_ORTHO;
940
941         perspective_m4(re->winmat,
942                        re->viewplane.xmin, re->viewplane.xmax,
943                        re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
944
945 }
946
947 void RE_SetOrtho(Render *re, const rctf *viewplane, float clipsta, float clipend)
948 {
949         /* re->ok flag? */
950
951         re->viewplane = *viewplane;
952         re->clipsta = clipsta;
953         re->clipend = clipend;
954         re->r.mode |= R_ORTHO;
955
956         orthographic_m4(re->winmat,
957                         re->viewplane.xmin, re->viewplane.xmax,
958                         re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
959 }
960
961 void RE_SetView(Render *re, float mat[4][4])
962 {
963         /* re->ok flag? */
964         copy_m4_m4(re->viewmat, mat);
965         invert_m4_m4(re->viewinv, re->viewmat);
966 }
967
968 void RE_GetViewPlane(Render *re, rctf *r_viewplane, rcti *r_disprect)
969 {
970         *r_viewplane = re->viewplane;
971
972         /* make disprect zero when no border render, is needed to detect changes in 3d view render */
973         if (re->r.mode & R_BORDER) {
974                 *r_disprect = re->disprect;
975         }
976         else {
977                 BLI_rcti_init(r_disprect, 0, 0, 0, 0);
978         }
979 }
980
981 void RE_GetView(Render *re, float mat[4][4])
982 {
983         copy_m4_m4(mat, re->viewmat);
984 }
985
986 /* image and movie output has to move to either imbuf or kernel */
987 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
988 {
989         re->display_init = f;
990         re->dih = handle;
991 }
992 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
993 {
994         re->display_clear = f;
995         re->dch = handle;
996 }
997 void RE_display_update_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
998 {
999         re->display_update = f;
1000         re->duh = handle;
1001 }
1002 void RE_current_scene_update_cb(Render *re, void *handle, void (*f)(void *handle, Scene *scene))
1003 {
1004         re->current_scene_update = f;
1005         re->suh = handle;
1006 }
1007 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
1008 {
1009         re->stats_draw = f;
1010         re->sdh = handle;
1011 }
1012 void RE_progress_cb(Render *re, void *handle, void (*f)(void *handle, float))
1013 {
1014         re->progress = f;
1015         re->prh = handle;
1016 }
1017
1018 void RE_draw_lock_cb(Render *re, void *handle, void (*f)(void *handle, int i))
1019 {
1020         re->draw_lock = f;
1021         re->dlh = handle;
1022 }
1023
1024 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
1025 {
1026         re->test_break = f;
1027         re->tbh = handle;
1028 }
1029
1030 /* ********* GL Context ******** */
1031
1032 /* Create the gl context of the Render.
1033  * It will be free by the render itself. */
1034 void RE_gl_context_create(Render *re)
1035 {
1036         /* Needs to be created in the main ogl thread. */
1037         re->gl_context = WM_opengl_context_create();
1038         re->gl_context_ownership = true;
1039 }
1040
1041 void RE_gl_context_destroy(Render *re)
1042 {
1043         /* Needs to be called from the thread which used the ogl context for rendering. */
1044         if (re->gwn_context) {
1045                 GWN_context_active_set(re->gwn_context);
1046                 GWN_context_discard(re->gwn_context);
1047                 re->gwn_context = NULL;
1048         }
1049         if (re->gl_context) {
1050                 if (re->gl_context_ownership) {
1051                         WM_opengl_context_dispose(re->gl_context);
1052                 }
1053                 re->gl_context = NULL;
1054         }
1055 }
1056
1057 /* Manually set the gl context of the Render.
1058  * It won't be free by the render itself. */
1059 void RE_gl_context_set(Render *re, void *gl_context)
1060 {
1061         BLI_assert(gl_context); /* Cannot set NULL */
1062         re->gl_context = gl_context;
1063         re->gl_context_ownership = false;
1064 }
1065
1066 void *RE_gl_context_get(Render *re)
1067 {
1068         return re->gl_context;
1069 }
1070
1071 void *RE_gwn_context_get(Render *re)
1072 {
1073         if (re->gwn_context == NULL) {
1074                 re->gwn_context = GWN_context_create();
1075         }
1076         return re->gwn_context;
1077 }
1078
1079 /* ********* add object data (later) ******** */
1080
1081 /* object is considered fully prepared on correct time etc */
1082 /* includes lights */
1083 #if 0
1084 void RE_AddObject(Render *UNUSED(re), Object *UNUSED(ob))
1085 {
1086
1087 }
1088 #endif
1089
1090 /* *************************************** */
1091
1092 #ifdef WITH_FREESTYLE
1093 static void init_freestyle(Render *re);
1094 static void add_freestyle(Render *re, int render);
1095 static void free_all_freestyle_renders(void);
1096 #endif
1097
1098
1099 /* ************  This part uses API, for rendering Blender scenes ********** */
1100
1101 static void do_render_3d(Render *re)
1102 {
1103         re->current_scene_update(re->suh, re->scene);
1104         RE_engine_render(re, 0);
1105 }
1106
1107 /* make sure disprect is not affected by the render border */
1108 static void render_result_disprect_to_full_resolution(Render *re)
1109 {
1110         re->disprect.xmin = re->disprect.ymin = 0;
1111         re->disprect.xmax = re->winx;
1112         re->disprect.ymax = re->winy;
1113         re->rectx = re->winx;
1114         re->recty = re->winy;
1115 }
1116
1117 static void render_result_uncrop(Render *re)
1118 {
1119         /* when using border render with crop disabled, insert render result into
1120          * full size with black pixels outside */
1121         if (re->result && (re->r.mode & R_BORDER)) {
1122                 if ((re->r.mode & R_CROP) == 0) {
1123                         RenderResult *rres;
1124
1125                         /* backup */
1126                         const rcti orig_disprect = re->disprect;
1127                         const int  orig_rectx = re->rectx, orig_recty = re->recty;
1128
1129                         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1130
1131                         /* sub-rect for merge call later on */
1132                         re->result->tilerect = re->disprect;
1133
1134                         /* weak is: it chances disprect from border */
1135                         render_result_disprect_to_full_resolution(re);
1136
1137                         rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS, RR_ALL_VIEWS);
1138
1139                         render_result_clone_passes(re, rres, NULL);
1140
1141                         render_result_merge(rres, re->result);
1142                         render_result_free(re->result);
1143                         re->result = rres;
1144
1145                         /* weak... the display callback wants an active renderlayer pointer... */
1146                         re->result->renlay = render_get_active_layer(re, re->result);
1147
1148                         BLI_rw_mutex_unlock(&re->resultmutex);
1149
1150                         re->display_init(re->dih, re->result);
1151                         re->display_update(re->duh, re->result, NULL);
1152
1153                         /* restore the disprect from border */
1154                         re->disprect = orig_disprect;
1155                         re->rectx = orig_rectx;
1156                         re->recty = orig_recty;
1157                 }
1158                 else {
1159                         /* set offset (again) for use in compositor, disprect was manipulated. */
1160                         re->result->xof = 0;
1161                         re->result->yof = 0;
1162                 }
1163         }
1164 }
1165
1166 /* main render routine, no compositing */
1167 static void do_render(Render *re)
1168 {
1169         Object *camera = RE_GetCamera(re);
1170         /* also check for camera here */
1171         if (camera == NULL) {
1172                 BKE_report(re->reports, RPT_ERROR, "Cannot render, no camera");
1173                 G.is_break = true;
1174                 return;
1175         }
1176
1177         /* now use renderdata and camera to set viewplane */
1178         RE_SetCamera(re, camera);
1179
1180         do_render_3d(re);
1181
1182         /* when border render, check if we have to insert it in black */
1183         render_result_uncrop(re);
1184 }
1185
1186
1187 /* within context of current Render *re, render another scene.
1188  * it uses current render image size and disprect, but doesn't execute composite
1189  */
1190 static void render_scene(Render *re, Scene *sce, int cfra)
1191 {
1192         Render *resc = RE_NewSceneRender(sce);
1193         int winx = re->winx, winy = re->winy;
1194
1195         sce->r.cfra = cfra;
1196
1197         BKE_scene_camera_switch_update(sce);
1198
1199         /* exception: scene uses own size (unfinished code) */
1200         if (0) {
1201                 winx = (sce->r.size * sce->r.xsch) / 100;
1202                 winy = (sce->r.size * sce->r.ysch) / 100;
1203         }
1204
1205         /* initial setup */
1206         RE_InitState(resc, re, &sce->r, &sce->view_layers, NULL, winx, winy, &re->disprect);
1207
1208         /* We still want to use 'rendercache' setting from org (main) scene... */
1209         resc->r.scemode = (resc->r.scemode & ~R_EXR_CACHE_FILE) | (re->r.scemode & R_EXR_CACHE_FILE);
1210
1211         /* still unsure entity this... */
1212         resc->main = re->main;
1213         resc->scene = sce;
1214         resc->lay = sce->lay;
1215
1216         /* ensure scene has depsgraph, base flags etc OK */
1217         BKE_scene_set_background(re->main, sce);
1218
1219         /* copy callbacks */
1220         resc->display_update = re->display_update;
1221         resc->duh = re->duh;
1222         resc->test_break = re->test_break;
1223         resc->tbh = re->tbh;
1224         resc->stats_draw = re->stats_draw;
1225         resc->sdh = re->sdh;
1226         resc->current_scene_update = re->current_scene_update;
1227         resc->suh = re->suh;
1228
1229         do_render(resc);
1230 }
1231
1232 /* helper call to detect if this scene needs a render, or if there's a any render layer to render */
1233 static int composite_needs_render(Scene *sce, int this_scene)
1234 {
1235         bNodeTree *ntree = sce->nodetree;
1236         bNode *node;
1237
1238         if (ntree == NULL) return 1;
1239         if (sce->use_nodes == false) return 1;
1240         if ((sce->r.scemode & R_DOCOMP) == 0) return 1;
1241
1242         for (node = ntree->nodes.first; node; node = node->next) {
1243                 if (node->type == CMP_NODE_R_LAYERS && (node->flag & NODE_MUTED) == 0)
1244                         if (this_scene == 0 || node->id == NULL || node->id == &sce->id)
1245                                 return 1;
1246         }
1247         return 0;
1248 }
1249
1250 bool RE_allow_render_generic_object(Object *ob)
1251 {
1252         /* override not showing object when duplis are used with particles */
1253         if (ob->transflag & OB_DUPLIPARTS) {
1254                 /* pass */  /* let particle system(s) handle showing vs. not showing */
1255         }
1256         else if ((ob->transflag & OB_DUPLI) && !(ob->transflag & OB_DUPLIFRAMES)) {
1257                 return false;
1258         }
1259         return true;
1260 }
1261
1262 static void ntree_render_scenes(Render *re)
1263 {
1264         bNode *node;
1265         int cfra = re->scene->r.cfra;
1266         Scene *restore_scene = re->scene;
1267         bool scene_changed = false;
1268
1269         if (re->scene->nodetree == NULL) return;
1270
1271         /* now foreach render-result node tagged we do a full render */
1272         /* results are stored in a way compisitor will find it */
1273         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1274                 if (node->type == CMP_NODE_R_LAYERS && (node->flag & NODE_MUTED) == 0) {
1275                         if (node->id && node->id != (ID *)re->scene) {
1276                                 if (node->flag & NODE_TEST) {
1277                                         Scene *scene = (Scene *)node->id;
1278
1279                                         scene_changed |= scene != restore_scene;
1280                                         render_scene(re, scene, cfra);
1281                                         node->flag &= ~NODE_TEST;
1282
1283                                         nodeUpdate(restore_scene->nodetree, node);
1284                                 }
1285                         }
1286                 }
1287         }
1288
1289         /* restore scene if we rendered another last */
1290         if (scene_changed)
1291                 BKE_scene_set_background(re->main, re->scene);
1292 }
1293
1294 /* bad call... need to think over proper method still */
1295 static void render_composit_stats(void *arg, const char *str)
1296 {
1297         Render *re = (Render*)arg;
1298
1299         RenderStats i;
1300         memcpy(&i, &re->i, sizeof(i));
1301         i.infostr = str;
1302         re->stats_draw(re->sdh, &i);
1303 }
1304
1305 #ifdef WITH_FREESTYLE
1306 /* init Freestyle renderer */
1307 static void init_freestyle(Render *re)
1308 {
1309         re->freestyle_bmain = BKE_main_new();
1310
1311         /* We use the same window manager for freestyle bmain as
1312          * real bmain uses. This is needed because freestyle's
1313          * bmain could be used to tag scenes for update, which
1314          * implies call of ED_render_scene_update in some cases
1315          * and that function requires proper window manager
1316          * to present (sergey)
1317          */
1318         re->freestyle_bmain->wm = re->main->wm;
1319
1320         FRS_init_stroke_renderer(re);
1321 }
1322
1323 /* invokes Freestyle stroke rendering */
1324 static void add_freestyle(Render *re, int render)
1325 {
1326         ViewLayer *view_layer, *active_view_layer;
1327         LinkData *link;
1328         Render *r;
1329
1330         active_view_layer = BLI_findlink(&re->view_layers, re->active_view_layer);
1331
1332         FRS_begin_stroke_rendering(re);
1333
1334         for (view_layer = (ViewLayer *)re->view_layers.first; view_layer; view_layer = view_layer->next) {
1335                 link = (LinkData *)MEM_callocN(sizeof(LinkData), "LinkData to Freestyle render");
1336                 BLI_addtail(&re->freestyle_renders, link);
1337
1338                 if ((re->r.scemode & R_SINGLE_LAYER) && view_layer != active_view_layer)
1339                         continue;
1340                 if (FRS_is_freestyle_enabled(view_layer)) {
1341                         r = FRS_do_stroke_rendering(re, view_layer, render);
1342                         link->data = (void *)r;
1343                 }
1344         }
1345
1346         FRS_end_stroke_rendering(re);
1347 }
1348
1349 /* releases temporary scenes and renders for Freestyle stroke rendering */
1350 static void free_all_freestyle_renders(void)
1351 {
1352         Render *re1, *freestyle_render;
1353         Scene *freestyle_scene;
1354         LinkData *link;
1355
1356         for (re1= RenderGlobal.renderlist.first; re1; re1= re1->next) {
1357                 for (link = (LinkData *)re1->freestyle_renders.first; link; link = link->next) {
1358                         freestyle_render = (Render *)link->data;
1359
1360                         if (freestyle_render) {
1361                                 freestyle_scene = freestyle_render->scene;
1362                                 RE_FreeRender(freestyle_render);
1363                                 BKE_libblock_unlink(re1->freestyle_bmain, freestyle_scene, false, false);
1364                                 BKE_libblock_free(re1->freestyle_bmain, freestyle_scene);
1365                         }
1366                 }
1367                 BLI_freelistN(&re1->freestyle_renders);
1368
1369                 if (re1->freestyle_bmain) {
1370                         /* detach the window manager from freestyle bmain (see comments
1371                          * in add_freestyle() for more detail)
1372                          */
1373                         BLI_listbase_clear(&re1->freestyle_bmain->wm);
1374
1375                         BKE_main_free(re1->freestyle_bmain);
1376                         re1->freestyle_bmain = NULL;
1377                 }
1378         }
1379 }
1380 #endif
1381
1382 /* returns fully composited render-result on given time step (in RenderData) */
1383 static void do_render_composite(Render *re)
1384 {
1385         bNodeTree *ntree = re->scene->nodetree;
1386         int update_newframe = 0;
1387
1388         if (composite_needs_render(re->scene, 1)) {
1389                 /* save memory... free all cached images */
1390                 ntreeFreeCache(ntree);
1391
1392                 /* render the frames
1393                  * it could be optimized to render only the needed view
1394                  * but what if a scene has a different number of views
1395                  * than the main scene? */
1396                 do_render(re);
1397         }
1398         else {
1399                 re->i.cfra = re->r.cfra;
1400
1401                 /* ensure new result gets added, like for regular renders */
1402                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1403
1404                 render_result_free(re->result);
1405                 if ((re->r.mode & R_CROP) == 0) {
1406                         render_result_disprect_to_full_resolution(re);
1407                 }
1408                 re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS, RR_ALL_VIEWS);
1409
1410                 BLI_rw_mutex_unlock(&re->resultmutex);
1411
1412                 /* scene render process already updates animsys */
1413                 update_newframe = 1;
1414         }
1415
1416         /* swap render result */
1417         if (re->r.scemode & R_SINGLE_LAYER) {
1418                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1419                 render_result_single_layer_end(re);
1420                 BLI_rw_mutex_unlock(&re->resultmutex);
1421         }
1422
1423         if (!re->test_break(re->tbh)) {
1424
1425                 if (ntree) {
1426                         ntreeCompositTagRender(re->scene);
1427                         ntreeCompositTagAnimated(ntree);
1428                 }
1429
1430                 if (ntree && re->scene->use_nodes && re->r.scemode & R_DOCOMP) {
1431                         /* checks if there are render-result nodes that need scene */
1432                         if ((re->r.scemode & R_SINGLE_LAYER) == 0)
1433                                 ntree_render_scenes(re);
1434
1435                         if (!re->test_break(re->tbh)) {
1436                                 ntree->stats_draw = render_composit_stats;
1437                                 ntree->test_break = re->test_break;
1438                                 ntree->progress = re->progress;
1439                                 ntree->sdh = re;
1440                                 ntree->tbh = re->tbh;
1441                                 ntree->prh = re->prh;
1442
1443                                 if (update_newframe) {
1444                                         /* If we have consistent depsgraph now would be a time to update them. */
1445                                 }
1446
1447                                 RenderView *rv;
1448                                 for (rv = re->result->views.first; rv; rv = rv->next) {
1449                                         ntreeCompositExecTree(re->scene, ntree, &re->r, true, G.background == 0, &re->scene->view_settings, &re->scene->display_settings, rv->name);
1450                                 }
1451
1452                                 ntree->stats_draw = NULL;
1453                                 ntree->test_break = NULL;
1454                                 ntree->progress = NULL;
1455                                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1456                         }
1457                 }
1458         }
1459
1460 #ifdef WITH_FREESTYLE
1461         free_all_freestyle_renders();
1462 #endif
1463
1464         /* weak... the display callback wants an active renderlayer pointer... */
1465         if (re->result != NULL) {
1466                 re->result->renlay = render_get_active_layer(re, re->result);
1467                 re->display_update(re->duh, re->result, NULL);
1468         }
1469 }
1470
1471 static void renderresult_stampinfo(Render *re)
1472 {
1473         RenderResult rres;
1474         RenderView *rv;
1475         int nr;
1476
1477         /* this is the basic trick to get the displayed float or char rect from render result */
1478         nr = 0;
1479         for (rv = re->result->views.first;rv;rv = rv->next, nr++) {
1480                 RE_SetActiveRenderView(re, rv->name);
1481                 RE_AcquireResultImage(re, &rres, nr);
1482                 BKE_image_stamp_buf(re->scene,
1483                                     RE_GetCamera(re),
1484                                     (re->r.stamp & R_STAMP_STRIPMETA) ? rres.stamp_data : NULL,
1485                                     (unsigned char *)rres.rect32,
1486                                     rres.rectf,
1487                                     rres.rectx, rres.recty,
1488                                     4);
1489                 RE_ReleaseResultImage(re);
1490         }
1491 }
1492
1493 int RE_seq_render_active(Scene *scene, RenderData *rd)
1494 {
1495         Editing *ed;
1496         Sequence *seq;
1497
1498         ed = scene->ed;
1499
1500         if (!(rd->scemode & R_DOSEQ) || !ed || !ed->seqbase.first)
1501                 return 0;
1502
1503         for (seq = ed->seqbase.first; seq; seq = seq->next) {
1504                 if (seq->type != SEQ_TYPE_SOUND_RAM)
1505                         return 1;
1506         }
1507
1508         return 0;
1509 }
1510
1511 static void do_render_seq(Render *re)
1512 {
1513         static int recurs_depth = 0;
1514         struct ImBuf *out;
1515         RenderResult *rr; /* don't assign re->result here as it might change during give_ibuf_seq */
1516         int cfra = re->r.cfra;
1517         SeqRenderData context;
1518         int view_id, tot_views;
1519         struct ImBuf **ibuf_arr;
1520         int re_x, re_y;
1521
1522         re->i.cfra = cfra;
1523
1524         if (recurs_depth == 0) {
1525                 /* otherwise sequencer animation isn't updated */
1526                 /* TODO(sergey): Currently depsgraph is only used to check whether it is an active
1527                  * edit window or not to deal with unkeyed changes. We don't have depsgraph here yet,
1528                  * but we also dont' deal with unkeyed changes. But still nice to get proper depsgraph
1529                  * within tjhe render pipeline, somehow.
1530                  */
1531                 BKE_animsys_evaluate_all_animation(re->main, NULL, re->scene, (float)cfra); // XXX, was BKE_scene_frame_get(re->scene)
1532         }
1533
1534         recurs_depth++;
1535
1536         if ((re->r.mode & R_BORDER) && (re->r.mode & R_CROP) == 0) {
1537                 /* if border rendering is used and cropping is disabled, final buffer should
1538                  * be as large as the whole frame */
1539                 re_x = re->winx;
1540                 re_y = re->winy;
1541         }
1542         else {
1543                 re_x = re->result->rectx;
1544                 re_y = re->result->recty;
1545         }
1546
1547         tot_views = BKE_scene_multiview_num_views_get(&re->r);
1548         ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * tot_views, "Sequencer Views ImBufs");
1549
1550         /* TODO(sergey): Currently depsgraph is only used to check whether it is an active
1551          * edit window or not to deal with unkeyed changes. We don't have depsgraph here yet,
1552          * but we also dont' deal with unkeyed changes. But still nice to get proper depsgraph
1553          * within tjhe render pipeline, somehow.
1554          */
1555         BKE_sequencer_new_render_data(
1556                 re->main, NULL, re->scene,
1557                 re_x, re_y, 100, true,
1558                 &context);
1559
1560         /* the renderresult gets destroyed during the rendering, so we first collect all ibufs
1561          * and then we populate the final renderesult */
1562
1563         for (view_id = 0; view_id < tot_views; view_id++) {
1564                 context.view_id = view_id;
1565                 out = BKE_sequencer_give_ibuf(&context, cfra, 0);
1566
1567                 if (out) {
1568                         ibuf_arr[view_id] = IMB_dupImBuf(out);
1569                         IMB_metadata_copy(ibuf_arr[view_id], out);
1570                         IMB_freeImBuf(out);
1571                         BKE_sequencer_imbuf_from_sequencer_space(re->scene, ibuf_arr[view_id]);
1572                 }
1573                 else {
1574                         ibuf_arr[view_id] = NULL;
1575                 }
1576         }
1577
1578         rr = re->result;
1579
1580         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1581         render_result_views_new(rr, &re->r);
1582         BLI_rw_mutex_unlock(&re->resultmutex);
1583
1584         for (view_id = 0; view_id < tot_views; view_id++) {
1585                 RenderView *rv = RE_RenderViewGetById(rr, view_id);
1586                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1587
1588                 if (ibuf_arr[view_id]) {
1589                         /* copy ibuf into combined pixel rect */
1590                         RE_render_result_rect_from_ibuf(rr, &re->r, ibuf_arr[view_id], view_id);
1591
1592                         if (ibuf_arr[view_id]->metadata && (re->r.stamp & R_STAMP_STRIPMETA)) {
1593                                 /* ensure render stamp info first */
1594                                 BKE_render_result_stamp_info(NULL, NULL, rr, true);
1595                                 BKE_stamp_info_from_imbuf(rr, ibuf_arr[view_id]);
1596                         }
1597
1598                         if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
1599                                 Editing *ed = re->scene->ed;
1600                                 if (ed)
1601                                         BKE_sequencer_free_imbuf(re->scene, &ed->seqbase, true);
1602                         }
1603                         IMB_freeImBuf(ibuf_arr[view_id]);
1604                 }
1605                 else {
1606                         /* render result is delivered empty in most cases, nevertheless we handle all cases */
1607                         render_result_rect_fill_zero(rr, view_id);
1608                 }
1609
1610                 BLI_rw_mutex_unlock(&re->resultmutex);
1611
1612                 /* would mark display buffers as invalid */
1613                 RE_SetActiveRenderView(re, rv->name);
1614                 re->display_update(re->duh, re->result, NULL);
1615         }
1616
1617         MEM_freeN(ibuf_arr);
1618
1619         recurs_depth--;
1620
1621         /* just in case this flag went missing at some point */
1622         re->r.scemode |= R_DOSEQ;
1623
1624         /* set overall progress of sequence rendering */
1625         if (re->r.efra != re->r.sfra)
1626                 re->progress(re->prh, (float)(cfra - re->r.sfra) / (re->r.efra - re->r.sfra));
1627         else
1628                 re->progress(re->prh, 1.0f);
1629 }
1630
1631 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1632
1633 /* main loop: doing sequence + 3d render + compositing */
1634 static void do_render_all_options(Render *re)
1635 {
1636         Object *camera;
1637         bool render_seq = false;
1638
1639         re->current_scene_update(re->suh, re->scene);
1640
1641         BKE_scene_camera_switch_update(re->scene);
1642
1643         re->i.starttime = PIL_check_seconds_timer();
1644
1645         /* ensure no images are in memory from previous animated sequences */
1646         BKE_image_all_free_anim_ibufs(re->main, re->r.cfra);
1647         BKE_sequencer_all_free_anim_ibufs(re->main, re->r.cfra);
1648
1649         if (RE_engine_render(re, 1)) {
1650                 /* in this case external render overrides all */
1651         }
1652         else if (RE_seq_render_active(re->scene, &re->r)) {
1653                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
1654                 if (!re->test_break(re->tbh)) {
1655                         do_render_seq(re);
1656                         render_seq = true;
1657                 }
1658
1659                 re->stats_draw(re->sdh, &re->i);
1660                 re->display_update(re->duh, re->result, NULL);
1661         }
1662         else {
1663                 do_render_composite(re);
1664         }
1665
1666         re->i.lastframetime = PIL_check_seconds_timer() - re->i.starttime;
1667
1668         re->stats_draw(re->sdh, &re->i);
1669
1670         /* save render result stamp if needed */
1671         if (re->result != NULL) {
1672                 camera = RE_GetCamera(re);
1673                 /* sequence rendering should have taken care of that already */
1674                 if (!(render_seq && (re->r.stamp & R_STAMP_STRIPMETA)))
1675                         BKE_render_result_stamp_info(re->scene, camera, re->result, false);
1676
1677                 /* stamp image info here */
1678                 if ((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
1679                         renderresult_stampinfo(re);
1680                         re->display_update(re->duh, re->result, NULL);
1681                 }
1682         }
1683 }
1684
1685 static bool check_valid_compositing_camera(Scene *scene, Object *camera_override)
1686 {
1687         if (scene->r.scemode & R_DOCOMP && scene->use_nodes) {
1688                 bNode *node = scene->nodetree->nodes.first;
1689
1690                 while (node) {
1691                         if (node->type == CMP_NODE_R_LAYERS && (node->flag & NODE_MUTED) == 0) {
1692                                 Scene *sce = node->id ? (Scene *)node->id : scene;
1693                                 if (sce->camera == NULL) {
1694                                         sce->camera = BKE_view_layer_camera_find(BKE_view_layer_default_render(sce));
1695                                 }
1696                                 if (sce->camera == NULL) {
1697                                         /* all render layers nodes need camera */
1698                                         return false;
1699                                 }
1700                         }
1701                         node = node->next;
1702                 }
1703
1704                 return true;
1705         }
1706         else {
1707                 return (camera_override != NULL || scene->camera != NULL);
1708         }
1709 }
1710
1711 static bool check_valid_camera_multiview(Scene *scene, Object *camera, ReportList *reports)
1712 {
1713         SceneRenderView *srv;
1714         bool active_view = false;
1715
1716         if (camera == NULL || (scene->r.scemode & R_MULTIVIEW) == 0)
1717                 return true;
1718
1719         for (srv = scene->r.views.first; srv; srv = srv->next) {
1720                 if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
1721                         active_view = true;
1722
1723                         if (scene->r.views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
1724                                 Object *view_camera;
1725                                 view_camera = BKE_camera_multiview_render(scene, camera, srv->name);
1726
1727                                 if (view_camera == camera) {
1728                                         /* if the suffix is not in the camera, means we are using the fallback camera */
1729                                         if (!BLI_str_endswith(view_camera->id.name + 2, srv->suffix)) {
1730                                                 BKE_reportf(reports, RPT_ERROR, "Camera \"%s\" is not a multi-view camera",
1731                                                             camera->id.name + 2);
1732                                                 return false;
1733                                         }
1734                                 }
1735                         }
1736                 }
1737         }
1738
1739         if (!active_view) {
1740                 BKE_reportf(reports, RPT_ERROR, "No active view found in scene \"%s\"", scene->id.name + 2);
1741                 return false;
1742         }
1743
1744         return true;
1745 }
1746
1747 static int check_valid_camera(Scene *scene, Object *camera_override, ReportList *reports)
1748 {
1749         const char *err_msg = "No camera found in scene \"%s\"";
1750
1751         if (camera_override == NULL && scene->camera == NULL)
1752                 scene->camera = BKE_view_layer_camera_find(BKE_view_layer_default_render(scene));
1753
1754         if (!check_valid_camera_multiview(scene, scene->camera, reports))
1755                 return false;
1756
1757         if (RE_seq_render_active(scene, &scene->r)) {
1758                 if (scene->ed) {
1759                         Sequence *seq = scene->ed->seqbase.first;
1760
1761                         while (seq) {
1762                                 if ((seq->type == SEQ_TYPE_SCENE) &&
1763                                     ((seq->flag & SEQ_SCENE_STRIPS) == 0) &&
1764                                     (seq->scene != NULL))
1765                                 {
1766                                         if (!seq->scene_camera) {
1767                                                 if (!seq->scene->camera &&
1768                                                     !BKE_view_layer_camera_find(BKE_view_layer_default_render(seq->scene)))
1769                                                 {
1770                                                         /* camera could be unneeded due to composite nodes */
1771                                                         Object *override = (seq->scene == scene) ? camera_override : NULL;
1772
1773                                                         if (!check_valid_compositing_camera(seq->scene, override)) {
1774                                                                 BKE_reportf(reports, RPT_ERROR, err_msg, seq->scene->id.name + 2);
1775                                                                 return false;
1776                                                         }
1777                                                 }
1778                                         }
1779                                         else if (!check_valid_camera_multiview(seq->scene, seq->scene_camera, reports))
1780                                                 return false;
1781                                 }
1782
1783                                 seq = seq->next;
1784                         }
1785                 }
1786         }
1787         else if (!check_valid_compositing_camera(scene, camera_override)) {
1788                 BKE_reportf(reports, RPT_ERROR, err_msg, scene->id.name + 2);
1789                 return false;
1790         }
1791
1792         return true;
1793 }
1794
1795 static bool node_tree_has_composite_output(bNodeTree *ntree)
1796 {
1797         bNode *node;
1798
1799         for (node = ntree->nodes.first; node; node = node->next) {
1800                 if (ELEM(node->type, CMP_NODE_COMPOSITE, CMP_NODE_OUTPUT_FILE)) {
1801                         return true;
1802                 }
1803                 else if (node->type == NODE_GROUP) {
1804                         if (node->id) {
1805                                 if (node_tree_has_composite_output((bNodeTree *)node->id)) {
1806                                         return true;
1807                                 }
1808                         }
1809                 }
1810         }
1811
1812         return false;
1813 }
1814
1815 static int check_composite_output(Scene *scene)
1816 {
1817         return node_tree_has_composite_output(scene->nodetree);
1818 }
1819
1820 bool RE_is_rendering_allowed(Scene *scene, ViewLayer *single_layer, Object *camera_override, ReportList *reports)
1821 {
1822         int scemode = check_mode_full_sample(&scene->r);
1823
1824         if (scene->r.mode & R_BORDER) {
1825                 if (scene->r.border.xmax <= scene->r.border.xmin ||
1826                     scene->r.border.ymax <= scene->r.border.ymin)
1827                 {
1828                         BKE_report(reports, RPT_ERROR, "No border area selected");
1829                         return 0;
1830                 }
1831         }
1832
1833         if (scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
1834                 char str[FILE_MAX];
1835
1836                 render_result_exr_file_path(scene, "", 0, str);
1837
1838                 if (!BLI_file_is_writable(str)) {
1839                         BKE_report(reports, RPT_ERROR, "Cannot save render buffers, check the temp default path");
1840                         return 0;
1841                 }
1842         }
1843
1844         if (scemode & R_DOCOMP) {
1845                 if (scene->use_nodes) {
1846                         if (!scene->nodetree) {
1847                                 BKE_report(reports, RPT_ERROR, "No node tree in scene");
1848                                 return 0;
1849                         }
1850
1851                         if (!check_composite_output(scene)) {
1852                                 BKE_report(reports, RPT_ERROR, "No render output node in scene");
1853                                 return 0;
1854                         }
1855
1856                         if (scemode & R_FULL_SAMPLE) {
1857                                 if (composite_needs_render(scene, 0) == 0) {
1858                                         BKE_report(reports, RPT_ERROR, "Full sample AA not supported without 3D rendering");
1859                                         return 0;
1860                                 }
1861                         }
1862                 }
1863         }
1864
1865         /* check valid camera, without camera render is OK (compo, seq) */
1866         if (!check_valid_camera(scene, camera_override, reports)) {
1867                 return 0;
1868         }
1869
1870         /* get panorama & ortho, only after camera is set */
1871         BKE_camera_object_mode(&scene->r, camera_override ? camera_override : scene->camera);
1872
1873         /* forbidden combinations */
1874         if (scene->r.mode & R_PANORAMA) {
1875                 if (scene->r.mode & R_ORTHO) {
1876                         BKE_report(reports, RPT_ERROR, "No ortho render possible for panorama");
1877                         return 0;
1878                 }
1879
1880 #ifdef WITH_FREESTYLE
1881                 if (scene->r.mode & R_EDGE_FRS) {
1882                         BKE_report(reports, RPT_ERROR, "Panoramic camera not supported in Freestyle");
1883                         return 0;
1884                 }
1885 #endif
1886         }
1887
1888         if (RE_seq_render_active(scene, &scene->r)) {
1889                 if (scene->r.mode & R_BORDER) {
1890                         BKE_report(reports, RPT_ERROR, "Border rendering is not supported by sequencer");
1891                         return false;
1892                 }
1893         }
1894
1895         /* layer flag tests */
1896         if (!render_scene_has_layers_to_render(scene, single_layer)) {
1897                 BKE_report(reports, RPT_ERROR, "All render layers are disabled");
1898                 return 0;
1899         }
1900
1901         return 1;
1902 }
1903
1904 static void validate_render_settings(Render *re)
1905 {
1906         if (RE_engine_is_external(re)) {
1907                 /* not supported yet */
1908                 re->r.scemode &= ~(R_FULL_SAMPLE);
1909         }
1910 }
1911
1912 static void update_physics_cache(Render *re, Scene *scene, ViewLayer *view_layer, int UNUSED(anim_init))
1913 {
1914         PTCacheBaker baker;
1915
1916         memset(&baker, 0, sizeof(baker));
1917         baker.bmain = re->main;
1918         baker.scene = scene;
1919         baker.view_layer = view_layer;
1920         baker.depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true);
1921         baker.bake = 0;
1922         baker.render = 1;
1923         baker.anim_init = 1;
1924         baker.quick_step = 1;
1925
1926         BKE_ptcache_bake(&baker);
1927 }
1928
1929 void RE_SetActiveRenderView(Render *re, const char *viewname)
1930 {
1931         BLI_strncpy(re->viewname, viewname, sizeof(re->viewname));
1932 }
1933
1934 const char *RE_GetActiveRenderView(Render *re)
1935 {
1936         return re->viewname;
1937 }
1938
1939 /* evaluating scene options for general Blender render */
1940 static int render_initialize_from_main(Render *re, RenderData *rd, Main *bmain, Scene *scene,
1941                                        ViewLayer *single_layer, Object *camera_override, unsigned int lay_override,
1942                                        int anim, int anim_init)
1943 {
1944         int winx, winy;
1945         rcti disprect;
1946
1947         /* r.xsch and r.ysch has the actual view window size
1948          * r.border is the clipping rect */
1949
1950         /* calculate actual render result and display size */
1951         winx = (rd->size * rd->xsch) / 100;
1952         winy = (rd->size * rd->ysch) / 100;
1953
1954         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
1955         if (scene->r.mode & R_BORDER) {
1956                 disprect.xmin = rd->border.xmin * winx;
1957                 disprect.xmax = rd->border.xmax * winx;
1958
1959                 disprect.ymin = rd->border.ymin * winy;
1960                 disprect.ymax = rd->border.ymax * winy;
1961         }
1962         else {
1963                 disprect.xmin = disprect.ymin = 0;
1964                 disprect.xmax = winx;
1965                 disprect.ymax = winy;
1966         }
1967
1968         re->main = bmain;
1969         re->scene = scene;
1970         re->camera_override = camera_override;
1971         re->lay = lay_override ? lay_override : scene->lay;
1972         re->layer_override = lay_override;
1973         re->i.localview = (re->lay & 0xFF000000) != 0;
1974         re->viewname[0] = '\0';
1975
1976         /* not too nice, but it survives anim-border render */
1977         if (anim) {
1978                 render_update_anim_renderdata(re, &scene->r, &scene->view_layers);
1979                 re->disprect = disprect;
1980                 return 1;
1981         }
1982
1983         /*
1984          * Disabled completely for now,
1985          * can be later set as render profile option
1986          * and default for background render.
1987          */
1988         if (0) {
1989                 /* make sure dynamics are up to date */
1990                 ViewLayer *view_layer = BKE_view_layer_context_active_PLACEHOLDER(scene);
1991                 update_physics_cache(re, scene, view_layer, anim_init);
1992         }
1993
1994         if (single_layer || scene->r.scemode & R_SINGLE_LAYER) {
1995                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1996                 render_result_single_layer_begin(re);
1997                 BLI_rw_mutex_unlock(&re->resultmutex);
1998         }
1999
2000         RE_InitState(re, NULL, &scene->r, &scene->view_layers, single_layer, winx, winy, &disprect);
2001         if (!re->ok)  /* if an error was printed, abort */
2002                 return 0;
2003
2004         /* initstate makes new result, have to send changed tags around */
2005         ntreeCompositTagRender(re->scene);
2006
2007         validate_render_settings(re);
2008
2009         re->display_init(re->dih, re->result);
2010         re->display_clear(re->dch, re->result);
2011
2012         return 1;
2013 }
2014
2015 void RE_SetReports(Render *re, ReportList *reports)
2016 {
2017         re->reports = reports;
2018 }
2019
2020 /* general Blender frame render call */
2021 void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, ViewLayer *single_layer, Object *camera_override,
2022                      unsigned int lay_override, int frame, const bool write_still)
2023 {
2024         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_INIT);
2025
2026         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2027         G.is_rendering = true;
2028
2029         scene->r.cfra = frame;
2030
2031         if (render_initialize_from_main(re, &scene->r, bmain, scene, single_layer,
2032                                         camera_override, lay_override, 0, 0))
2033         {
2034                 MEM_reset_peak_memory();
2035
2036                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2037
2038                 do_render_all_options(re);
2039
2040                 if (write_still && !G.is_break) {
2041                         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2042                                 /* operator checks this but in case its called from elsewhere */
2043                                 printf("Error: cant write single images with a movie format!\n");
2044                         }
2045                         else {
2046                                 char name[FILE_MAX];
2047                                 BKE_image_path_from_imformat(
2048                                         name, scene->r.pic, BKE_main_blendfile_path(bmain), scene->r.cfra,
2049                                         &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, false, NULL);
2050
2051                                 /* reports only used for Movie */
2052                                 do_write_image_or_movie(re, bmain, scene, NULL, 0, name);
2053                         }
2054                 }
2055
2056                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2057                 if (write_still) {
2058                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_WRITE);
2059                 }
2060         }
2061
2062         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2063
2064         /* Destroy the opengl context in the correct thread. */
2065         RE_gl_context_destroy(re);
2066
2067         /* UGLY WARNING */
2068         G.is_rendering = false;
2069 }
2070
2071 #ifdef WITH_FREESTYLE
2072 void RE_RenderFreestyleStrokes(Render *re, Main *bmain, Scene *scene, int render)
2073 {
2074         re->result_ok= 0;
2075         if (render_initialize_from_main(re, &scene->r, bmain, scene, NULL, NULL, scene->lay, 0, 0)) {
2076                 if (render)
2077                         do_render_3d(re);
2078         }
2079         re->result_ok = 1;
2080 }
2081
2082 void RE_RenderFreestyleExternal(Render *re)
2083 {
2084         if (!re->test_break(re->tbh)) {
2085                 RenderView *rv;
2086
2087                 init_freestyle(re);
2088
2089                 for (rv = re->result->views.first; rv; rv = rv->next) {
2090                         RE_SetActiveRenderView(re, rv->name);
2091
2092                         /* scene needs to be set to get camera */
2093                         Object *camera = RE_GetCamera(re);
2094
2095                         /* if no camera, viewmat should have been set! */
2096                         if (camera) {
2097                                 /* called before but need to call again in case of lens animation from the
2098                                  * above call to BKE_scene_graph_update_for_newframe, fixes bug. [#22702].
2099                                  * following calls don't depend on 'RE_SetCamera' */
2100                                 float mat[4][4];
2101
2102                                 RE_SetCamera(re, camera);
2103                                 RE_GetCameraModelMatrix(re, camera, mat);
2104                                 invert_m4(mat);
2105                                 RE_SetView(re, mat);
2106
2107                                 /* force correct matrix for scaled cameras */
2108                                 DEG_id_tag_update_ex(re->main, &camera->id, OB_RECALC_OB);
2109                         }
2110
2111                         printf("add freestyle\n");
2112
2113                         add_freestyle(re, 1);
2114                 }
2115         }
2116 }
2117 #endif
2118
2119 bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scene, const bool stamp, char *name)
2120 {
2121         bool ok = true;
2122         RenderData *rd = &scene->r;
2123
2124         if (!rr)
2125                 return false;
2126
2127         bool is_mono = BLI_listbase_count_at_most(&rr->views, 2) < 2;
2128         bool is_exr_rr = ELEM(rd->im_format.imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER) &&
2129                          RE_HasFloatPixels(rr);
2130
2131         if (rd->im_format.views_format == R_IMF_VIEWS_MULTIVIEW && is_exr_rr)
2132         {
2133                 ok = RE_WriteRenderResult(reports, rr, name, &rd->im_format, NULL, -1);
2134                 render_print_save_message(reports, name, ok, errno);
2135         }
2136
2137         /* mono, legacy code */
2138         else if (is_mono || (rd->im_format.views_format == R_IMF_VIEWS_INDIVIDUAL))
2139         {
2140                 RenderView *rv;
2141                 int view_id;
2142                 char filepath[FILE_MAX];
2143
2144                 BLI_strncpy(filepath, name, sizeof(filepath));
2145
2146                 for (view_id = 0, rv = rr->views.first; rv; rv = rv->next, view_id++) {
2147                         if (!is_mono) {
2148                                 BKE_scene_multiview_view_filepath_get(&scene->r, filepath, rv->name, name);
2149                         }
2150
2151                         if (is_exr_rr) {
2152                                 ok = RE_WriteRenderResult(reports, rr, name, &rd->im_format, rv->name, -1);
2153                                 render_print_save_message(reports, name, ok, errno);
2154
2155                                 /* optional preview images for exr */
2156                                 if (ok && (rd->im_format.flag & R_IMF_FLAG_PREVIEW_JPG)) {
2157                                         ImageFormatData imf = rd->im_format;
2158                                         imf.imtype = R_IMF_IMTYPE_JPEG90;
2159
2160                                         if (BLI_path_extension_check(name, ".exr"))
2161                                                 name[strlen(name) - 4] = 0;
2162                                         BKE_image_path_ensure_ext_from_imformat(name, &imf);
2163
2164                                         ImBuf *ibuf = render_result_rect_to_ibuf(rr, rd, view_id);
2165                                         ibuf->planes = 24;
2166
2167                                         ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf, name, &imf, stamp);
2168
2169                                         IMB_freeImBuf(ibuf);
2170                                 }
2171                         }
2172                         else {
2173                                 ImBuf *ibuf = render_result_rect_to_ibuf(rr, rd, view_id);
2174
2175                                 IMB_colormanagement_imbuf_for_write(ibuf, true, false, &scene->view_settings,
2176                                                                     &scene->display_settings, &rd->im_format);
2177
2178                                 ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf, name, &rd->im_format, stamp);
2179
2180                                 /* imbuf knows which rects are not part of ibuf */
2181                                 IMB_freeImBuf(ibuf);
2182                         }
2183                 }
2184         }
2185         else { /* R_IMF_VIEWS_STEREO_3D */
2186                 BLI_assert(scene->r.im_format.views_format == R_IMF_VIEWS_STEREO_3D);
2187
2188                 if (rd->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
2189                         printf("Stereo 3D not supported for MultiLayer image: %s\n", name);
2190                 }
2191                 else {
2192                         ImBuf *ibuf_arr[3] = {NULL};
2193                         const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
2194                         int i;
2195
2196                         for (i = 0; i < 2; i++) {
2197                                 int view_id = BLI_findstringindex(&rr->views, names[i], offsetof(RenderView, name));
2198                                 ibuf_arr[i] = render_result_rect_to_ibuf(rr, rd, view_id);
2199                                 IMB_colormanagement_imbuf_for_write(ibuf_arr[i], true, false, &scene->view_settings,
2200                                                                     &scene->display_settings, &scene->r.im_format);
2201                                 IMB_prepare_write_ImBuf(IMB_isfloat(ibuf_arr[i]), ibuf_arr[i]);
2202                         }
2203
2204                         ibuf_arr[2] = IMB_stereo3d_ImBuf(&scene->r.im_format, ibuf_arr[0], ibuf_arr[1]);
2205
2206                         ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf_arr[2], name, &rd->im_format, stamp);
2207
2208                         /* optional preview images for exr */
2209                         if (ok && is_exr_rr &&
2210                             (rd->im_format.flag & R_IMF_FLAG_PREVIEW_JPG))
2211                         {
2212                                 ImageFormatData imf = rd->im_format;
2213                                 imf.imtype = R_IMF_IMTYPE_JPEG90;
2214
2215                                 if (BLI_path_extension_check(name, ".exr"))
2216                                         name[strlen(name) - 4] = 0;
2217
2218                                 BKE_image_path_ensure_ext_from_imformat(name, &imf);
2219                                 ibuf_arr[2]->planes = 24;
2220
2221                                 ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf_arr[2], name, &rd->im_format, stamp);
2222                         }
2223
2224                         /* imbuf knows which rects are not part of ibuf */
2225                         for (i = 0; i < 3; i++) {
2226                                 IMB_freeImBuf(ibuf_arr[i]);
2227                         }
2228                 }
2229         }
2230
2231         return ok;
2232 }
2233
2234 bool RE_WriteRenderViewsMovie(
2235         ReportList *reports, RenderResult *rr, Scene *scene, RenderData *rd, bMovieHandle *mh,
2236         void **movie_ctx_arr, const int totvideos, bool preview)
2237 {
2238         bool is_mono;
2239         bool ok = true;
2240
2241         if (!rr)
2242                 return false;
2243
2244         is_mono = BLI_listbase_count_at_most(&rr->views, 2) < 2;
2245
2246         if (is_mono || (scene->r.im_format.views_format == R_IMF_VIEWS_INDIVIDUAL)) {
2247                 int view_id;
2248                 for (view_id = 0; view_id < totvideos; view_id++) {
2249                         const char *suffix = BKE_scene_multiview_view_id_suffix_get(&scene->r, view_id);
2250                         ImBuf *ibuf = render_result_rect_to_ibuf(rr, &scene->r, view_id);
2251
2252                         IMB_colormanagement_imbuf_for_write(ibuf, true, false, &scene->view_settings,
2253                                                             &scene->display_settings, &scene->r.im_format);
2254
2255                         ok &= mh->append_movie(movie_ctx_arr[view_id], rd, preview ? scene->r.psfra : scene->r.sfra, scene->r.cfra,
2256                                                (int *) ibuf->rect, ibuf->x, ibuf->y, suffix, reports);
2257
2258                         /* imbuf knows which rects are not part of ibuf */
2259                         IMB_freeImBuf(ibuf);
2260                 }
2261                 printf("Append frame %d\n", scene->r.cfra);
2262         }
2263         else { /* R_IMF_VIEWS_STEREO_3D */
2264                 const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
2265                 ImBuf *ibuf_arr[3] = {NULL};
2266                 int i;
2267
2268                 BLI_assert((totvideos == 1) && (scene->r.im_format.views_format == R_IMF_VIEWS_STEREO_3D));
2269
2270                 for (i = 0; i < 2; i++) {
2271                         int view_id = BLI_findstringindex(&rr->views, names[i], offsetof(RenderView, name));
2272                         ibuf_arr[i] = render_result_rect_to_ibuf(rr, &scene->r, view_id);
2273
2274                         IMB_colormanagement_imbuf_for_write(ibuf_arr[i], true, false, &scene->view_settings,
2275                                                             &scene->display_settings, &scene->r.im_format);
2276                 }
2277
2278                 ibuf_arr[2] = IMB_stereo3d_ImBuf(&scene->r.im_format, ibuf_arr[0], ibuf_arr[1]);
2279
2280                 ok = mh->append_movie(movie_ctx_arr[0], rd, preview ? scene->r.psfra : scene->r.sfra, scene->r.cfra, (int *) ibuf_arr[2]->rect,
2281                                       ibuf_arr[2]->x, ibuf_arr[2]->y, "", reports);
2282
2283                 for (i = 0; i < 3; i++) {
2284                         /* imbuf knows which rects are not part of ibuf */
2285                         IMB_freeImBuf(ibuf_arr[i]);
2286                 }
2287         }
2288
2289         return ok;
2290 }
2291
2292 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const int totvideos, const char *name_override)
2293 {
2294         char name[FILE_MAX];
2295         RenderResult rres;
2296         double render_time;
2297         bool ok = true;
2298
2299         RE_AcquireResultImageViews(re, &rres);
2300
2301         /* write movie or image */
2302         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2303                 RE_WriteRenderViewsMovie(re->reports, &rres, scene, &re->r, mh, re->movie_ctx_arr, totvideos, false);
2304         }
2305         else {
2306                 if (name_override)
2307                         BLI_strncpy(name, name_override, sizeof(name));
2308                 else
2309                         BKE_image_path_from_imformat(
2310                                 name, scene->r.pic, BKE_main_blendfile_path(bmain), scene->r.cfra,
2311                                 &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, true, NULL);
2312
2313                 /* write images as individual images or stereo */
2314                 ok = RE_WriteRenderViewsImage(re->reports, &rres, scene, true, name);
2315         }
2316
2317         RE_ReleaseResultImageViews(re, &rres);
2318
2319         render_time = re->i.lastframetime;
2320         re->i.lastframetime = PIL_check_seconds_timer() - re->i.starttime;
2321
2322         BLI_timecode_string_from_time_simple(name, sizeof(name), re->i.lastframetime);
2323         printf(" Time: %s", name);
2324
2325         /* Flush stdout to be sure python callbacks are printing stuff after blender. */
2326         fflush(stdout);
2327
2328         BLI_callback_exec(re->main, NULL, BLI_CB_EVT_RENDER_STATS);
2329
2330         BLI_timecode_string_from_time_simple(name, sizeof(name), re->i.lastframetime - render_time);
2331         printf(" (Saving: %s)\n", name);
2332
2333         fputc('\n', stdout);
2334         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2335
2336         return ok;
2337 }
2338
2339 static void get_videos_dimensions(
2340         Render *re, RenderData *rd,
2341         size_t *r_width, size_t *r_height)
2342 {
2343         size_t width, height;
2344         if (re->r.mode & R_BORDER) {
2345                 if ((re->r.mode & R_CROP) == 0) {
2346                         width = re->winx;
2347                         height = re->winy;
2348                 }
2349                 else {
2350                         width = re->rectx;
2351                         height = re->recty;
2352                 }
2353         }
2354         else {
2355                 width = re->rectx;
2356                 height = re->recty;
2357         }
2358
2359         BKE_scene_multiview_videos_dimensions_get(rd, width, height, r_width, r_height);
2360 }
2361
2362 static void re_movie_free_all(Render *re, bMovieHandle *mh, int totvideos)
2363 {
2364         int i;
2365
2366         for (i = 0; i < totvideos; i++) {
2367                 mh->end_movie(re->movie_ctx_arr[i]);
2368                 mh->context_free(re->movie_ctx_arr[i]);
2369         }
2370
2371         MEM_SAFE_FREE(re->movie_ctx_arr);
2372 }
2373
2374 /* saves images to disk */
2375 void RE_BlenderAnim(Render *re, Main *bmain, Scene *scene, Object *camera_override,
2376                     unsigned int lay_override, int sfra, int efra, int tfra)
2377 {
2378         RenderData rd = scene->r;
2379         bMovieHandle *mh = NULL;
2380         int cfrao = scene->r.cfra;
2381         int nfra, totrendered = 0, totskipped = 0;
2382         const int totvideos = BKE_scene_multiview_num_videos_get(&rd);
2383         const bool is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
2384         const bool is_multiview_name = ((scene->r.scemode & R_MULTIVIEW) != 0 &&
2385                                         (scene->r.im_format.views_format == R_IMF_VIEWS_INDIVIDUAL));
2386
2387         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_INIT);
2388
2389         /* do not fully call for each frame, it initializes & pops output window */
2390         if (!render_initialize_from_main(re, &rd, bmain, scene, NULL, camera_override, lay_override, 0, 1))
2391                 return;
2392
2393         if (is_movie) {
2394                 size_t width, height;
2395                 int i;
2396                 bool is_error = false;
2397
2398                 get_videos_dimensions(re, &rd, &width, &height);
2399
2400                 mh = BKE_movie_handle_get(scene->r.im_format.imtype);
2401                 if (mh == NULL) {
2402                         BKE_report(re->reports, RPT_ERROR, "Movie format unsupported");
2403                         return;
2404                 }
2405
2406                 re->movie_ctx_arr = MEM_mallocN(sizeof(void *) * totvideos, "Movies' Context");
2407
2408                 for (i = 0; i < totvideos; i++) {
2409                         const char *suffix = BKE_scene_multiview_view_id_suffix_get(&re->r, i);
2410
2411                         re->movie_ctx_arr[i] = mh->context_create();
2412
2413                         if (!mh->start_movie(re->movie_ctx_arr[i], scene, &re->r, width, height, re->reports, false, suffix)) {
2414                                 is_error = true;
2415                                 break;
2416                         }
2417                 }
2418
2419                 if (is_error) {
2420                         /* report is handled above */
2421                         re_movie_free_all(re, mh, i + 1);
2422                         return;
2423                 }
2424         }
2425
2426         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2427         /* is also set by caller renderwin.c */
2428         G.is_rendering = true;
2429
2430         re->flag |= R_ANIMATION;
2431
2432         {
2433                 for (nfra = sfra, scene->r.cfra = sfra; scene->r.cfra <= efra; scene->r.cfra++) {
2434                         char name[FILE_MAX];
2435
2436                         /* Special case for 'mh->get_next_frame'
2437                          * this overrides regular frame stepping logic */
2438                         if (mh && mh->get_next_frame) {
2439                                 while (G.is_break == false) {
2440                                         int nfra_test = mh->get_next_frame(re->movie_ctx_arr[0], &re->r, re->reports);
2441                                         if (nfra_test >= 0 && nfra_test >= sfra && nfra_test <= efra) {
2442                                                 nfra = nfra_test;
2443                                                 break;
2444                                         }
2445                                         else {
2446                                                 if (re->test_break(re->tbh)) {
2447                                                         G.is_break = true;
2448                                                 }
2449                                         }
2450                                 }
2451                         }
2452
2453                         /* Here is a feedback loop exists -- render initialization requires updated
2454                          * render layers settings which could be animated, but scene evaluation for
2455                          * the frame happens later because it depends on what layers are visible to
2456                          * render engine.
2457                          *
2458                          * The idea here is to only evaluate animation data associated with the scene,
2459                          * which will make sure render layer settings are up-to-date, initialize the
2460                          * render database itself and then perform full scene update with only needed
2461                          * layers.
2462                          *                                                              -sergey-
2463                          */
2464                         {
2465                                 float ctime = BKE_scene_frame_get(scene);
2466                                 AnimData *adt = BKE_animdata_from_id(&scene->id);
2467                                 /* TODO(sergey): Currently depsgraph is only used to check whether it is an active
2468                                  * edit window or not to deal with unkeyed changes. We don't have depsgraph here yet,
2469                                  * but we also dont' deal with unkeyed changes. But still nice to get proper depsgraph
2470                                  * within tjhe render pipeline, somehow.
2471                                  */
2472                                 BKE_animsys_evaluate_animdata(NULL, scene, &scene->id, adt, ctime, ADT_RECALC_ALL);
2473                         }
2474
2475                         /* only border now, todo: camera lens. (ton) */
2476                         render_initialize_from_main(re, &rd, bmain, scene,
2477                                                     NULL, camera_override, lay_override, 1, 0);
2478
2479                         if (nfra != scene->r.cfra) {
2480                                 /* Skip this frame, but could update for physics and particles system. */
2481                                 continue;
2482                         }
2483                         else
2484                                 nfra += tfra;
2485
2486                         /* Touch/NoOverwrite options are only valid for image's */
2487                         if (is_movie == false) {
2488                                 if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2489                                         BKE_image_path_from_imformat(
2490                                                 name, scene->r.pic, BKE_main_blendfile_path(bmain), scene->r.cfra,
2491                                                 &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, true, NULL);
2492
2493                                 if (scene->r.mode & R_NO_OVERWRITE) {
2494                                         if (!is_multiview_name) {
2495                                                 if (BLI_exists(name)) {
2496                                                         printf("skipping existing frame \"%s\"\n", name);
2497                                                         totskipped++;
2498                                                         continue;
2499                                                 }
2500                                         }
2501                                         else {
2502                                                 SceneRenderView *srv;
2503                                                 bool is_skip = false;
2504                                                 char filepath[FILE_MAX];
2505
2506                                                 for (srv = scene->r.views.first; srv; srv = srv->next) {
2507                                                         if (!BKE_scene_multiview_is_render_view_active(&scene->r, srv))
2508                                                                 continue;
2509
2510                                                         BKE_scene_multiview_filepath_get(srv, name, filepath);
2511
2512                                                         if (BLI_exists(filepath)) {
2513                                                                 is_skip = true;
2514                                                                 printf("skipping existing frame \"%s\" for view \"%s\"\n", filepath, srv->name);
2515                                                         }
2516                                                 }
2517
2518                                                 if (is_skip) {
2519                                                         totskipped++;
2520                                                         continue;
2521                                                 }
2522                                         }
2523                                 }
2524
2525                                 if (scene->r.mode & R_TOUCH) {
2526                                         if (!is_multiview_name) {
2527                                                 if (!BLI_exists(name)) {
2528                                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2529                                                         BLI_file_touch(name);
2530                                                 }
2531                                         }
2532                                         else {
2533                                                 SceneRenderView *srv;
2534                                                 char filepath[FILE_MAX];
2535
2536                                                 for (srv = scene->r.views.first; srv; srv = srv->next) {
2537                                                         if (!BKE_scene_multiview_is_render_view_active(&scene->r, srv))
2538                                                                 continue;
2539
2540                                                         BKE_scene_multiview_filepath_get(srv, name, filepath);
2541
2542                                                         if (!BLI_exists(filepath)) {
2543                                                                 BLI_make_existing_file(filepath); /* makes the dir if its not there */
2544                                                                 BLI_file_touch(filepath);
2545                                                         }
2546                                                 }
2547                                         }
2548                                 }
2549                         }
2550
2551                         re->r.cfra = scene->r.cfra;     /* weak.... */
2552
2553                         /* run callbacs before rendering, before the scene is updated */
2554                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2555
2556
2557                         do_render_all_options(re);
2558                         totrendered++;
2559
2560                         if (re->test_break(re->tbh) == 0) {
2561                                 if (!G.is_break)
2562                                         if (!do_write_image_or_movie(re, bmain, scene, mh, totvideos, NULL))
2563                                                 G.is_break = true;
2564                         }
2565                         else
2566                                 G.is_break = true;
2567
2568                         if (G.is_break == true) {
2569                                 /* remove touched file */
2570                                 if (is_movie == false) {
2571                                         if ((scene->r.mode & R_TOUCH)) {
2572                                                 if (!is_multiview_name) {
2573                                                         if ((BLI_file_size(name) == 0)) {
2574                                                                 /* BLI_exists(name) is implicit */
2575                                                                 BLI_delete(name, false, false);
2576                                                         }
2577                                                 }
2578                                                 else {
2579                                                         SceneRenderView *srv;
2580                                                         char filepath[FILE_MAX];
2581
2582                                                         for (srv = scene->r.views.first; srv; srv = srv->next) {
2583                                                                 if (!BKE_scene_multiview_is_render_view_active(&scene->r, srv))
2584                                                                         continue;
2585
2586                                                                 BKE_scene_multiview_filepath_get(srv, name, filepath);
2587
2588                                                                 if ((BLI_file_size(filepath) == 0)) {
2589                                                                         /* BLI_exists(filepath) is implicit */
2590                                                                         BLI_delete(filepath, false, false);
2591                                                                 }
2592                                                         }
2593                                                 }
2594                                         }
2595                                 }
2596
2597                                 break;
2598                         }
2599
2600                         if (G.is_break == false) {
2601                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2602                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_WRITE);
2603                         }
2604                 }
2605         }
2606
2607         /* end movie */
2608         if (is_movie) {
2609                 re_movie_free_all(re, mh, totvideos);
2610         }
2611
2612         if (totskipped && totrendered == 0)
2613                 BKE_report(re->reports, RPT_INFO, "No frames rendered, skipped to not overwrite");
2614
2615         scene->r.cfra = cfrao;
2616
2617         re->flag &= ~R_ANIMATION;
2618
2619         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2620         BKE_sound_reset_scene_specs(scene);
2621
2622         /* Destroy the opengl context in the correct thread. */
2623         RE_gl_context_destroy(re);
2624
2625         /* UGLY WARNING */
2626         G.is_rendering = false;
2627 }
2628
2629 void RE_PreviewRender(Render *re, Main *bmain, Scene *sce)
2630 {
2631         Object *camera;
2632         int winx, winy;
2633
2634         winx = (sce->r.size * sce->r.xsch) / 100;
2635         winy = (sce->r.size * sce->r.ysch) / 100;
2636
2637         RE_InitState(re, NULL, &sce->r, &sce->view_layers, NULL, winx, winy, NULL);
2638
2639         re->main = bmain;
2640         re->scene = sce;
2641         re->lay = sce->lay;
2642
2643         camera = RE_GetCamera(re);
2644         RE_SetCamera(re, camera);
2645
2646         do_render_3d(re);
2647
2648         /* Destroy the opengl context in the correct thread. */
2649         RE_gl_context_destroy(re);
2650 }
2651
2652 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2653
2654 /* only the temp file! */
2655 bool RE_ReadRenderResult(Scene *scene, Scene *scenode)
2656 {
2657         Render *re;
2658         int winx, winy;
2659         bool success;
2660         rcti disprect;
2661
2662         /* calculate actual render result and display size */
2663         winx = (scene->r.size * scene->r.xsch) / 100;
2664         winy = (scene->r.size * scene->r.ysch) / 100;
2665
2666         /* only in movie case we render smaller part */
2667         if (scene->r.mode & R_BORDER) {
2668                 disprect.xmin = scene->r.border.xmin * winx;
2669                 disprect.xmax = scene->r.border.xmax * winx;
2670
2671                 disprect.ymin = scene->r.border.ymin * winy;
2672                 disprect.ymax = scene->r.border.ymax * winy;
2673         }
2674         else {
2675                 disprect.xmin = disprect.ymin = 0;
2676                 disprect.xmax = winx;
2677                 disprect.ymax = winy;
2678         }
2679
2680         if (scenode)
2681                 scene = scenode;
2682
2683         /* get render: it can be called from UI with draw callbacks */
2684         re = RE_GetSceneRender(scene);
2685         if (re == NULL)
2686                 re = RE_NewSceneRender(scene);
2687         RE_InitState(re, NULL, &scene->r, &scene->view_layers, NULL, winx, winy, &disprect);
2688         re->scene = scene;
2689
2690         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2691         success = render_result_exr_file_cache_read(re);
2692         BLI_rw_mutex_unlock(&re->resultmutex);
2693
2694         render_result_uncrop(re);
2695
2696         return success;
2697 }
2698
2699 void RE_init_threadcount(Render *re)
2700 {
2701         re->r.threads = BKE_render_num_threads(&re->r);
2702 }
2703
2704 /* loads in image into a result, size must match
2705  * x/y offsets are only used on a partial copy when dimensions don't match */
2706 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, const char *filename, int x, int y)
2707 {
2708         /* OCIO_TODO: assume layer was saved in defaule color space */
2709         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect, NULL);
2710         RenderPass *rpass = NULL;
2711
2712         /* multiview: since the API takes no 'view', we use the first combined pass found */
2713         for (rpass = layer->passes.first; rpass; rpass = rpass->next)
2714                 if (STREQ(rpass->name, RE_PASSNAME_COMBINED))
2715                         break;
2716
2717         if (rpass == NULL)
2718                 BKE_reportf(reports, RPT_ERROR, "%s: no Combined pass found in the render layer '%s'", __func__, filename);
2719
2720         if (ibuf && (ibuf->rect || ibuf->rect_float)) {
2721                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
2722                         if (ibuf->rect_float == NULL)
2723                                 IMB_float_from_rect(ibuf);
2724
2725                         memcpy(rpass->rect, ibuf->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2726                 }
2727                 else {
2728                         if ((ibuf->x - x >= layer->rectx) && (ibuf->y - y >= layer->recty)) {
2729                                 ImBuf *ibuf_clip;
2730
2731                                 if (ibuf->rect_float == NULL)
2732                                         IMB_float_from_rect(ibuf);
2733
2734                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat);
2735                                 if (ibuf_clip) {
2736                                         IMB_rectcpy(ibuf_clip, ibuf, 0, 0, x, y, layer->rectx, layer->recty);
2737
2738                                         memcpy(rpass->rect, ibuf_clip->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2739                                         IMB_freeImBuf(ibuf_clip);
2740                                 }
2741                                 else {
2742                                         BKE_reportf(reports, RPT_ERROR, "%s: failed to allocate clip buffer '%s'", __func__, filename);
2743                                 }
2744                         }
2745                         else {
2746                                 BKE_reportf(reports, RPT_ERROR, "%s: incorrect dimensions for partial copy '%s'", __func__, filename);
2747                         }
2748                 }
2749
2750                 IMB_freeImBuf(ibuf);
2751         }
2752         else {
2753                 BKE_reportf(reports, RPT_ERROR, "%s: failed to load '%s'", __func__, filename);
2754         }
2755 }
2756
2757 void RE_result_load_from_file(RenderResult *result, ReportList *reports, const char *filename)
2758 {
2759         if (!render_result_exr_file_read_path(result, NULL, filename)) {
2760                 BKE_reportf(reports, RPT_ERROR, "%s: failed to load '%s'", __func__, filename);
2761                 return;
2762         }
2763 }
2764
2765 /* Used in the interface to decide whether to show layers or passes. */
2766 bool RE_layers_have_name(struct RenderResult *rr)
2767 {
2768         switch (BLI_listbase_count_at_most(&rr->layers, 2)) {
2769                 case 0:
2770                         return false;
2771                 case 1:
2772                         return (((RenderLayer *)rr->layers.first)->name[0] != '\0');
2773                 default:
2774                         return true;
2775         }
2776         return false;
2777 }
2778
2779 bool RE_passes_have_name(struct RenderLayer *rl)
2780 {
2781         for (RenderPass *rp = rl->passes.first; rp; rp = rp->next) {
2782                 if (!STREQ(rp->name, "Combined")) {
2783                         return true;
2784                 }
2785         }
2786
2787         return false;
2788 }
2789
2790 RenderPass *RE_pass_find_by_name(volatile RenderLayer *rl, const char *name, const char *viewname)
2791 {
2792         RenderPass *rp = NULL;
2793
2794         for (rp = rl->passes.last; rp; rp = rp->prev) {
2795                 if (STREQ(rp->name, name)) {
2796                         if (viewname == NULL || viewname[0] == '\0')
2797                                 break;
2798                         else if (STREQ(rp->view, viewname))
2799                                 break;
2800                 }
2801         }
2802         return rp;
2803 }
2804
2805 /* Only provided for API compatibility, don't use this in new code! */
2806 RenderPass *RE_pass_find_by_type(volatile RenderLayer *rl, int passtype, const char *viewname)
2807 {
2808 #define CHECK_PASS(NAME) \
2809         if (passtype == SCE_PASS_ ## NAME) \
2810                 return RE_pass_find_by_name(rl, RE_PASSNAME_ ## NAME, viewname);
2811
2812         CHECK_PASS(COMBINED);
2813         CHECK_PASS(Z);
2814         CHECK_PASS(VECTOR);
2815         CHECK_PASS(NORMAL);
2816         CHECK_PASS(UV);
2817         CHECK_PASS(RGBA);
2818         CHECK_PASS(EMIT);
2819         CHECK_PASS(DIFFUSE);
2820         CHECK_PASS(SPEC);
2821         CHECK_PASS(SHADOW);
2822         CHECK_PASS(AO);
2823         CHECK_PASS(ENVIRONMENT);
2824         CHECK_PASS(INDIRECT);
2825         CHECK_PASS(REFLECT);
2826         CHECK_PASS(REFRACT);
2827         CHECK_PASS(INDEXOB);
2828         CHECK_PASS(INDEXMA);
2829         CHECK_PASS(MIST);
2830         CHECK_PASS(RAYHITS);
2831         CHECK_PASS(DIFFUSE_DIRECT);
2832         CHECK_PASS(DIFFUSE_INDIRECT);
2833         CHECK_PASS(DIFFUSE_COLOR);
2834         CHECK_PASS(GLOSSY_DIRECT);
2835         CHECK_PASS(GLOSSY_INDIRECT);
2836         CHECK_PASS(GLOSSY_COLOR);
2837         CHECK_PASS(TRANSM_DIRECT);
2838         CHECK_PASS(TRANSM_INDIRECT);
2839         CHECK_PASS(TRANSM_COLOR);
2840         CHECK_PASS(SUBSURFACE_DIRECT);
2841         CHECK_PASS(SUBSURFACE_INDIRECT);
2842         CHECK_PASS(SUBSURFACE_COLOR);
2843
2844 #undef CHECK_PASS
2845
2846         return NULL;
2847 }
2848
2849 /* create a renderlayer and renderpass for grease pencil layer */
2850 RenderPass *RE_create_gp_pass(RenderResult *rr, const char *layername, const char *viewname)
2851 {
2852         RenderLayer *rl = BLI_findstring(&rr->layers, layername, offsetof(RenderLayer, name));
2853         /* only create render layer if not exist */
2854         if (!rl) {
2855                 rl = MEM_callocN(sizeof(RenderLayer), layername);
2856                 BLI_addtail(&rr->layers, rl);
2857                 BLI_strncpy(rl->name, layername, sizeof(rl->name));
2858                 rl->layflag = SCE_LAY_SOLID;
2859                 rl->passflag = SCE_PASS_COMBINED;
2860                 rl->rectx = rr->rectx;
2861                 rl->recty = rr->recty;
2862         }
2863
2864         /* clear previous pass if exist or the new image will be over previous one*/
2865         RenderPass *rp = RE_pass_find_by_name(rl, RE_PASSNAME_COMBINED, viewname);
2866         if (rp) {
2867                 if (rp->rect) {
2868                         MEM_freeN(rp->rect);
2869                 }
2870                 BLI_freelinkN(&rl->passes, rp);
2871         }
2872         /* create a totally new pass */
2873         return gp_add_pass(rr, rl, 4, RE_PASSNAME_COMBINED, viewname);
2874 }