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