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