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