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