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