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