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