Merged changes in the trunk up to revision 52118.
[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
38 #include "DNA_group_types.h"
39 #include "DNA_image_types.h"
40 #include "DNA_node_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_sequence_types.h"
44 #include "DNA_userdef_types.h"
45
46 #include "MEM_guardedalloc.h"
47
48 #include "BKE_animsys.h"  /* <------ should this be here?, needed for sequencer update */
49 #include "BKE_camera.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_library.h"
53 #include "BKE_main.h"
54 #include "BKE_node.h"
55 #include "BKE_pointcache.h"
56 #include "BKE_report.h"
57 #include "BKE_scene.h"
58 #include "BKE_sequencer.h"
59 #include "BKE_writeavi.h"  /* <------ should be replaced once with generic movie module */
60
61 #include "BLI_math.h"
62 #include "BLI_rect.h"
63 #include "BLI_listbase.h"
64 #include "BLI_string.h"
65 #include "BLI_path_util.h"
66 #include "BLI_fileops.h"
67 #include "BLI_rand.h"
68 #include "BLI_callbacks.h"
69
70 #include "PIL_time.h"
71 #include "IMB_colormanagement.h"
72 #include "IMB_imbuf.h"
73 #include "IMB_imbuf_types.h"
74
75 #include "RE_engine.h"
76 #include "RE_pipeline.h"
77
78 #include "FRS_freestyle.h"
79
80 /* internal */
81 #include "render_result.h"
82 #include "render_types.h"
83 #include "renderpipeline.h"
84 #include "renderdatabase.h"
85 #include "rendercore.h"
86 #include "initrender.h"
87 #include "shadbuf.h"
88 #include "pixelblending.h"
89 #include "zbuf.h"
90
91 /* render flow
92  *
93  * 1) Initialize state
94  * - state data, tables
95  * - movie/image file init
96  * - everything that doesn't change during animation
97  *
98  * 2) Initialize data
99  * - camera, world, matrices
100  * - make render verts, faces, halos, strands
101  * - everything can change per frame/field
102  *
103  * 3) Render Processor
104  * - multiple layers
105  * - tiles, rect, baking
106  * - layers/tiles optionally to disk or directly in Render Result
107  *
108  * 4) Composite Render Result
109  * - also read external files etc
110  *
111  * 5) Image Files
112  * - save file or append in movie
113  *
114  */
115
116
117 /* ********* globals ******** */
118
119 /* here we store all renders */
120 static struct {
121         ListBase renderlist;
122
123         /* commandline thread override */
124         int threads;
125 } RenderGlobal = {{NULL, NULL}, -1}; 
126
127 /* hardcopy of current render, used while rendering for speed */
128 Render R;
129
130 /* ********* alloc and free ******** */
131
132 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override);
133
134 static volatile int g_break = 0;
135 static int thread_break(void *UNUSED(arg))
136 {
137         return g_break;
138 }
139
140 /* default callbacks, set in each new render */
141 static void result_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr)) {}
142 static void result_rcti_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect)) {}
143 static void stats_nothing(void *UNUSED(arg), RenderStats *UNUSED(rs)) {}
144 static void float_nothing(void *UNUSED(arg), float UNUSED(val)) {}
145 static int default_break(void *UNUSED(arg)) { return G.is_break == TRUE; }
146
147 static void stats_background(void *UNUSED(arg), RenderStats *rs)
148 {
149         uintptr_t mem_in_use, mmap_in_use, peak_memory;
150         float megs_used_memory, mmap_used_memory, megs_peak_memory;
151
152         mem_in_use = MEM_get_memory_in_use();
153         mmap_in_use = MEM_get_mapped_memory_in_use();
154         peak_memory = MEM_get_peak_memory();
155
156         megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
157         mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
158         megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
159
160         fprintf(stdout, "Fra:%d Mem:%.2fM (%.2fM, peak %.2fM) ", rs->cfra,
161                 megs_used_memory, mmap_used_memory, megs_peak_memory);
162
163         if (rs->curfield)
164                 fprintf(stdout, "Field %d ", rs->curfield);
165         if (rs->curblur)
166                 fprintf(stdout, "Blur %d ", rs->curblur);
167
168         if (rs->infostr) {
169                 fprintf(stdout, "| %s", rs->infostr);
170         }
171         else {
172                 if (rs->tothalo)
173                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", rs->scene_name, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
174                 else
175                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d La:%d", rs->scene_name, rs->totvert, rs->totface, rs->totlamp);
176         }
177
178         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
179
180         fputc('\n', stdout);
181         fflush(stdout);
182 }
183
184 void RE_FreeRenderResult(RenderResult *res)
185 {
186         render_result_free(res);
187 }
188
189 float *RE_RenderLayerGetPass(RenderLayer *rl, int passtype)
190 {
191         RenderPass *rpass;
192         
193         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
194                 if (rpass->passtype == passtype)
195                         return rpass->rect;
196         return NULL;
197 }
198
199 RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
200 {
201         if (rr == NULL) {
202                 return NULL;
203         }
204         else {
205                 return BLI_findstring(&rr->layers, name, offsetof(RenderLayer, name));
206         }
207 }
208
209 RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, int predivide, int rectx, int recty)
210 {
211         return render_result_new_from_exr(exrhandle, colorspace, predivide, rectx, recty);
212 }
213
214 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
215 {
216         RenderLayer *rl = BLI_findlink(&rr->layers, re->r.actlay);
217         
218         if (rl)
219                 return rl;
220         else 
221                 return rr->layers.first;
222 }
223
224 static int render_scene_needs_vector(Render *re)
225 {
226         SceneRenderLayer *srl;
227         
228         for (srl = re->scene->r.layers.first; srl; srl = srl->next)
229                 if (!(srl->layflag & SCE_LAY_DISABLE))
230                         if (srl->passflag & SCE_PASS_VECTOR)
231                                 return 1;
232
233         return 0;
234 }
235
236 /* *************************************************** */
237
238 Render *RE_GetRender(const char *name)
239 {
240         Render *re;
241
242         /* search for existing renders */
243         for (re = RenderGlobal.renderlist.first; re; re = re->next)
244                 if (strncmp(re->name, name, RE_MAXNAME) == 0)
245                         break;
246
247         return re;
248 }
249
250
251 /* if you want to know exactly what has been done */
252 RenderResult *RE_AcquireResultRead(Render *re)
253 {
254         if (re) {
255                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
256                 return re->result;
257         }
258
259         return NULL;
260 }
261
262 RenderResult *RE_AcquireResultWrite(Render *re)
263 {
264         if (re) {
265                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
266                 return re->result;
267         }
268
269         return NULL;
270 }
271
272 void RE_SwapResult(Render *re, RenderResult **rr)
273 {
274         /* for keeping render buffers */
275         if (re) {
276                 SWAP(RenderResult *, re->result, *rr);
277         }
278 }
279
280
281 void RE_ReleaseResult(Render *re)
282 {
283         if (re)
284                 BLI_rw_mutex_unlock(&re->resultmutex);
285 }
286
287 /* displist.c util.... */
288 Scene *RE_GetScene(Render *re)
289 {
290         if (re)
291                 return re->scene;
292         return NULL;
293 }
294
295 /* fill provided result struct with what's currently active or done */
296 void RE_AcquireResultImage(Render *re, RenderResult *rr)
297 {
298         memset(rr, 0, sizeof(RenderResult));
299
300         if (re) {
301                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
302
303                 if (re->result) {
304                         RenderLayer *rl;
305                         
306                         rr->rectx = re->result->rectx;
307                         rr->recty = re->result->recty;
308                         
309                         rr->rectf = re->result->rectf;
310                         rr->rectz = re->result->rectz;
311                         rr->rect32 = re->result->rect32;
312                         
313                         /* active layer */
314                         rl = render_get_active_layer(re, re->result);
315
316                         if (rl) {
317                                 if (rr->rectf == NULL)
318                                         rr->rectf = rl->rectf;
319                                 if (rr->rectz == NULL)
320                                         rr->rectz = RE_RenderLayerGetPass(rl, SCE_PASS_Z);
321                         }
322
323                         rr->have_combined = (re->result->rectf != NULL);
324                         rr->layers = re->result->layers;
325                 }
326         }
327 }
328
329 void RE_ReleaseResultImage(Render *re)
330 {
331         if (re)
332                 BLI_rw_mutex_unlock(&re->resultmutex);
333 }
334
335 /* caller is responsible for allocating rect in correct size! */
336 void RE_ResultGet32(Render *re, unsigned int *rect)
337 {
338         RenderResult rres;
339         
340         RE_AcquireResultImage(re, &rres);
341         render_result_rect_get_pixels(&rres, &re->r, rect, re->rectx, re->recty, &re->scene->view_settings, &re->scene->display_settings);
342         RE_ReleaseResultImage(re);
343 }
344
345 RenderStats *RE_GetStats(Render *re)
346 {
347         return &re->i;
348 }
349
350 Render *RE_NewRender(const char *name)
351 {
352         Render *re;
353
354         /* only one render per name exists */
355         re = RE_GetRender(name);
356         if (re == NULL) {
357                 
358                 /* new render data struct */
359                 re = MEM_callocN(sizeof(Render), "new render");
360                 BLI_addtail(&RenderGlobal.renderlist, re);
361                 BLI_strncpy(re->name, name, RE_MAXNAME);
362                 BLI_rw_mutex_init(&re->resultmutex);
363         }
364         
365         RE_InitRenderCB(re);
366
367         /* init some variables */
368         re->ycor = 1.0f;
369         
370         return re;
371 }
372
373 /* called for new renders and when finishing rendering so
374  * we always have valid callbacks on a render */
375 void RE_InitRenderCB(Render *re)
376 {
377         /* set default empty callbacks */
378         re->display_init = result_nothing;
379         re->display_clear = result_nothing;
380         re->display_draw = result_rcti_nothing;
381         re->progress = float_nothing;
382         re->test_break = default_break;
383         if (G.background)
384                 re->stats_draw = stats_background;
385         else
386                 re->stats_draw = stats_nothing;
387         /* clear callback handles */
388         re->dih = re->dch = re->ddh = re->sdh = re->prh = re->tbh = NULL;
389 }
390
391 /* only call this while you know it will remove the link too */
392 void RE_FreeRender(Render *re)
393 {
394         if (re->engine)
395                 RE_engine_free(re->engine);
396
397         BLI_rw_mutex_end(&re->resultmutex);
398         
399         free_renderdata_tables(re);
400         free_sample_tables(re);
401         
402         render_result_free(re->result);
403         render_result_free(re->pushedresult);
404         
405         BLI_remlink(&RenderGlobal.renderlist, re);
406         MEM_freeN(re);
407 }
408
409 /* exit blender */
410 void RE_FreeAllRender(void)
411 {
412         while (RenderGlobal.renderlist.first) {
413                 RE_FreeRender(RenderGlobal.renderlist.first);
414         }
415 }
416
417 /* on file load, free all re */
418 void RE_FreeAllRenderResults(void)
419 {
420         Render *re;
421
422         for (re = RenderGlobal.renderlist.first; re; re = re->next) {
423                 render_result_free(re->result);
424                 render_result_free(re->pushedresult);
425
426                 re->result = NULL;
427                 re->pushedresult = NULL;
428         }
429 }
430
431 void RE_FreePersistentData(void)
432 {
433         Render *re;
434
435         /* render engines can be kept around for quick re-render, this clears all */
436         for (re = RenderGlobal.renderlist.first; re; re = re->next) {
437                 if (re->engine) {
438                         RE_engine_free(re->engine);
439                         re->engine = NULL;
440                 }
441         }
442 }
443
444 /* ********* initialize state ******** */
445
446
447 /* what doesn't change during entire render sequence */
448 /* disprect is optional, if NULL it assumes full window render */
449 void RE_InitState(Render *re, Render *source, RenderData *rd, SceneRenderLayer *srl, int winx, int winy, rcti *disprect)
450 {
451         re->ok = TRUE;   /* maybe flag */
452         
453         re->i.starttime = PIL_check_seconds_timer();
454         re->r = *rd;     /* hardcopy */
455         
456         re->winx = winx;
457         re->winy = winy;
458         if (disprect) {
459                 re->disprect = *disprect;
460                 re->rectx = BLI_rcti_size_x(disprect);
461                 re->recty = BLI_rcti_size_y(disprect);
462         }
463         else {
464                 re->disprect.xmin = re->disprect.ymin = 0;
465                 re->disprect.xmax = winx;
466                 re->disprect.ymax = winy;
467                 re->rectx = winx;
468                 re->recty = winy;
469         }
470         
471         if (re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->im_format.imtype) &&
472                                                (re->rectx < 16 || re->recty < 16) ))
473         {
474                 BKE_report(re->reports, RPT_ERROR, "Image too small");
475                 re->ok = 0;
476                 return;
477         }
478
479         if ((re->r.mode & (R_OSA)) == 0)
480                 re->r.scemode &= ~R_FULL_SAMPLE;
481
482 #ifdef WITH_OPENEXR
483         if (re->r.scemode & R_FULL_SAMPLE)
484                 re->r.scemode |= R_EXR_TILE_FILE;   /* enable automatic */
485
486         /* Until use_border is made compatible with save_buffers/full_sample, render without the later instead of not rendering at all.*/
487         if (re->r.mode & R_BORDER) {
488                 re->r.scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
489         }
490
491 #else
492         /* can't do this without openexr support */
493         re->r.scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
494 #endif
495         
496         /* fullsample wants uniform osa levels */
497         if (source && (re->r.scemode & R_FULL_SAMPLE)) {
498                 /* but, if source has no full sample we disable it */
499                 if ((source->r.scemode & R_FULL_SAMPLE) == 0)
500                         re->r.scemode &= ~R_FULL_SAMPLE;
501                 else
502                         re->r.osa = re->osa = source->osa;
503         }
504         else {
505                 /* check state variables, osa? */
506                 if (re->r.mode & (R_OSA)) {
507                         re->osa = re->r.osa;
508                         if (re->osa > 16) re->osa = 16;
509                 }
510                 else re->osa = 0;
511         }
512         
513         if (srl) {
514                 int index = BLI_findindex(&re->r.layers, srl);
515                 if (index != -1) {
516                         re->r.actlay = index;
517                         re->r.scemode |= R_SINGLE_LAYER;
518                 }
519         }
520                 
521         /* always call, checks for gamma, gamma tables and jitter too */
522         make_sample_tables(re);
523         
524         /* if preview render, we try to keep old result */
525         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
526
527         if (re->r.scemode & R_PREVIEWBUTS) {
528                 if (re->result && re->result->rectx == re->rectx && re->result->recty == re->recty) {
529                         /* pass */
530                 }
531                 else {
532                         render_result_free(re->result);
533                         re->result = NULL;
534                 }
535         }
536         else {
537                 
538                 /* make empty render result, so display callbacks can initialize */
539                 render_result_free(re->result);
540                 re->result = MEM_callocN(sizeof(RenderResult), "new render result");
541                 re->result->rectx = re->rectx;
542                 re->result->recty = re->recty;
543         }
544
545         BLI_rw_mutex_unlock(&re->resultmutex);
546         
547         /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
548         re->clipcrop = 1.0f + 2.0f / (float)(re->winx > re->winy ? re->winy : re->winx);
549         
550         re->mblur_offs = re->field_offs = 0.f;
551         
552         RE_init_threadcount(re);
553 }
554
555 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
556 {
557         /* re->ok flag? */
558         
559         re->viewplane = *viewplane;
560         re->clipsta = clipsta;
561         re->clipend = clipend;
562         re->r.mode &= ~R_ORTHO;
563
564         perspective_m4(re->winmat,
565                        re->viewplane.xmin, re->viewplane.xmax,
566                        re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
567         
568 }
569
570 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
571 {
572         /* re->ok flag? */
573         
574         re->viewplane = *viewplane;
575         re->clipsta = clipsta;
576         re->clipend = clipend;
577         re->r.mode |= R_ORTHO;
578
579         orthographic_m4(re->winmat,
580                         re->viewplane.xmin, re->viewplane.xmax,
581                         re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
582 }
583
584 void RE_SetView(Render *re, float mat[][4])
585 {
586         /* re->ok flag? */
587         copy_m4_m4(re->viewmat, mat);
588         invert_m4_m4(re->viewinv, re->viewmat);
589 }
590
591 /* image and movie output has to move to either imbuf or kernel */
592 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
593 {
594         re->display_init = f;
595         re->dih = handle;
596 }
597 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
598 {
599         re->display_clear = f;
600         re->dch = handle;
601 }
602 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
603 {
604         re->display_draw = f;
605         re->ddh = handle;
606 }
607 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
608 {
609         re->stats_draw = f;
610         re->sdh = handle;
611 }
612 void RE_progress_cb(Render *re, void *handle, void (*f)(void *handle, float))
613 {
614         re->progress = f;
615         re->prh = handle;
616 }
617
618 void RE_draw_lock_cb(Render *re, void *handle, void (*f)(void *handle, int i))
619 {
620         re->draw_lock = f;
621         re->tbh = handle;
622 }
623
624 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
625 {
626         re->test_break = f;
627         re->tbh = handle;
628 }
629
630
631 /* ********* add object data (later) ******** */
632
633 /* object is considered fully prepared on correct time etc */
634 /* includes lights */
635 #if 0
636 void RE_AddObject(Render *UNUSED(re), Object *UNUSED(ob))
637 {
638         
639 }
640 #endif
641
642 /* *************************************** */
643
644 static int render_display_draw_enabled(Render *re)
645 {
646         /* don't show preprocess for previewrender sss */
647         if (re->sss_points)
648                 return !(re->r.scemode & R_PREVIEWBUTS);
649         else
650                 return 1;
651 }
652
653 /* the main thread call, renders an entire part */
654 static void *do_part_thread(void *pa_v)
655 {
656         RenderPart *pa = pa_v;
657         
658         /* need to return nicely all parts on esc */
659         if (R.test_break(R.tbh) == 0) {
660                 
661                 if (!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
662                         pa->result = render_result_new_full_sample(&R, &pa->fullresult, &pa->disprect, pa->crop, RR_USE_MEM);
663                 else
664                         pa->result = render_result_new(&R, &pa->disprect, pa->crop, RR_USE_MEM, RR_ALL_LAYERS);
665
666                 if (R.sss_points)
667                         zbufshade_sss_tile(pa);
668                 else if (R.osa)
669                         zbufshadeDA_tile(pa);
670                 else
671                         zbufshade_tile(pa);
672                 
673                 /* merge too on break! */
674                 if (R.result->do_exr_tile) {
675                         render_result_exr_file_merge(R.result, pa->result);
676                 }
677                 else if (render_display_draw_enabled(&R)) {
678                         /* on break, don't merge in result for preview renders, looks nicer */
679                         if (R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS)) {
680                                 /* pass */
681                         }
682                         else {
683                                 render_result_merge(R.result, pa->result);
684                         }
685                 }
686         }
687         
688         pa->ready = 1;
689         
690         return NULL;
691 }
692
693 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
694 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
695 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
696 float panorama_pixel_rot(Render *re)
697 {
698         float psize, phi, xfac;
699         float borderfac = (float)BLI_rcti_size_x(&re->disprect) / (float)re->winx;
700         int xparts = (re->rectx + re->partx - 1) / re->partx;
701         
702         /* size of 1 pixel mapped to viewplane coords */
703         psize = BLI_rctf_size_x(&re->viewplane) / (float)re->winx;
704         /* angle of a pixel */
705         phi = atan(psize / re->clipsta);
706         
707         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
708         xfac = borderfac * BLI_rctf_size_x(&re->viewplane) / (float)xparts;
709         xfac = atan(0.5f * xfac / re->clipsta);
710         /* and how much the same viewplane angle is wrapped */
711         psize = 0.5f * phi * ((float)re->partx);
712         
713         /* the ratio applied to final per-pixel angle */
714         phi *= xfac / psize;
715         
716         return phi;
717 }
718
719 /* call when all parts stopped rendering, to find the next Y slice */
720 /* if slice found, it rotates the dbase */
721 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
722 {
723         RenderPart *pa, *best = NULL;
724         
725         *minx = re->winx;
726         
727         /* most left part of the non-rendering parts */
728         for (pa = re->parts.first; pa; pa = pa->next) {
729                 if (pa->ready == 0 && pa->nr == 0) {
730                         if (pa->disprect.xmin < *minx) {
731                                 best = pa;
732                                 *minx = pa->disprect.xmin;
733                         }
734                 }
735         }
736                         
737         if (best) {
738                 float phi = panorama_pixel_rot(re);
739
740                 R.panodxp = (re->winx - (best->disprect.xmin + best->disprect.xmax) ) / 2;
741                 R.panodxv = (BLI_rctf_size_x(viewplane) * R.panodxp) / (float)(re->winx);
742                 
743                 /* shift viewplane */
744                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
745                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
746                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
747                 copy_m4_m4(R.winmat, re->winmat);
748                 
749                 /* rotate database according to part coordinates */
750                 project_renderdata(re, projectverto, 1, -R.panodxp * phi, 1);
751                 R.panosi = sin(R.panodxp * phi);
752                 R.panoco = cos(R.panodxp * phi);
753         }
754         return best;
755 }
756
757 static RenderPart *find_next_part(Render *re, int minx)
758 {
759         RenderPart *pa, *best = NULL;
760
761         /* long long int's needed because of overflow [#24414] */
762         long long int centx = re->winx / 2, centy = re->winy / 2, tot = 1;
763         long long int mindist = (long long int)re->winx * (long long int)re->winy;
764         
765         /* find center of rendered parts, image center counts for 1 too */
766         for (pa = re->parts.first; pa; pa = pa->next) {
767                 if (pa->ready) {
768                         centx += BLI_rcti_cent_x(&pa->disprect);
769                         centy += BLI_rcti_cent_y(&pa->disprect);
770                         tot++;
771                 }
772         }
773         centx /= tot;
774         centy /= tot;
775         
776         /* closest of the non-rendering parts */
777         for (pa = re->parts.first; pa; pa = pa->next) {
778                 if (pa->ready == 0 && pa->nr == 0) {
779                         long long int distx = centx - BLI_rcti_cent_x(&pa->disprect);
780                         long long int disty = centy - BLI_rcti_cent_y(&pa->disprect);
781                         distx = (long long int)sqrt(distx * distx + disty * disty);
782                         if (distx < mindist) {
783                                 if (re->r.mode & R_PANORAMA) {
784                                         if (pa->disprect.xmin == minx) {
785                                                 best = pa;
786                                                 mindist = distx;
787                                         }
788                                 }
789                                 else {
790                                         best = pa;
791                                         mindist = distx;
792                                 }
793                         }
794                 }
795         }
796         return best;
797 }
798
799 static void print_part_stats(Render *re, RenderPart *pa)
800 {
801         char str[64];
802         
803         BLI_snprintf(str, sizeof(str), "%s, Part %d-%d", re->scene->id.name + 2, pa->nr, re->i.totpart);
804         re->i.infostr = str;
805         re->stats_draw(re->sdh, &re->i);
806         re->i.infostr = NULL;
807 }
808
809 static void threaded_tile_processor(Render *re)
810 {
811         ListBase threads;
812         RenderPart *pa, *nextpa;
813         rctf viewplane = re->viewplane;
814         int rendering = 1, counter = 1, drawtimer = 0, hasdrawn, minx = 0;
815         
816         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
817
818         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
819         if (re->result == NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
820                 render_result_free(re->result);
821         
822                 if (re->sss_points && render_display_draw_enabled(re))
823                         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
824                 else if (re->r.scemode & R_FULL_SAMPLE)
825                         re->result = render_result_new_full_sample(re, &re->fullresult, &re->disprect, 0, RR_USE_EXR);
826                 else
827                         re->result = render_result_new(re, &re->disprect, 0,
828                                                        (re->r.scemode & R_EXR_TILE_FILE) ? RR_USE_EXR : RR_USE_MEM, RR_ALL_LAYERS);
829         }
830
831         BLI_rw_mutex_unlock(&re->resultmutex);
832         
833         if (re->result == NULL)
834                 return;
835         
836         /* warning; no return here without closing exr file */
837         
838         initparts(re, TRUE);
839
840         if (re->result->do_exr_tile)
841                 render_result_exr_file_begin(re);
842         
843         BLI_init_threads(&threads, do_part_thread, re->r.threads);
844         
845         /* assuming no new data gets added to dbase... */
846         R = *re;
847         
848         /* set threadsafe break */
849         R.test_break = thread_break;
850         
851         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
852         if (re->r.mode & R_PANORAMA)
853                 nextpa = find_next_pano_slice(re, &minx, &viewplane);
854         else
855                 nextpa = find_next_part(re, 0);
856         
857         while (rendering) {
858                 
859                 if (re->test_break(re->tbh))
860                         PIL_sleep_ms(50);
861                 else if (nextpa && BLI_available_threads(&threads)) {
862                         drawtimer = 0;
863                         nextpa->nr = counter++;  /* for nicest part, and for stats */
864                         nextpa->thread = BLI_available_thread_index(&threads);   /* sample index */
865                         BLI_insert_thread(&threads, nextpa);
866
867                         nextpa = find_next_part(re, minx);
868                 }
869                 else if (re->r.mode & R_PANORAMA) {
870                         if (nextpa == NULL && BLI_available_threads(&threads) == re->r.threads)
871                                 nextpa = find_next_pano_slice(re, &minx, &viewplane);
872                         else {
873                                 PIL_sleep_ms(50);
874                                 drawtimer++;
875                         }
876                 }
877                 else {
878                         PIL_sleep_ms(50);
879                         drawtimer++;
880                 }
881                 
882                 /* check for ready ones to display, and if we need to continue */
883                 rendering = 0;
884                 hasdrawn = 0;
885                 for (pa = re->parts.first; pa; pa = pa->next) {
886                         if (pa->ready) {
887                                 
888                                 BLI_remove_thread(&threads, pa);
889                                 
890                                 if (pa->result) {
891                                         if (render_display_draw_enabled(re))
892                                                 re->display_draw(re->ddh, pa->result, NULL);
893                                         print_part_stats(re, pa);
894                                         
895                                         render_result_free_list(&pa->fullresult, pa->result);
896                                         pa->result = NULL;
897                                         re->i.partsdone++;
898                                         re->progress(re->prh, re->i.partsdone / (float)re->i.totpart);
899                                         hasdrawn = 1;
900                                 }
901                         }
902                         else {
903                                 rendering = 1;
904                                 if (pa->nr && pa->result && drawtimer > 20) {
905                                         if (render_display_draw_enabled(re))
906                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
907                                         hasdrawn = 1;
908                                 }
909                         }
910                 }
911                 if (hasdrawn)
912                         drawtimer = 0;
913
914                 /* on break, wait for all slots to get freed */
915                 if ( (g_break = re->test_break(re->tbh)) && BLI_available_threads(&threads) == re->r.threads)
916                         rendering = 0;
917                 
918         }
919         
920         if (re->result->do_exr_tile) {
921                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
922                 render_result_exr_file_end(re);
923                 BLI_rw_mutex_unlock(&re->resultmutex);
924         }
925         
926         /* unset threadsafety */
927         g_break = 0;
928         
929         BLI_end_threads(&threads);
930         freeparts(re);
931         re->viewplane = viewplane; /* restore viewplane, modified by pano render */
932 }
933
934 /* currently only called by preview renders and envmap */
935 void RE_TileProcessor(Render *re)
936 {
937         threaded_tile_processor(re);
938 }
939
940 /* ************  This part uses API, for rendering Blender scenes ********** */
941
942 static void add_freestyle(Render *re);
943
944 static void do_render_3d(Render *re)
945 {
946         /* try external */
947         if (RE_engine_render(re, 0))
948                 return;
949
950         /* internal */
951         
952 //      re->cfra= cfra; /* <- unused! */
953         re->scene->r.subframe = re->mblur_offs + re->field_offs;
954         
955         /* lock drawing in UI during data phase */
956         if (re->draw_lock)
957                 re->draw_lock(re->dlh, 1);
958         
959         /* make render verts/faces/halos/lamps */
960         if (render_scene_needs_vector(re))
961                 RE_Database_FromScene_Vectors(re, re->main, re->scene, re->lay);
962         else
963                 RE_Database_FromScene(re, re->main, re->scene, re->lay, 1);
964         
965         /* clear UI drawing locks */
966         if (re->draw_lock)
967                 re->draw_lock(re->dlh, 0);
968         
969         threaded_tile_processor(re);
970         
971         /* do left-over 3d post effects (flares) */
972         if (re->flag & R_HALO)
973                 if (!re->test_break(re->tbh))
974                         add_halo_flare(re);
975         
976         /* Freestyle  */
977         if( re->r.mode & R_EDGE_FRS)
978                 if(!re->test_break(re->tbh))
979                         add_freestyle(re);
980                 
981         /* free all render verts etc */
982         RE_Database_Free(re);
983         
984         re->scene->r.subframe = 0.f;
985 }
986
987 /* called by blur loop, accumulate RGBA key alpha */
988 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
989 {
990         float mfac = 1.0f - blurfac;
991         int a, b, stride = 4 * rr->rectx;
992         int len = stride * sizeof(float);
993         
994         for (a = 0; a < rr->recty; a++) {
995                 if (blurfac == 1.0f) {
996                         memcpy(rectf, rectf1, len);
997                 }
998                 else {
999                         float *rf = rectf, *rf1 = rectf1;
1000                         
1001                         for (b = rr->rectx; b > 0; b--, rf += 4, rf1 += 4) {
1002                                 if (rf1[3] < 0.01f)
1003                                         rf[3] = mfac * rf[3];
1004                                 else if (rf[3] < 0.01f) {
1005                                         rf[0] = rf1[0];
1006                                         rf[1] = rf1[1];
1007                                         rf[2] = rf1[2];
1008                                         rf[3] = blurfac * rf1[3];
1009                                 }
1010                                 else {
1011                                         rf[0] = mfac * rf[0] + blurfac * rf1[0];
1012                                         rf[1] = mfac * rf[1] + blurfac * rf1[1];
1013                                         rf[2] = mfac * rf[2] + blurfac * rf1[2];
1014                                         rf[3] = mfac * rf[3] + blurfac * rf1[3];
1015                                 }
1016                         }
1017                 }
1018                 rectf += stride;
1019                 rectf1 += stride;
1020         }
1021 }
1022
1023 /* called by blur loop, accumulate renderlayers */
1024 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1025 {
1026         float mfac = 1.0f - blurfac;
1027         int a, b, stride = channels * rr->rectx;
1028         int len = stride * sizeof(float);
1029         
1030         for (a = 0; a < rr->recty; a++) {
1031                 if (blurfac == 1.0f) {
1032                         memcpy(rectf, rectf1, len);
1033                 }
1034                 else {
1035                         float *rf = rectf, *rf1 = rectf1;
1036                         
1037                         for (b = rr->rectx * channels; b > 0; b--, rf++, rf1++) {
1038                                 rf[0] = mfac * rf[0] + blurfac * rf1[0];
1039                         }
1040                 }
1041                 rectf += stride;
1042                 rectf1 += stride;
1043         }
1044 }
1045
1046
1047 /* called by blur loop, accumulate renderlayers */
1048 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1049 {
1050         RenderLayer *rl, *rl1;
1051         RenderPass *rpass, *rpass1;
1052         
1053         rl1 = brr->layers.first;
1054         for (rl = rr->layers.first; rl && rl1; rl = rl->next, rl1 = rl1->next) {
1055                 
1056                 /* combined */
1057                 if (rl->rectf && rl1->rectf) {
1058                         if (key_alpha)
1059                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1060                         else
1061                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1062                 }
1063                 
1064                 /* passes are allocated in sync */
1065                 rpass1 = rl1->passes.first;
1066                 for (rpass = rl->passes.first; rpass && rpass1; rpass = rpass->next, rpass1 = rpass1->next) {
1067                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1068                 }
1069         }
1070 }
1071
1072 /* main blur loop, can be called by fields too */
1073 static void do_render_blur_3d(Render *re)
1074 {
1075         RenderResult *rres;
1076         float blurfac;
1077         int blur = re->r.mblur_samples;
1078         
1079         /* create accumulation render result */
1080         rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1081         
1082         /* do the blur steps */
1083         while (blur--) {
1084                 re->mblur_offs = re->r.blurfac * ((float)(re->r.mblur_samples - blur)) / (float)re->r.mblur_samples;
1085                 
1086                 re->i.curblur = re->r.mblur_samples - blur;    /* stats */
1087                 
1088                 do_render_3d(re);
1089                 
1090                 blurfac = 1.0f / (float)(re->r.mblur_samples - blur);
1091                 
1092                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1093                 if (re->test_break(re->tbh)) break;
1094         }
1095         
1096         /* swap results */
1097         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1098         render_result_free(re->result);
1099         re->result = rres;
1100         BLI_rw_mutex_unlock(&re->resultmutex);
1101         
1102         re->mblur_offs = 0.0f;
1103         re->i.curblur = 0;   /* stats */
1104         
1105         /* weak... the display callback wants an active renderlayer pointer... */
1106         re->result->renlay = render_get_active_layer(re, re->result);
1107         re->display_draw(re->ddh, re->result, NULL);
1108 }
1109
1110
1111 /* function assumes rectf1 and rectf2 to be half size of rectf */
1112 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1113 {
1114         int a, stride = channels * rr->rectx;
1115         int len = stride * sizeof(float);
1116         
1117         for (a = 0; a < rr->recty; a += 2) {
1118                 memcpy(rectf, rectf1, len);
1119                 rectf += stride;
1120                 rectf1 += stride;
1121                 memcpy(rectf, rectf2, len);
1122                 rectf += stride;
1123                 rectf2 += stride;
1124         }
1125 }
1126
1127 /* merge render results of 2 fields */
1128 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1129 {
1130         RenderLayer *rl, *rl1, *rl2;
1131         RenderPass *rpass, *rpass1, *rpass2;
1132         
1133         rl1 = rr1->layers.first;
1134         rl2 = rr2->layers.first;
1135         for (rl = rr->layers.first; rl && rl1 && rl2; rl = rl->next, rl1 = rl1->next, rl2 = rl2->next) {
1136                 
1137                 /* combined */
1138                 if (rl->rectf && rl1->rectf && rl2->rectf)
1139                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1140                 
1141                 /* passes are allocated in sync */
1142                 rpass1 = rl1->passes.first;
1143                 rpass2 = rl2->passes.first;
1144                 for (rpass = rl->passes.first;
1145                      rpass && rpass1 && rpass2;
1146                      rpass = rpass->next, rpass1 = rpass1->next, rpass2 = rpass2->next)
1147                 {
1148                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1149                 }
1150         }
1151 }
1152
1153
1154 /* interleaves 2 frames */
1155 static void do_render_fields_3d(Render *re)
1156 {
1157         Object *camera = RE_GetCamera(re);
1158         RenderResult *rr1, *rr2 = NULL;
1159         
1160         /* no render result was created, we can safely halve render y */
1161         re->winy /= 2;
1162         re->recty /= 2;
1163         re->disprect.ymin /= 2;
1164         re->disprect.ymax /= 2;
1165         
1166         re->i.curfield = 1;  /* stats */
1167         
1168         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1169         RE_SetCamera(re, camera);
1170         if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1171                 do_render_blur_3d(re);
1172         else
1173                 do_render_3d(re);
1174
1175         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1176         rr1 = re->result;
1177         re->result = NULL;
1178         BLI_rw_mutex_unlock(&re->resultmutex);
1179         
1180         /* second field */
1181         if (!re->test_break(re->tbh)) {
1182                 
1183                 re->i.curfield = 2;  /* stats */
1184                 
1185                 re->flag |= R_SEC_FIELD;
1186                 if ((re->r.mode & R_FIELDSTILL) == 0) {
1187                         re->field_offs = 0.5f;
1188                 }
1189                 RE_SetCamera(re, camera);
1190                 if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1191                         do_render_blur_3d(re);
1192                 else
1193                         do_render_3d(re);
1194                 re->flag &= ~R_SEC_FIELD;
1195                 
1196                 re->field_offs = 0.0f;
1197                 
1198                 rr2 = re->result;
1199         }
1200         
1201         /* allocate original height new buffers */
1202         re->winy *= 2;
1203         re->recty *= 2;
1204         re->disprect.ymin *= 2;
1205         re->disprect.ymax *= 2;
1206
1207         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1208         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1209
1210         if (rr2) {
1211                 if (re->r.mode & R_ODDFIELD)
1212                         merge_renderresult_fields(re->result, rr2, rr1);
1213                 else
1214                         merge_renderresult_fields(re->result, rr1, rr2);
1215                 
1216                 render_result_free(rr2);
1217         }
1218
1219         render_result_free(rr1);
1220         
1221         re->i.curfield = 0;  /* stats */
1222         
1223         /* weak... the display callback wants an active renderlayer pointer... */
1224         re->result->renlay = render_get_active_layer(re, re->result);
1225
1226         BLI_rw_mutex_unlock(&re->resultmutex);
1227
1228         re->display_draw(re->ddh, re->result, NULL);
1229 }
1230
1231 /* main render routine, no compositing */
1232 static void do_render_fields_blur_3d(Render *re)
1233 {
1234         Object *camera = RE_GetCamera(re);
1235         /* also check for camera here */
1236         if (camera == NULL) {
1237                 printf("ERROR: Cannot render, no camera\n");
1238                 G.is_break = TRUE;
1239                 return;
1240         }
1241
1242         /* now use renderdata and camera to set viewplane */
1243         RE_SetCamera(re, camera);
1244         
1245         if (re->r.mode & R_FIELDS)
1246                 do_render_fields_3d(re);
1247         else if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1248                 do_render_blur_3d(re);
1249         else
1250                 do_render_3d(re);
1251         
1252         /* when border render, check if we have to insert it in black */
1253         if (re->result) {
1254                 if (re->r.mode & R_BORDER) {
1255                         if ((re->r.mode & R_CROP) == 0) {
1256                                 RenderResult *rres;
1257                                 
1258                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1259
1260                                 /* sub-rect for merge call later on */
1261                                 re->result->tilerect = re->disprect;
1262                                 
1263                                 /* this copying sequence could become function? */
1264                                 /* weak is: it chances disprect from border */
1265                                 re->disprect.xmin = re->disprect.ymin = 0;
1266                                 re->disprect.xmax = re->winx;
1267                                 re->disprect.ymax = re->winy;
1268                                 re->rectx = re->winx;
1269                                 re->recty = re->winy;
1270                                 
1271                                 rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1272                                 
1273                                 render_result_merge(rres, re->result);
1274                                 render_result_free(re->result);
1275                                 re->result = rres;
1276                                 
1277                                 /* weak... the display callback wants an active renderlayer pointer... */
1278                                 re->result->renlay = render_get_active_layer(re, re->result);
1279                                 
1280                                 BLI_rw_mutex_unlock(&re->resultmutex);
1281                 
1282                                 re->display_init(re->dih, re->result);
1283                                 re->display_draw(re->ddh, re->result, NULL);
1284                         }
1285                         else {
1286                                 /* set offset (again) for use in compositor, disprect was manipulated. */
1287                                 re->result->xof = 0;
1288                                 re->result->yof = 0;
1289                         }
1290                 }
1291         }
1292 }
1293
1294
1295 /* within context of current Render *re, render another scene.
1296  * it uses current render image size and disprect, but doesn't execute composite
1297  */
1298 static void render_scene(Render *re, Scene *sce, int cfra)
1299 {
1300         Render *resc = RE_NewRender(sce->id.name);
1301         int winx = re->winx, winy = re->winy;
1302         
1303         sce->r.cfra = cfra;
1304
1305         BKE_scene_camera_switch_update(sce);
1306
1307         /* exception: scene uses own size (unfinished code) */
1308         if (0) {
1309                 winx = (sce->r.size * sce->r.xsch) / 100;
1310                 winy = (sce->r.size * sce->r.ysch) / 100;
1311         }
1312         
1313         /* initial setup */
1314         RE_InitState(resc, re, &sce->r, NULL, winx, winy, &re->disprect);
1315         
1316         /* still unsure entity this... */
1317         resc->main = re->main;
1318         resc->scene = sce;
1319         resc->lay = sce->lay;
1320         
1321         /* ensure scene has depsgraph, base flags etc OK */
1322         BKE_scene_set_background(re->main, sce);
1323
1324         /* copy callbacks */
1325         resc->display_draw = re->display_draw;
1326         resc->ddh = re->ddh;
1327         resc->test_break = re->test_break;
1328         resc->tbh = re->tbh;
1329         resc->stats_draw = re->stats_draw;
1330         resc->sdh = re->sdh;
1331         
1332         do_render_fields_blur_3d(resc);
1333 }
1334
1335 /* helper call to detect if this scene needs a render, or if there's a any render layer to render */
1336 static int composite_needs_render(Scene *sce, int this_scene)
1337 {
1338         bNodeTree *ntree = sce->nodetree;
1339         bNode *node;
1340         
1341         if (ntree == NULL) return 1;
1342         if (sce->use_nodes == FALSE) return 1;
1343         if ((sce->r.scemode & R_DOCOMP) == 0) return 1;
1344         
1345         for (node = ntree->nodes.first; node; node = node->next) {
1346                 if (node->type == CMP_NODE_R_LAYERS)
1347                         if (this_scene == 0 || node->id == NULL || node->id == &sce->id)
1348                                 return 1;
1349         }
1350         return 0;
1351 }
1352
1353 static void tag_scenes_for_render(Render *re)
1354 {
1355         bNode *node;
1356         Scene *sce;
1357         
1358         for (sce = re->main->scene.first; sce; sce = sce->id.next)
1359                 sce->id.flag &= ~LIB_DOIT;
1360         
1361         if (RE_GetCamera(re) && composite_needs_render(re->scene, 1))
1362                 re->scene->id.flag |= LIB_DOIT;
1363         
1364         if (re->scene->nodetree == NULL) return;
1365         
1366         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
1367         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1368                 if (node->type == CMP_NODE_R_LAYERS) {
1369                         if (node->id) {
1370                                 if (node->id != (ID *)re->scene)
1371                                         node->id->flag |= LIB_DOIT;
1372                         }
1373                 }
1374         }
1375         
1376 }
1377
1378 static void ntree_render_scenes(Render *re)
1379 {
1380         bNode *node;
1381         int cfra = re->scene->r.cfra;
1382         int restore_scene = 0;
1383         
1384         if (re->scene->nodetree == NULL) return;
1385         
1386         tag_scenes_for_render(re);
1387         
1388         /* now foreach render-result node tagged we do a full render */
1389         /* results are stored in a way compisitor will find it */
1390         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1391                 if (node->type == CMP_NODE_R_LAYERS) {
1392                         if (node->id && node->id != (ID *)re->scene) {
1393                                 if (node->id->flag & LIB_DOIT) {
1394                                         Scene *scene = (Scene *)node->id;
1395
1396                                         render_scene(re, scene, cfra);
1397                                         restore_scene = (scene != re->scene);
1398                                         node->id->flag &= ~LIB_DOIT;
1399                                         
1400                                         nodeUpdate(re->scene->nodetree, node);
1401                                 }
1402                         }
1403                 }
1404         }
1405
1406         /* restore scene if we rendered another last */
1407         if (restore_scene)
1408                 BKE_scene_set_background(re->main, re->scene);
1409 }
1410
1411 /* bad call... need to think over proper method still */
1412 static void render_composit_stats(void *UNUSED(arg), char *str)
1413 {
1414         R.i.infostr = str;
1415         R.stats_draw(R.sdh, &R.i);
1416         R.i.infostr = NULL;
1417 }
1418
1419 /* invokes Freestyle stroke rendering */
1420 static void add_freestyle(Render *re)
1421 {
1422         SceneRenderLayer *srl, *actsrl;
1423         LinkData *link;
1424
1425         actsrl = BLI_findlink(&re->r.layers, re->r.actlay);
1426
1427         FRS_init_stroke_rendering(re);
1428
1429         for (srl= (SceneRenderLayer *)re->r.layers.first; srl; srl= srl->next) {
1430
1431                 link = (LinkData *)MEM_callocN(sizeof(LinkData), "LinkData to Freestyle render");
1432                 BLI_addtail(&re->freestyle_renders, link);
1433
1434                 if ((re->r.scemode & R_SINGLE_LAYER) && srl != actsrl)
1435                         continue;
1436                 if (FRS_is_freestyle_enabled(srl)) {
1437                         link->data = (void *)FRS_do_stroke_rendering(re, srl);
1438                 }
1439         }
1440
1441         FRS_finish_stroke_rendering(re);
1442 }
1443
1444 /* merges the results of Freestyle stroke rendering into a given render result */
1445 static void composite_freestyle_renders(Render *re, int sample)
1446 {
1447         Render *freestyle_render;
1448         SceneRenderLayer *srl, *actsrl;
1449         LinkData *link;
1450
1451         actsrl = BLI_findlink(&re->r.layers, re->r.actlay);
1452
1453         link = (LinkData *)re->freestyle_renders.first;
1454         for (srl= (SceneRenderLayer *)re->r.layers.first; srl; srl= srl->next) {
1455                 if ((re->r.scemode & R_SINGLE_LAYER) && srl != actsrl)
1456                         continue;
1457                 if (FRS_is_freestyle_enabled(srl)) {
1458                         freestyle_render = (Render *)link->data;
1459                         render_result_exr_file_read(freestyle_render, sample);
1460                         FRS_composite_result(re, srl, freestyle_render);
1461                         RE_FreeRenderResult(freestyle_render->result);
1462                         freestyle_render->result = NULL;
1463                 }
1464                 link = link->next;
1465         }
1466 }
1467
1468 /* releases temporary scenes and renders for Freestyle stroke rendering */
1469 static void free_all_freestyle_renders(Scene *scene)
1470 {
1471         Render *re1, *freestyle_render;
1472         LinkData *link;
1473
1474         for (re1= RenderGlobal.renderlist.first; re1; re1= re1->next) {
1475                 for (link = (LinkData *)re1->freestyle_renders.first; link; link = link->next) {
1476                         if (link->data) {
1477                                 freestyle_render = (Render *)link->data;
1478                                 BKE_scene_unlink(G.main, freestyle_render->scene, scene);
1479                                 RE_FreeRender(freestyle_render);
1480                         }
1481                 }
1482                 BLI_freelistN( &re1->freestyle_renders );
1483         }
1484 }
1485
1486
1487 /* reads all buffers, calls optional composite, merges in first result->rectf */
1488 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
1489 {
1490         float *rectf, filt[3][3];
1491         int x, y, sample;
1492         
1493         /* interaction callbacks */
1494         if (ntree) {
1495                 ntree->stats_draw = render_composit_stats;
1496                 ntree->test_break = re->test_break;
1497                 ntree->progress = re->progress;
1498                 ntree->sdh = re->sdh;
1499                 ntree->tbh = re->tbh;
1500                 ntree->prh = re->prh;
1501         }
1502         
1503         /* filtmask needs it */
1504         R = *re;
1505         
1506         /* we accumulate in here */
1507         rectf = MEM_mapallocN(re->rectx * re->recty * sizeof(float) * 4, "fullsample rgba");
1508         
1509         for (sample = 0; sample < re->r.osa; sample++) {
1510                 Render *re1;
1511                 RenderResult rres;
1512                 int mask;
1513                 
1514                 /* enable full sample print */
1515                 R.i.curfsa = sample + 1;
1516                 
1517                 /* set all involved renders on the samplebuffers (first was done by render itself, but needs tagged) */
1518                 /* also function below assumes this */
1519                         
1520                 tag_scenes_for_render(re);
1521                 for (re1 = RenderGlobal.renderlist.first; re1; re1 = re1->next) {
1522                         if (re1->scene->id.flag & LIB_DOIT) {
1523                                 if (re1->r.scemode & R_FULL_SAMPLE) {
1524                                         if (sample) {
1525                                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1526                                                 render_result_exr_file_read(re1, sample);
1527                                                 if( re1->r.mode & R_EDGE_FRS)
1528                                                         composite_freestyle_renders(re1, sample);
1529                                                 BLI_rw_mutex_unlock(&re->resultmutex);
1530                                         }
1531                                         ntreeCompositTagRender(re1->scene); /* ensure node gets exec to put buffers on stack */
1532                                 }
1533                         }
1534                 }
1535                 
1536                 /* composite */
1537                 if (ntree) {
1538                         ntreeCompositTagRender(re->scene);
1539                         ntreeCompositTagAnimated(ntree);
1540                         
1541                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0, &re->scene->view_settings, &re->scene->display_settings);
1542                 }
1543                 
1544                 /* ensure we get either composited result or the active layer */
1545                 RE_AcquireResultImage(re, &rres);
1546                 
1547                 /* accumulate with filter, and clip */
1548                 mask = (1 << sample);
1549                 mask_array(mask, filt);
1550
1551                 for (y = 0; y < re->recty; y++) {
1552                         float *rf = rectf + 4 * y * re->rectx;
1553                         float *col = rres.rectf + 4 * y * re->rectx;
1554                                 
1555                         for (x = 0; x < re->rectx; x++, rf += 4, col += 4) {
1556                                 /* clamping to 1.0 is needed for correct AA */
1557                                 if (col[0] < 0.0f) col[0] = 0.0f; else if (col[0] > 1.0f) col[0] = 1.0f;
1558                                 if (col[1] < 0.0f) col[1] = 0.0f; else if (col[1] > 1.0f) col[1] = 1.0f;
1559                                 if (col[2] < 0.0f) col[2] = 0.0f; else if (col[2] > 1.0f) col[2] = 1.0f;
1560                                 
1561                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
1562                         }
1563                 }
1564                 
1565                 RE_ReleaseResultImage(re);
1566
1567                 /* show stuff */
1568                 if (sample != re->osa - 1) {
1569                         /* weak... the display callback wants an active renderlayer pointer... */
1570                         re->result->renlay = render_get_active_layer(re, re->result);
1571                         re->display_draw(re->ddh, re->result, NULL);
1572                 }
1573                 
1574                 if (re->test_break(re->tbh))
1575                         break;
1576         }
1577
1578         /* clamp alpha and RGB to 0..1 and 0..inf, can go outside due to filter */
1579         for (y = 0; y < re->recty; y++) {
1580                 float *rf = rectf + 4 * y * re->rectx;
1581                         
1582                 for (x = 0; x < re->rectx; x++, rf += 4) {
1583                         rf[0] = MAX2(rf[0], 0.0f);
1584                         rf[1] = MAX2(rf[1], 0.0f);
1585                         rf[2] = MAX2(rf[2], 0.0f);
1586                         CLAMP(rf[3], 0.0f, 1.0f);
1587                 }
1588         }
1589         
1590         /* clear interaction callbacks */
1591         if (ntree) {
1592                 ntree->stats_draw = NULL;
1593                 ntree->test_break = NULL;
1594                 ntree->progress = NULL;
1595                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1596         }
1597         
1598         /* disable full sample print */
1599         R.i.curfsa = 0;
1600         
1601         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1602         if (re->result->rectf)
1603                 MEM_freeN(re->result->rectf);
1604         re->result->rectf = rectf;
1605         BLI_rw_mutex_unlock(&re->resultmutex);
1606 }
1607
1608 /* called externally, via compositor */
1609 void RE_MergeFullSample(Render *re, Main *bmain, Scene *sce, bNodeTree *ntree)
1610 {
1611         Scene *scene;
1612         bNode *node;
1613
1614         /* default start situation */
1615         G.is_break = FALSE;
1616         
1617         re->main = bmain;
1618         re->scene = sce;
1619         re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
1620         
1621         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
1622         
1623         /* tag scenes unread */
1624         for (scene = re->main->scene.first; scene; scene = scene->id.next)
1625                 scene->id.flag |= LIB_DOIT;
1626         
1627         for (node = ntree->nodes.first; node; node = node->next) {
1628                 if (node->type == CMP_NODE_R_LAYERS) {
1629                         Scene *nodescene = (Scene *)node->id;
1630                         
1631                         if (nodescene == NULL) nodescene = sce;
1632                         if (nodescene->id.flag & LIB_DOIT) {
1633                                 nodescene->r.mode |= R_OSA; /* render struct needs tables */
1634                                 RE_ReadRenderResult(sce, nodescene);
1635                                 nodescene->id.flag &= ~LIB_DOIT;
1636                         }
1637                 }
1638         }
1639         
1640         /* own render result should be read/allocated */
1641         if (re->scene->id.flag & LIB_DOIT) {
1642                 RE_ReadRenderResult(re->scene, re->scene);
1643                 re->scene->id.flag &= ~LIB_DOIT;
1644         }
1645         
1646         /* and now we can draw (result is there) */
1647         re->display_init(re->dih, re->result);
1648         re->display_clear(re->dch, re->result);
1649         
1650         do_merge_fullsample(re, ntree);
1651 }
1652
1653 /* returns fully composited render-result on given time step (in RenderData) */
1654 static void do_render_composite_fields_blur_3d(Render *re)
1655 {
1656         bNodeTree *ntree = re->scene->nodetree;
1657         int update_newframe = 0;
1658         
1659         /* INIT seeding, compositor can use random texture */
1660         BLI_srandom(re->r.cfra);
1661         
1662         if (composite_needs_render(re->scene, 1)) {
1663                 /* save memory... free all cached images */
1664                 ntreeFreeCache(ntree);
1665                 
1666                 do_render_fields_blur_3d(re);
1667         }
1668         else {
1669                 /* ensure new result gets added, like for regular renders */
1670                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1671                 
1672                 render_result_free(re->result);
1673                 re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS);
1674
1675                 BLI_rw_mutex_unlock(&re->resultmutex);
1676                 
1677                 /* scene render process already updates animsys */
1678                 update_newframe = 1;
1679         }
1680         
1681         /* swap render result */
1682         if (re->r.scemode & R_SINGLE_LAYER) {
1683                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1684                 render_result_single_layer_end(re);
1685                 BLI_rw_mutex_unlock(&re->resultmutex);
1686         }
1687         
1688         if (!re->test_break(re->tbh)) {
1689                 
1690                 if (ntree) {
1691                         ntreeCompositTagRender(re->scene);
1692                         ntreeCompositTagAnimated(ntree);
1693                 }
1694                 
1695                 if (ntree && re->scene->use_nodes && re->r.scemode & R_DOCOMP) {
1696                         /* checks if there are render-result nodes that need scene */
1697                         if ((re->r.scemode & R_SINGLE_LAYER) == 0)
1698                                 ntree_render_scenes(re);
1699                         
1700                         if (!re->test_break(re->tbh)) {
1701                                 ntree->stats_draw = render_composit_stats;
1702                                 ntree->test_break = re->test_break;
1703                                 ntree->progress = re->progress;
1704                                 ntree->sdh = re->sdh;
1705                                 ntree->tbh = re->tbh;
1706                                 ntree->prh = re->prh;
1707                                 
1708                                 /* in case it was never initialized */
1709                                 R.sdh = re->sdh;
1710                                 R.stats_draw = re->stats_draw;
1711                                 
1712                                 if (update_newframe)
1713                                         BKE_scene_update_for_newframe(re->main, re->scene, re->lay);
1714                                 
1715                                 if (re->r.scemode & R_FULL_SAMPLE)
1716                                         do_merge_fullsample(re, ntree);
1717                                 else {
1718                                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0, &re->scene->view_settings, &re->scene->display_settings);
1719                                 }
1720                                 
1721                                 ntree->stats_draw = NULL;
1722                                 ntree->test_break = NULL;
1723                                 ntree->progress = NULL;
1724                                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1725                         }
1726                 }
1727                 else if (re->r.scemode & R_FULL_SAMPLE)
1728                         do_merge_fullsample(re, NULL);
1729         }
1730
1731         free_all_freestyle_renders(re->scene);
1732
1733         /* weak... the display callback wants an active renderlayer pointer... */
1734         re->result->renlay = render_get_active_layer(re, re->result);
1735         re->display_draw(re->ddh, re->result, NULL);
1736 }
1737
1738 static void renderresult_stampinfo(Render *re)
1739 {
1740         RenderResult rres;
1741
1742         /* this is the basic trick to get the displayed float or char rect from render result */
1743         RE_AcquireResultImage(re, &rres);
1744         BKE_stamp_buf(re->scene, RE_GetCamera(re), (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
1745         RE_ReleaseResultImage(re);
1746 }
1747
1748 int RE_seq_render_active(Scene *scene, RenderData *rd)
1749 {
1750         Editing *ed;
1751         Sequence *seq;
1752
1753         ed = scene->ed;
1754         
1755         if (!(rd->scemode & R_DOSEQ) || !ed || !ed->seqbase.first)
1756                 return 0;
1757         
1758         for (seq = ed->seqbase.first; seq; seq = seq->next) {
1759                 if (seq->type != SEQ_TYPE_SOUND_RAM)
1760                         return 1;
1761         }
1762         
1763         return 0;
1764 }
1765
1766 static void do_render_seq(Render *re)
1767 {
1768         static int recurs_depth = 0;
1769         struct ImBuf *ibuf, *out;
1770         RenderResult *rr; /* don't assign re->result here as it might change during give_ibuf_seq */
1771         int cfra = re->r.cfra;
1772         SeqRenderData context;
1773
1774         re->i.cfra = cfra;
1775
1776         if (recurs_depth == 0) {
1777                 /* otherwise sequencer animation isn't updated */
1778                 BKE_animsys_evaluate_all_animation(re->main, re->scene, (float)cfra); // XXX, was BKE_scene_frame_get(re->scene)
1779         }
1780
1781         recurs_depth++;
1782
1783         if ((re->r.mode & R_BORDER) && (re->r.mode & R_CROP) == 0) {
1784                 /* if border rendering is used and cropping is disabled, final buffer should
1785                  * be as large as the whole frame */
1786                 context = BKE_sequencer_new_render_data(re->main, re->scene,
1787                                               re->winx, re->winy,
1788                                               100);
1789         }
1790         else {
1791                 context = BKE_sequencer_new_render_data(re->main, re->scene,
1792                                               re->result->rectx, re->result->recty,
1793                                               100);
1794         }
1795
1796         out = BKE_sequencer_give_ibuf(context, cfra, 0);
1797
1798         if (out) {
1799                 ibuf = IMB_dupImBuf(out);
1800                 IMB_freeImBuf(out);
1801                 BKE_sequencer_imbuf_from_sequencer_space(re->scene, ibuf);
1802         }
1803         else {
1804                 ibuf = NULL;
1805         }
1806
1807         recurs_depth--;
1808
1809         rr = re->result;
1810         
1811         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1812
1813         if (ibuf) {
1814                 /* copy ibuf into combined pixel rect */
1815                 render_result_rect_from_ibuf(rr, &re->r, ibuf);
1816                 
1817                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
1818                         Editing *ed = re->scene->ed;
1819                         if (ed)
1820                                 BKE_sequencer_free_imbuf(re->scene, &ed->seqbase, TRUE);
1821                 }
1822                 IMB_freeImBuf(ibuf);
1823         }
1824         else {
1825                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
1826                 render_result_rect_fill_zero(rr);
1827         }
1828
1829         BLI_rw_mutex_unlock(&re->resultmutex);
1830
1831         /* just in case this flag went missing at some point */
1832         re->r.scemode |= R_DOSEQ;
1833
1834         /* set overall progress of sequence rendering */
1835         if (re->r.efra != re->r.sfra)
1836                 re->progress(re->prh, (float)(cfra - re->r.sfra) / (re->r.efra - re->r.sfra));
1837         else
1838                 re->progress(re->prh, 1.0f);
1839
1840         /* would mark display buffers as invalid */
1841         re->display_draw(re->ddh, re->result, NULL);
1842 }
1843
1844 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1845
1846 /* main loop: doing sequence + fields + blur + 3d render + compositing */
1847 static void do_render_all_options(Render *re)
1848 {
1849         BKE_scene_camera_switch_update(re->scene);
1850
1851         re->i.starttime = PIL_check_seconds_timer();
1852
1853         /* ensure no images are in memory from previous animated sequences */
1854         BKE_image_all_free_anim_ibufs(re->r.cfra);
1855
1856         if (RE_engine_render(re, 1)) {
1857                 /* in this case external render overrides all */
1858         }
1859         else if (RE_seq_render_active(re->scene, &re->r)) {
1860                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
1861                 if (!re->test_break(re->tbh))
1862                         do_render_seq(re);
1863                 
1864                 re->stats_draw(re->sdh, &re->i);
1865                 re->display_draw(re->ddh, re->result, NULL);
1866         }
1867         else {
1868                 do_render_composite_fields_blur_3d(re);
1869         }
1870         
1871         re->i.lastframetime = PIL_check_seconds_timer() - re->i.starttime;
1872         
1873         re->stats_draw(re->sdh, &re->i);
1874         
1875         /* stamp image info here */
1876         if ((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
1877                 renderresult_stampinfo(re);
1878                 re->display_draw(re->ddh, re->result, NULL);
1879         }
1880 }
1881
1882 static int check_valid_camera(Scene *scene, Object *camera_override)
1883 {
1884         int check_comp = 1;
1885
1886         if (camera_override == NULL && scene->camera == NULL)
1887                 scene->camera = BKE_scene_camera_find(scene);
1888
1889         if (scene->r.scemode & R_DOSEQ) {
1890                 if (scene->ed) {
1891                         Sequence *seq = scene->ed->seqbase.first;
1892
1893                         check_comp = 0;
1894
1895                         while (seq) {
1896                                 if (seq->type == SEQ_TYPE_SCENE && seq->scene) {
1897                                         if (!seq->scene_camera) {
1898                                                 if (!seq->scene->camera && !BKE_scene_camera_find(seq->scene)) {
1899                                                         if (seq->scene == scene) {
1900                                                                 /* for current scene camera could be unneeded due to compisite nodes */
1901                                                                 check_comp = 1;
1902                                                         }
1903                                                         else {
1904                                                                 /* for other scenes camera is necessary */
1905                                                                 return 0;
1906                                                         }
1907                                                 }
1908                                         }
1909                                 }
1910
1911                                 seq = seq->next;
1912                         }
1913                 }
1914         }
1915
1916         if (check_comp) { /* no sequencer or sequencer depends on compositor */
1917                 if (scene->r.scemode & R_DOCOMP && scene->use_nodes) {
1918                         bNode *node = scene->nodetree->nodes.first;
1919
1920                         while (node) {
1921                                 if (node->type == CMP_NODE_R_LAYERS) {
1922                                         Scene *sce = node->id ? (Scene *)node->id : scene;
1923
1924                                         if (!sce->camera && !BKE_scene_camera_find(sce)) {
1925                                                 /* all render layers nodes need camera */
1926                                                 return 0;
1927                                         }
1928                                 }
1929
1930                                 node = node->next;
1931                         }
1932                 }
1933                 else {
1934                         return (camera_override != NULL || scene->camera != NULL);
1935                 }
1936         }
1937
1938         return 1;
1939 }
1940
1941 static int node_tree_has_composite_output(bNodeTree *ntree)
1942 {
1943         bNode *node;
1944
1945         for (node = ntree->nodes.first; node; node = node->next) {
1946                 if (node->type == CMP_NODE_COMPOSITE) {
1947                         return TRUE;
1948                 }
1949                 else if (node->type == NODE_GROUP) {
1950                         if (node->id) {
1951                                 if (node_tree_has_composite_output((bNodeTree *)node->id)) {
1952                                         return TRUE;
1953                                 }
1954                         }
1955                 }
1956         }
1957
1958         return FALSE;
1959 }
1960
1961 static int check_composite_output(Scene *scene)
1962 {
1963         return node_tree_has_composite_output(scene->nodetree);
1964 }
1965
1966 int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *reports)
1967 {
1968         SceneRenderLayer *srl;
1969         
1970         if (scene->r.mode & R_BORDER) {
1971                 if (scene->r.border.xmax <= scene->r.border.xmin ||
1972                     scene->r.border.ymax <= scene->r.border.ymin)
1973                 {
1974                         BKE_report(reports, RPT_ERROR, "No border area selected");
1975                         return 0;
1976                 }
1977         }
1978         
1979         if (scene->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
1980                 char str[FILE_MAX];
1981                 
1982                 render_result_exr_file_path(scene, "", 0, str);
1983                 
1984                 if (BLI_file_is_writable(str) == 0) {
1985                         BKE_report(reports, RPT_ERROR, "Cannot save render buffers, check the temp default path");
1986                         return 0;
1987                 }
1988                 
1989                 /* no fullsample and edge */
1990                 if ((scene->r.scemode & R_FULL_SAMPLE) && (scene->r.mode & R_EDGE)) {
1991                         BKE_report(reports, RPT_ERROR, "Full sample does not support edge enhance");
1992                         return 0;
1993                 }
1994                 
1995         }
1996         else
1997                 scene->r.scemode &= ~R_FULL_SAMPLE;  /* clear to be sure */
1998         
1999         if (scene->r.scemode & R_DOCOMP) {
2000                 if (scene->use_nodes) {
2001                         if (!scene->nodetree) {
2002                                 BKE_report(reports, RPT_ERROR, "No node tree in scene");
2003                                 return 0;
2004                         }
2005                         
2006                         if (!check_composite_output(scene)) {
2007                                 BKE_report(reports, RPT_ERROR, "No render output node in scene");
2008                                 return 0;
2009                         }
2010                         
2011                         if (scene->r.scemode & R_FULL_SAMPLE) {
2012                                 if (composite_needs_render(scene, 0) == 0) {
2013                                         BKE_report(reports, RPT_ERROR, "Full sample AA not supported without 3D rendering");
2014                                         return 0;
2015                                 }
2016                         }
2017                 }
2018         }
2019         
2020         /* check valid camera, without camera render is OK (compo, seq) */
2021         if (!check_valid_camera(scene, camera_override)) {
2022                 BKE_report(reports, RPT_ERROR, "No camera");
2023                 return 0;
2024         }
2025         
2026         /* get panorama & ortho, only after camera is set */
2027         BKE_camera_object_mode(&scene->r, camera_override ? camera_override : scene->camera);
2028
2029         /* forbidden combinations */
2030         if (scene->r.mode & R_PANORAMA) {
2031                 if (scene->r.mode & R_ORTHO) {
2032                         BKE_report(reports, RPT_ERROR, "No ortho render possible for panorama");
2033                         return 0;
2034                 }
2035         }
2036
2037         /* layer flag tests */
2038         if (scene->r.scemode & R_SINGLE_LAYER) {
2039                 srl = BLI_findlink(&scene->r.layers, scene->r.actlay);
2040                 /* force layer to be enabled */
2041                 srl->layflag &= ~SCE_LAY_DISABLE;
2042         }
2043         
2044         for (srl = scene->r.layers.first; srl; srl = srl->next)
2045                 if (!(srl->layflag & SCE_LAY_DISABLE))
2046                         break;
2047         if (srl == NULL) {
2048                 BKE_report(reports, RPT_ERROR, "All render layers are disabled");
2049                 return 0;
2050         }
2051
2052         return 1;
2053 }
2054
2055 static void validate_render_settings(Render *re)
2056 {
2057         if (re->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
2058                 /* no osa + fullsample won't work... */
2059                 if (re->r.osa == 0)
2060                         re->r.scemode &= ~R_FULL_SAMPLE;
2061         }
2062         else re->r.scemode &= ~R_FULL_SAMPLE;   /* clear to be sure */
2063
2064         if (RE_engine_is_external(re)) {
2065                 /* not supported yet */
2066                 re->r.scemode &= ~(R_FULL_SAMPLE);
2067                 re->r.mode &= ~(R_FIELDS | R_MBLUR);
2068         }
2069 }
2070
2071 static void update_physics_cache(Render *re, Scene *scene, int UNUSED(anim_init))
2072 {
2073         PTCacheBaker baker;
2074
2075         baker.main = re->main;
2076         baker.scene = scene;
2077         baker.pid = NULL;
2078         baker.bake = 0;
2079         baker.render = 1;
2080         baker.anim_init = 1;
2081         baker.quick_step = 1;
2082         baker.break_test = re->test_break;
2083         baker.break_data = re->tbh;
2084         baker.progressbar = NULL;
2085
2086         BKE_ptcache_bake(&baker);
2087 }
2088 /* evaluating scene options for general Blender render */
2089 static int render_initialize_from_main(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int anim, int anim_init)
2090 {
2091         int winx, winy;
2092         rcti disprect;
2093         
2094         /* r.xsch and r.ysch has the actual view window size
2095          * r.border is the clipping rect */
2096         
2097         /* calculate actual render result and display size */
2098         winx = (scene->r.size * scene->r.xsch) / 100;
2099         winy = (scene->r.size * scene->r.ysch) / 100;
2100         
2101         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2102         if (scene->r.mode & R_BORDER) {
2103                 disprect.xmin = scene->r.border.xmin * winx;
2104                 disprect.xmax = scene->r.border.xmax * winx;
2105                 
2106                 disprect.ymin = scene->r.border.ymin * winy;
2107                 disprect.ymax = scene->r.border.ymax * winy;
2108         }
2109         else {
2110                 disprect.xmin = disprect.ymin = 0;
2111                 disprect.xmax = winx;
2112                 disprect.ymax = winy;
2113         }
2114         
2115         re->main = bmain;
2116         re->scene = scene;
2117         re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
2118         re->camera_override = camera_override;
2119         re->lay = lay;
2120         
2121         /* not too nice, but it survives anim-border render */
2122         if (anim) {
2123                 re->disprect = disprect;
2124                 return 1;
2125         }
2126         
2127         /* check all scenes involved */
2128         tag_scenes_for_render(re);
2129
2130         /*
2131          * Disabled completely for now,
2132          * can be later set as render profile option
2133          * and default for background render.
2134          */
2135         if (0) {
2136                 /* make sure dynamics are up to date */
2137                 update_physics_cache(re, scene, anim_init);
2138         }
2139         
2140         if (srl || scene->r.scemode & R_SINGLE_LAYER) {
2141                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2142                 render_result_single_layer_begin(re);
2143                 BLI_rw_mutex_unlock(&re->resultmutex);
2144         }
2145         
2146         RE_InitState(re, NULL, &scene->r, srl, winx, winy, &disprect);
2147         if (!re->ok)  /* if an error was printed, abort */
2148                 return 0;
2149         
2150         /* initstate makes new result, have to send changed tags around */
2151         ntreeCompositTagRender(re->scene);
2152
2153         validate_render_settings(re);
2154
2155         re->display_init(re->dih, re->result);
2156         re->display_clear(re->dch, re->result);
2157         
2158         return 1;
2159 }
2160
2161 void RE_SetReports(Render *re, ReportList *reports)
2162 {
2163         re->reports = reports;
2164 }
2165
2166 /* general Blender frame render call */
2167 void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int frame, const short write_still)
2168 {
2169         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2170         G.is_rendering = TRUE;
2171         
2172         scene->r.cfra = frame;
2173         
2174         if (render_initialize_from_main(re, bmain, scene, srl, camera_override, lay, 0, 0)) {
2175                 MEM_reset_peak_memory();
2176
2177                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2178
2179                 do_render_all_options(re);
2180                 
2181                 if (write_still && !G.is_break) {
2182                         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2183                                 /* operator checks this but in case its called from elsewhere */
2184                                 printf("Error: cant write single images with a movie format!\n");
2185                         }
2186                         else {
2187                                 char name[FILE_MAX];
2188                                 BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, FALSE);
2189
2190                                 /* reports only used for Movie */
2191                                 do_write_image_or_movie(re, bmain, scene, NULL, name);
2192                         }
2193                 }
2194
2195                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2196         }
2197
2198         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2199
2200         /* UGLY WARNING */
2201         G.is_rendering = FALSE;
2202 }
2203
2204 void RE_RenderFreestyleStrokes(Render *re, Main *bmain, Scene *scene)
2205 {
2206         re->result_ok= 0;
2207         if(render_initialize_from_main(re, bmain, scene, NULL, NULL, scene->lay, 0, 0)) {
2208                 do_render_fields_blur_3d(re);
2209         }
2210         re->result_ok= 1;
2211 }
2212
2213 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override)
2214 {
2215         char name[FILE_MAX];
2216         RenderResult rres;
2217         Object *camera = RE_GetCamera(re);
2218         int ok = 1;
2219         
2220         RE_AcquireResultImage(re, &rres);
2221
2222         /* write movie or image */
2223         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2224                 int do_free = FALSE;
2225                 ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
2226
2227                 /* note; the way it gets 32 bits rects is weak... */
2228                 if (ibuf->rect == NULL) {
2229                         ibuf->rect = MEM_mapallocN(sizeof(int) * rres.rectx * rres.recty, "temp 32 bits rect");
2230                         ibuf->mall |= IB_rect;
2231                         RE_ResultGet32(re, ibuf->rect);
2232                         do_free = TRUE;
2233                 }
2234
2235
2236                 IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2237                                                     &scene->display_settings, &scene->r.im_format);
2238
2239                 ok = mh->append_movie(&re->r, scene->r.sfra, scene->r.cfra, (int *) ibuf->rect,
2240                                       ibuf->x, ibuf->y, re->reports);
2241                 if (do_free) {
2242                         MEM_freeN(ibuf->rect);
2243                         ibuf->rect = NULL;
2244                         ibuf->mall &= ~IB_rect;
2245                 }
2246
2247                 /* imbuf knows which rects are not part of ibuf */
2248                 IMB_freeImBuf(ibuf);
2249
2250                 printf("Append frame %d", scene->r.cfra);
2251         }
2252         else {
2253                 if (name_override)
2254                         BLI_strncpy(name, name_override, sizeof(name));
2255                 else
2256                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, TRUE);
2257                 
2258                 if (re->r.im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
2259                         if (re->result) {
2260                                 RE_WriteRenderResult(re->reports, re->result, name, scene->r.im_format.exr_codec);
2261                                 printf("Saved: %s", name);
2262                         }
2263                 }
2264                 else {
2265                         ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
2266
2267                         IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2268                                                             &scene->display_settings, &scene->r.im_format);
2269
2270                         ok = BKE_imbuf_write_stamp(scene, camera, ibuf, name, &scene->r.im_format);
2271                         
2272                         if (ok == 0) {
2273                                 printf("Render error: cannot save %s\n", name);
2274                         }
2275                         else printf("Saved: %s", name);
2276                         
2277                         /* optional preview images for exr */
2278                         if (ok && scene->r.im_format.imtype == R_IMF_IMTYPE_OPENEXR && (scene->r.im_format.flag & R_IMF_FLAG_PREVIEW_JPG)) {
2279                                 ImageFormatData imf = scene->r.im_format;
2280                                 imf.imtype = R_IMF_IMTYPE_JPEG90;
2281
2282                                 if (BLI_testextensie(name, ".exr"))
2283                                         name[strlen(name) - 4] = 0;
2284                                 BKE_add_image_extension(name, R_IMF_IMTYPE_JPEG90);
2285                                 ibuf->planes = 24;
2286
2287                                 IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings,
2288                                                                     &scene->display_settings, &imf);
2289
2290                                 BKE_imbuf_write_stamp(scene, camera, ibuf, name, &imf);
2291                                 printf("\nSaved: %s", name);
2292                         }
2293                         
2294                         /* imbuf knows which rects are not part of ibuf */
2295                         IMB_freeImBuf(ibuf);
2296                 }
2297         }
2298         
2299         RE_ReleaseResultImage(re);
2300
2301         BLI_timestr(re->i.lastframetime, name);
2302         printf(" Time: %s", name);
2303
2304         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
2305
2306         fputc('\n', stdout);
2307         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2308
2309         return ok;
2310 }
2311
2312 /* saves images to disk */
2313 void RE_BlenderAnim(Render *re, Main *bmain, Scene *scene, Object *camera_override, unsigned int lay, int sfra, int efra, int tfra)
2314 {
2315         bMovieHandle *mh = BKE_movie_handle_get(scene->r.im_format.imtype);
2316         int cfrao = scene->r.cfra;
2317         int nfra, totrendered = 0, totskipped = 0;
2318         
2319         /* do not fully call for each frame, it initializes & pops output window */
2320         if (!render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 0, 1))
2321                 return;
2322         
2323         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2324         /* is also set by caller renderwin.c */
2325         G.is_rendering = TRUE;
2326
2327         re->flag |= R_ANIMATION;
2328
2329         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2330                 if (!mh->start_movie(scene, &re->r, re->rectx, re->recty, re->reports))
2331                         G.is_break = TRUE;
2332
2333         if (mh->get_next_frame) {
2334                 while (!(G.is_break == 1)) {
2335                         int nf = mh->get_next_frame(&re->r, re->reports);
2336                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2337                                 scene->r.cfra = re->r.cfra = nf;
2338
2339                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2340
2341                                 do_render_all_options(re);
2342                                 totrendered++;
2343
2344                                 if (re->test_break(re->tbh) == 0) {
2345                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2346                                                 G.is_break = TRUE;
2347                                 }
2348
2349                                 if (G.is_break == FALSE) {
2350                                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2351                                 }
2352                         }
2353                         else {
2354                                 if (re->test_break(re->tbh)) {
2355                                         G.is_break = TRUE;
2356                                 }
2357                         }
2358                 }
2359         }
2360         else {
2361                 for (nfra = sfra, scene->r.cfra = sfra; scene->r.cfra <= efra; scene->r.cfra++) {
2362                         char name[FILE_MAX];
2363                         
2364                         /* only border now, todo: camera lens. (ton) */
2365                         render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 1, 0);
2366
2367                         if (nfra != scene->r.cfra) {
2368                                 /*
2369                                  * Skip this frame, but update for physics and particles system.
2370                                  * From convertblender.c:
2371                                  * in localview, lamps are using normal layers, objects only local bits.
2372                                  */
2373                                 unsigned int updatelay;
2374
2375                                 if (re->lay & 0xFF000000)
2376                                         updatelay = re->lay & 0xFF000000;
2377                                 else
2378                                         updatelay = re->lay;
2379
2380                                 BKE_scene_update_for_newframe(bmain, scene, updatelay);
2381                                 continue;
2382                         }
2383                         else
2384                                 nfra += tfra;
2385
2386                         /* Touch/NoOverwrite options are only valid for image's */
2387                         if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2388                                 if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2389                                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, TRUE);
2390
2391                                 if (scene->r.mode & R_NO_OVERWRITE && BLI_exists(name)) {
2392                                         printf("skipping existing frame \"%s\"\n", name);
2393                                         totskipped++;
2394                                         continue;
2395                                 }
2396                                 if (scene->r.mode & R_TOUCH && !BLI_exists(name)) {
2397                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2398                                         BLI_file_touch(name);
2399                                 }
2400                         }
2401
2402                         re->r.cfra = scene->r.cfra;     /* weak.... */
2403
2404                         /* run callbacs before rendering, before the scene is updated */
2405                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2406
2407                         
2408                         do_render_all_options(re);
2409                         totrendered++;
2410                         
2411                         if (re->test_break(re->tbh) == 0) {
2412                                 if (!G.is_break)
2413                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2414                                                 G.is_break = TRUE;
2415                         }
2416                         else
2417                                 G.is_break = TRUE;
2418                 
2419                         if (G.is_break == TRUE) {
2420                                 /* remove touched file */
2421                                 if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2422                                         if (scene->r.mode & R_TOUCH && BLI_exists(name) && BLI_file_size(name) == 0) {
2423                                                 BLI_delete(name, 0, 0);
2424                                         }
2425                                 }
2426                                 
2427                                 break;
2428                         }
2429
2430                         if (G.is_break == FALSE) {
2431                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2432                         }
2433                 }
2434         }
2435         
2436         /* end movie */
2437         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2438                 mh->end_movie();
2439         
2440         if (totskipped && totrendered == 0)
2441                 BKE_report(re->reports, RPT_INFO, "No frames rendered, skipped to not overwrite");
2442
2443         scene->r.cfra = cfrao;
2444
2445         re->flag &= ~R_ANIMATION;
2446
2447         BLI_callback_exec(re->main, (ID *)scene, G.is_break ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2448
2449         /* UGLY WARNING */
2450         G.is_rendering = FALSE;
2451 }
2452
2453 void RE_PreviewRender(Render *re, Main *bmain, Scene *sce)
2454 {
2455         Object *camera;
2456         int winx, winy;
2457
2458         winx = (sce->r.size * sce->r.xsch) / 100;
2459         winy = (sce->r.size * sce->r.ysch) / 100;
2460
2461         RE_InitState(re, NULL, &sce->r, NULL, winx, winy, NULL);
2462
2463         re->main = bmain;
2464         re->scene = sce;
2465         re->scene_color_manage = BKE_scene_check_color_management_enabled(sce);
2466         re->lay = sce->lay;
2467
2468         camera = RE_GetCamera(re);
2469         RE_SetCamera(re, camera);
2470
2471         do_render_3d(re);
2472 }
2473
2474 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2475
2476 /* only the temp file! */
2477 int RE_ReadRenderResult(Scene *scene, Scene *scenode)
2478 {
2479         Render *re;
2480         int winx, winy, success;
2481         rcti disprect;
2482         
2483         /* calculate actual render result and display size */
2484         winx = (scene->r.size * scene->r.xsch) / 100;
2485         winy = (scene->r.size * scene->r.ysch) / 100;
2486         
2487         /* only in movie case we render smaller part */
2488         if (scene->r.mode & R_BORDER) {
2489                 disprect.xmin = scene->r.border.xmin * winx;
2490                 disprect.xmax = scene->r.border.xmax * winx;
2491                 
2492                 disprect.ymin = scene->r.border.ymin * winy;
2493                 disprect.ymax = scene->r.border.ymax * winy;
2494         }
2495         else {
2496                 disprect.xmin = disprect.ymin = 0;
2497                 disprect.xmax = winx;
2498                 disprect.ymax = winy;
2499         }
2500         
2501         if (scenode)
2502                 scene = scenode;
2503         
2504         /* get render: it can be called from UI with draw callbacks */
2505         re = RE_GetRender(scene->id.name);
2506         if (re == NULL)
2507                 re = RE_NewRender(scene->id.name);
2508         RE_InitState(re, NULL, &scene->r, NULL, winx, winy, &disprect);
2509         re->scene = scene;
2510         re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
2511         
2512         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2513         success = render_result_exr_file_read(re, 0);
2514         BLI_rw_mutex_unlock(&re->resultmutex);
2515
2516         return success;
2517 }
2518
2519 void RE_set_max_threads(int threads)
2520 {
2521         if (threads == 0) {
2522                 RenderGlobal.threads = BLI_system_thread_count();
2523         }
2524         else if (threads >= 1 && threads <= BLENDER_MAX_THREADS) {
2525                 RenderGlobal.threads = threads;
2526         }
2527         else {
2528                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2529         }
2530 }
2531
2532 void RE_init_threadcount(Render *re) 
2533 {
2534         if (RenderGlobal.threads >= 1) { /* only set as an arg in background mode */
2535                 re->r.threads = MIN2(RenderGlobal.threads, BLENDER_MAX_THREADS);
2536         }
2537         else if ((re->r.mode & R_FIXED_THREADS) == 0 || RenderGlobal.threads == 0) { /* Automatic threads */
2538                 re->r.threads = BLI_system_thread_count();
2539         }
2540 }
2541
2542 /* loads in image into a result, size must match
2543  * x/y offsets are only used on a partial copy when dimensions don't match */
2544 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, const char *filename, int x, int y)
2545 {
2546         /* OCIO_TODO: assume layer was saved in defaule color space */
2547         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect, NULL);
2548
2549         if (ibuf && (ibuf->rect || ibuf->rect_float)) {
2550                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
2551                         if (ibuf->rect_float == NULL)
2552                                 IMB_float_from_rect(ibuf);
2553
2554                         memcpy(layer->rectf, ibuf->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2555                 }
2556                 else {
2557                         if ((ibuf->x - x >= layer->rectx) && (ibuf->y - y >= layer->recty)) {
2558                                 ImBuf *ibuf_clip;
2559
2560                                 if (ibuf->rect_float == NULL)
2561                                         IMB_float_from_rect(ibuf);
2562
2563                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat);
2564                                 if (ibuf_clip) {
2565                                         IMB_rectcpy(ibuf_clip, ibuf, 0, 0, x, y, layer->rectx, layer->recty);
2566
2567                                         memcpy(layer->rectf, ibuf_clip->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2568                                         IMB_freeImBuf(ibuf_clip);
2569                                 }
2570                                 else {
2571                                         BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'", filename);
2572                                 }
2573                         }
2574                         else {
2575                                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'", filename);
2576                         }
2577                 }
2578
2579                 IMB_freeImBuf(ibuf);
2580         }
2581         else {
2582                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
2583         }
2584 }
2585
2586 void RE_result_load_from_file(RenderResult *result, ReportList *reports, const char *filename)
2587 {
2588         if (!render_result_exr_file_read_path(result, NULL, filename)) {
2589                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'", filename);
2590                 return;
2591         }
2592 }
2593
2594 const float default_envmap_layout[] = { 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1 };
2595
2596 int RE_WriteEnvmapResult(struct ReportList *reports, Scene *scene, EnvMap *env, const char *relpath, const char imtype, float layout[12])
2597 {
2598         ImageFormatData imf;
2599         ImBuf *ibuf = NULL;
2600         int ok;
2601         int dx;
2602         int maxX = 0, maxY = 0, i = 0;
2603         char filepath[FILE_MAX];
2604
2605         if (env->cube[1] == NULL) {
2606                 BKE_report(reports, RPT_ERROR, "There is no generated environment map available to save");
2607                 return 0;
2608         }
2609
2610         imf = scene->r.im_format;
2611         imf.imtype = imtype;
2612
2613         dx = env->cube[1]->x;
2614
2615         if (env->type == ENV_CUBE) {
2616                 for (i = 0; i < 12; i += 2) {
2617                         maxX = max_ii(maxX, (int)layout[i] + 1);
2618                         maxY = max_ii(maxY, (int)layout[i + 1] + 1);
2619                 }
2620
2621                 ibuf = IMB_allocImBuf(maxX * dx, maxY * dx, 24, IB_rectfloat);
2622
2623                 for (i = 0; i < 12; i += 2)
2624                         if (layout[i] > -1 && layout[i + 1] > -1)
2625                                 IMB_rectcpy(ibuf, env->cube[i / 2], layout[i] * dx, layout[i + 1] * dx, 0, 0, dx, dx);
2626         }
2627         else if (env->type == ENV_PLANE) {
2628                 ibuf = IMB_allocImBuf(dx, dx, 24, IB_rectfloat);
2629                 IMB_rectcpy(ibuf, env->cube[1], 0, 0, 0, 0, dx, dx);
2630         }
2631         else {
2632                 BKE_report(reports, RPT_ERROR, "Invalid environment map type");
2633                 return 0;
2634         }
2635
2636         IMB_colormanagement_imbuf_for_write(ibuf, TRUE, FALSE, &scene->view_settings, &scene->display_settings, &imf);
2637
2638         /* to save, we first get absolute path */
2639         BLI_strncpy(filepath, relpath, sizeof(filepath));
2640         BLI_path_abs(filepath, G.main->name);
2641
2642         ok = BKE_imbuf_write(ibuf, filepath, &imf);
2643
2644         IMB_freeImBuf(ibuf);
2645
2646         if (ok) {
2647                 return TRUE;
2648         }
2649         else {
2650                 BKE_report(reports, RPT_ERROR, "Error writing environment map");
2651                 return FALSE;
2652         }
2653 }
2654