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