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