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