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