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