Merged changes in the trunk up to revision 39896.
[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_global.h"
52 #include "BKE_image.h"
53 #include "BKE_library.h"
54 #include "BKE_main.h"
55 #include "BKE_node.h"
56 #include "BKE_object.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_blenlib.h"
66 #include "BLI_rand.h"
67 #include "BLI_threads.h"
68 #include "BLI_callbacks.h"
69 #include "BLI_utildefines.h"
70
71 #include "PIL_time.h"
72 #include "IMB_imbuf.h"
73 #include "IMB_imbuf_types.h"
74
75 #include "intern/openexr/openexr_multi.h"
76
77 #include "RE_pipeline.h"
78
79 #include "FRS_freestyle.h"
80 #include "FRS_freestyle_config.h"
81
82 /* internal */
83 #include "render_types.h"
84 #include "renderpipeline.h"
85 #include "renderdatabase.h"
86 #include "rendercore.h"
87 #include "envmap.h"
88 #include "initrender.h"
89 #include "shadbuf.h"
90 #include "pixelblending.h"
91 #include "zbuf.h"
92
93
94 /* render flow
95
96 1) Initialize state
97 - state data, tables
98 - movie/image file init
99 - everything that doesn't change during animation
100
101 2) Initialize data
102 - camera, world, matrices
103 - make render verts, faces, halos, strands
104 - everything can change per frame/field
105
106 3) Render Processor
107 - multiple layers
108 - tiles, rect, baking
109 - layers/tiles optionally to disk or directly in Render Result
110
111 4) Composite Render Result
112 - also read external files etc
113
114 5) Image Files
115 - save file or append in movie
116
117 */
118
119
120 /* ********* globals ******** */
121
122 /* here we store all renders */
123 static struct {
124         ListBase renderlist;
125
126         /* commandline thread override */
127         int threads;
128 } RenderGlobal = {{NULL, NULL}, -1}; 
129
130 /* hardcopy of current render, used while rendering for speed */
131 Render R;
132
133 /* ********* alloc and free ******** */
134
135 static int do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh, const char *name_override);
136
137 static volatile int g_break= 0;
138 static int thread_break(void *UNUSED(arg))
139 {
140         return g_break;
141 }
142
143 /* default callbacks, set in each new render */
144 static void result_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr)) {}
145 static void result_rcti_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect)) {}
146 static void stats_nothing(void *UNUSED(arg), RenderStats *UNUSED(rs)) {}
147 static void float_nothing(void *UNUSED(arg), float UNUSED(val)) {}
148 static int default_break(void *UNUSED(arg)) {return G.afbreek == 1;}
149
150 static void stats_background(void *UNUSED(arg), RenderStats *rs)
151 {
152         uintptr_t mem_in_use, mmap_in_use, peak_memory;
153         float megs_used_memory, mmap_used_memory, megs_peak_memory;
154
155         mem_in_use= MEM_get_memory_in_use();
156         mmap_in_use= MEM_get_mapped_memory_in_use();
157         peak_memory = MEM_get_peak_memory();
158
159         megs_used_memory= (mem_in_use-mmap_in_use)/(1024.0*1024.0);
160         mmap_used_memory= (mmap_in_use)/(1024.0*1024.0);
161         megs_peak_memory = (peak_memory)/(1024.0*1024.0);
162
163         fprintf(stdout, "Fra:%d Mem:%.2fM (%.2fM, peak %.2fM) ", rs->cfra,
164                                    megs_used_memory, mmap_used_memory, megs_peak_memory);
165
166         if(rs->curfield)
167                 fprintf(stdout, "Field %d ", rs->curfield);
168         if(rs->curblur)
169                 fprintf(stdout, "Blur %d ", rs->curblur);
170
171         if(rs->infostr) {
172                 fprintf(stdout, "| %s", rs->infostr);
173         }
174         else {
175                 if(rs->tothalo)
176                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", rs->scenename, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
177                 else
178                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d La:%d", rs->scenename, rs->totvert, rs->totface, rs->totlamp);
179         }
180
181         BLI_exec_cb(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
182
183         fputc('\n', stdout);
184         fflush(stdout);
185 }
186
187 void RE_FreeRenderResult(RenderResult *res)
188 {
189         if(res==NULL) return;
190
191         while(res->layers.first) {
192                 RenderLayer *rl= res->layers.first;
193                 
194                 if(rl->rectf) MEM_freeN(rl->rectf);
195                 /* acolrect and scolrect are optionally allocated in shade_tile, only free here since it can be used for drawing */
196                 if(rl->acolrect) MEM_freeN(rl->acolrect);
197                 if(rl->scolrect) MEM_freeN(rl->scolrect);
198                 
199                 while(rl->passes.first) {
200                         RenderPass *rpass= rl->passes.first;
201                         if(rpass->rect) MEM_freeN(rpass->rect);
202                         BLI_remlink(&rl->passes, rpass);
203                         MEM_freeN(rpass);
204                 }
205                 BLI_remlink(&res->layers, rl);
206                 MEM_freeN(rl);
207         }
208         
209         if(res->rect32)
210                 MEM_freeN(res->rect32);
211         if(res->rectz)
212                 MEM_freeN(res->rectz);
213         if(res->rectf)
214                 MEM_freeN(res->rectf);
215         if(res->text)
216                 MEM_freeN(res->text);
217         
218         MEM_freeN(res);
219 }
220
221 /* version that's compatible with fullsample buffers */
222 static void free_render_result(ListBase *lb, RenderResult *rr)
223 {
224         RenderResult *rrnext;
225         
226         for(; rr; rr= rrnext) {
227                 rrnext= rr->next;
228                 
229                 if(lb && lb->first)
230                         BLI_remlink(lb, rr);
231                 
232                 RE_FreeRenderResult(rr);
233         }
234 }
235
236
237 /* all layers except the active one get temporally pushed away */
238 static void push_render_result(Render *re)
239 {
240         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
241
242         /* officially pushed result should be NULL... error can happen with do_seq */
243         RE_FreeRenderResult(re->pushedresult);
244         
245         re->pushedresult= re->result;
246         re->result= NULL;
247
248         BLI_rw_mutex_unlock(&re->resultmutex);
249 }
250
251 /* if scemode is R_SINGLE_LAYER, at end of rendering, merge the both render results */
252 static void pop_render_result(Render *re)
253 {
254         if(re->result==NULL) {
255                 printf("pop render result error; no current result!\n");
256                 return;
257         }
258
259         if(re->pushedresult) {
260                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
261
262                 if(re->pushedresult->rectx==re->result->rectx && re->pushedresult->recty==re->result->recty) {
263                         /* find which layer in pushedresult should be replaced */
264                         SceneRenderLayer *srl;
265                         RenderLayer *rlpush;
266                         RenderLayer *rl= re->result->layers.first;
267                         int nr;
268                         
269                         /* render result should be empty after this */
270                         BLI_remlink(&re->result->layers, rl);
271                         
272                         /* reconstruct render result layers */
273                         for(nr=0, srl= re->scene->r.layers.first; srl; srl= srl->next, nr++) {
274                                 if(nr==re->r.actlay)
275                                         BLI_addtail(&re->result->layers, rl);
276                                 else {
277                                         rlpush= RE_GetRenderLayer(re->pushedresult, srl->name);
278                                         if(rlpush) {
279                                                 BLI_remlink(&re->pushedresult->layers, rlpush);
280                                                 BLI_addtail(&re->result->layers, rlpush);
281                                         }
282                                 }
283                         }
284                 }
285                 
286                 RE_FreeRenderResult(re->pushedresult);
287                 re->pushedresult= NULL;
288
289                 BLI_rw_mutex_unlock(&re->resultmutex);
290         }
291 }
292
293 /* NOTE: OpenEXR only supports 32 chars for layer+pass names
294    In blender we now use max 10 chars for pass, max 20 for layer */
295 static const char *get_pass_name(int passtype, int channel)
296 {
297         
298         if(passtype == SCE_PASS_COMBINED) {
299                 if(channel==-1) return "Combined";
300                 if(channel==0) return "Combined.R";
301                 if(channel==1) return "Combined.G";
302                 if(channel==2) return "Combined.B";
303                 return "Combined.A";
304         }
305         if(passtype == SCE_PASS_Z) {
306                 if(channel==-1) return "Depth";
307                 return "Depth.Z";
308         }
309         if(passtype == SCE_PASS_VECTOR) {
310                 if(channel==-1) return "Vector";
311                 if(channel==0) return "Vector.X";
312                 if(channel==1) return "Vector.Y";
313                 if(channel==2) return "Vector.Z";
314                 return "Vector.W";
315         }
316         if(passtype == SCE_PASS_NORMAL) {
317                 if(channel==-1) return "Normal";
318                 if(channel==0) return "Normal.X";
319                 if(channel==1) return "Normal.Y";
320                 return "Normal.Z";
321         }
322         if(passtype == SCE_PASS_UV) {
323                 if(channel==-1) return "UV";
324                 if(channel==0) return "UV.U";
325                 if(channel==1) return "UV.V";
326                 return "UV.A";
327         }
328         if(passtype == SCE_PASS_RGBA) {
329                 if(channel==-1) return "Color";
330                 if(channel==0) return "Color.R";
331                 if(channel==1) return "Color.G";
332                 if(channel==2) return "Color.B";
333                 return "Color.A";
334         }
335         if(passtype == SCE_PASS_EMIT) {
336                 if(channel==-1) return "Emit";
337                 if(channel==0) return "Emit.R";
338                 if(channel==1) return "Emit.G";
339                 return "Emit.B";
340         }
341         if(passtype == SCE_PASS_DIFFUSE) {
342                 if(channel==-1) return "Diffuse";
343                 if(channel==0) return "Diffuse.R";
344                 if(channel==1) return "Diffuse.G";
345                 return "Diffuse.B";
346         }
347         if(passtype == SCE_PASS_SPEC) {
348                 if(channel==-1) return "Spec";
349                 if(channel==0) return "Spec.R";
350                 if(channel==1) return "Spec.G";
351                 return "Spec.B";
352         }
353         if(passtype == SCE_PASS_SHADOW) {
354                 if(channel==-1) return "Shadow";
355                 if(channel==0) return "Shadow.R";
356                 if(channel==1) return "Shadow.G";
357                 return "Shadow.B";
358         }
359         if(passtype == SCE_PASS_AO) {
360                 if(channel==-1) return "AO";
361                 if(channel==0) return "AO.R";
362                 if(channel==1) return "AO.G";
363                 return "AO.B";
364         }
365         if(passtype == SCE_PASS_ENVIRONMENT) {
366                 if(channel==-1) return "Env";
367                 if(channel==0) return "Env.R";
368                 if(channel==1) return "Env.G";
369                 return "Env.B";
370         }
371         if(passtype == SCE_PASS_INDIRECT) {
372                 if(channel==-1) return "Indirect";
373                 if(channel==0) return "Indirect.R";
374                 if(channel==1) return "Indirect.G";
375                 return "Indirect.B";
376         }
377         if(passtype == SCE_PASS_REFLECT) {
378                 if(channel==-1) return "Reflect";
379                 if(channel==0) return "Reflect.R";
380                 if(channel==1) return "Reflect.G";
381                 return "Reflect.B";
382         }
383         if(passtype == SCE_PASS_REFRACT) {
384                 if(channel==-1) return "Refract";
385                 if(channel==0) return "Refract.R";
386                 if(channel==1) return "Refract.G";
387                 return "Refract.B";
388         }
389         if(passtype == SCE_PASS_INDEXOB) {
390                 if(channel==-1) return "IndexOB";
391                 return "IndexOB.X";
392         }
393         if(passtype == SCE_PASS_INDEXMA) {
394                 if(channel==-1) return "IndexMA";
395                 return "IndexMA.X";
396         }
397         if(passtype == SCE_PASS_MIST) {
398                 if(channel==-1) return "Mist";
399                 return "Mist.Z";
400         }
401         if(passtype == SCE_PASS_RAYHITS)
402         {
403                 if(channel==-1) return "Rayhits";
404                 if(channel==0) return "Rayhits.R";
405                 if(channel==1) return "Rayhits.G";
406                 return "Rayhits.B";
407         }
408         return "Unknown";
409 }
410
411 static int passtype_from_name(char *str)
412 {
413         
414         if(strcmp(str, "Combined")==0)
415                 return SCE_PASS_COMBINED;
416
417         if(strcmp(str, "Depth")==0)
418                 return SCE_PASS_Z;
419
420         if(strcmp(str, "Vector")==0)
421                 return SCE_PASS_VECTOR;
422
423         if(strcmp(str, "Normal")==0)
424                 return SCE_PASS_NORMAL;
425
426         if(strcmp(str, "UV")==0)
427                 return SCE_PASS_UV;
428
429         if(strcmp(str, "Color")==0)
430                 return SCE_PASS_RGBA;
431
432         if(strcmp(str, "Emit")==0)
433                 return SCE_PASS_EMIT;
434
435         if(strcmp(str, "Diffuse")==0)
436                 return SCE_PASS_DIFFUSE;
437
438         if(strcmp(str, "Spec")==0)
439                 return SCE_PASS_SPEC;
440
441         if(strcmp(str, "Shadow")==0)
442                 return SCE_PASS_SHADOW;
443         
444         if(strcmp(str, "AO")==0)
445                 return SCE_PASS_AO;
446
447         if(strcmp(str, "Env")==0)
448                 return SCE_PASS_ENVIRONMENT;
449
450         if(strcmp(str, "Indirect")==0)
451                 return SCE_PASS_INDIRECT;
452
453         if(strcmp(str, "Reflect")==0)
454                 return SCE_PASS_REFLECT;
455
456         if(strcmp(str, "Refract")==0)
457                 return SCE_PASS_REFRACT;
458
459         if(strcmp(str, "IndexOB")==0)
460                 return SCE_PASS_INDEXOB;
461
462         if(strcmp(str, "IndexMA")==0)
463                 return SCE_PASS_INDEXMA;
464
465         if(strcmp(str, "Mist")==0)
466                 return SCE_PASS_MIST;
467         
468         if(strcmp(str, "RayHits")==0)
469                 return SCE_PASS_RAYHITS;
470         return 0;
471 }
472
473 static void scene_unique_exr_name(Scene *scene, char *str, int sample)
474 {
475         char di[FILE_MAX], name[FILE_MAXFILE+MAX_ID_NAME+100], fi[FILE_MAXFILE];
476         
477         BLI_strncpy(di, G.main->name, FILE_MAX);
478         BLI_splitdirstring(di, fi);
479         
480         if(sample==0)
481                 BLI_snprintf(name, sizeof(name), "%s_%s.exr", fi, scene->id.name+2);
482         else
483                 BLI_snprintf(name, sizeof(name), "%s_%s%d.exr", fi, scene->id.name+2, sample);
484
485         BLI_make_file_string("/", str, btempdir, name);
486 }
487
488 static void render_unique_exr_name(Render *re, char *str, int sample)
489 {
490         scene_unique_exr_name(re->scene, str, sample);
491 }
492
493 static void render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, int passtype)
494 {
495         const char *typestr= get_pass_name(passtype, 0);
496         RenderPass *rpass= MEM_callocN(sizeof(RenderPass), typestr);
497         int rectsize= rr->rectx*rr->recty*channels;
498         
499         BLI_addtail(&rl->passes, rpass);
500         rpass->passtype= passtype;
501         rpass->channels= channels;
502         rpass->rectx= rl->rectx;
503         rpass->recty= rl->recty;
504         
505         if(rr->exrhandle) {
506                 int a;
507                 for(a=0; a<channels; a++)
508                         IMB_exr_add_channel(rr->exrhandle, rl->name, get_pass_name(passtype, a), 0, 0, NULL);
509         }
510         else {
511                 float *rect;
512                 int x;
513                 
514                 rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
515                 
516                 if(passtype==SCE_PASS_VECTOR) {
517                         /* initialize to max speed */
518                         rect= rpass->rect;
519                         for(x= rectsize-1; x>=0; x--)
520                                 rect[x]= PASS_VECTOR_MAX;
521                 }
522                 else if(passtype==SCE_PASS_Z) {
523                         rect= rpass->rect;
524                         for(x= rectsize-1; x>=0; x--)
525                                 rect[x]= 10e10;
526                 }
527         }
528 }
529
530 float *RE_RenderLayerGetPass(RenderLayer *rl, int passtype)
531 {
532         RenderPass *rpass;
533         
534         for(rpass=rl->passes.first; rpass; rpass= rpass->next)
535                 if(rpass->passtype== passtype)
536                         return rpass->rect;
537         return NULL;
538 }
539
540 RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
541 {
542         RenderLayer *rl;
543         
544         if(rr==NULL) return NULL;
545         
546         for(rl= rr->layers.first; rl; rl= rl->next)
547                 if(strncmp(rl->name, name, RE_MAXNAME)==0)
548                         return rl;
549         return NULL;
550 }
551
552 #define RR_USEMEM       0
553 /* called by main render as well for parts */
554 /* will read info from Render *re to define layers */
555 /* called in threads */
556 /* re->winx,winy is coordinate space of entire image, partrct the part within */
557 static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int savebuffers)
558 {
559         RenderResult *rr;
560         RenderLayer *rl;
561         SceneRenderLayer *srl;
562         int rectx, recty, nr;
563         
564         rectx= partrct->xmax - partrct->xmin;
565         recty= partrct->ymax - partrct->ymin;
566         
567         if(rectx<=0 || recty<=0)
568                 return NULL;
569         
570         rr= MEM_callocN(sizeof(RenderResult), "new render result");
571         rr->rectx= rectx;
572         rr->recty= recty;
573         rr->renrect.xmin= 0; rr->renrect.xmax= rectx-2*crop;
574         /* crop is one or two extra pixels rendered for filtering, is used for merging and display too */
575         rr->crop= crop;
576         
577         /* tilerect is relative coordinates within render disprect. do not subtract crop yet */
578         rr->tilerect.xmin= partrct->xmin - re->disprect.xmin;
579         rr->tilerect.xmax= partrct->xmax - re->disprect.xmax;
580         rr->tilerect.ymin= partrct->ymin - re->disprect.ymin;
581         rr->tilerect.ymax= partrct->ymax - re->disprect.ymax;
582         
583         if(savebuffers) {
584                 rr->exrhandle= IMB_exr_get_handle();
585         }
586         
587         /* check renderdata for amount of layers */
588         for(nr=0, srl= re->r.layers.first; srl; srl= srl->next, nr++) {
589                 
590                 if((re->r.scemode & R_SINGLE_LAYER) && nr!=re->r.actlay)
591                         continue;
592                 if(srl->layflag & SCE_LAY_DISABLE)
593                         continue;
594                 
595                 rl= MEM_callocN(sizeof(RenderLayer), "new render layer");
596                 BLI_addtail(&rr->layers, rl);
597                 
598                 BLI_strncpy(rl->name, srl->name, sizeof(rl->name));
599                 rl->lay= srl->lay;
600                 rl->lay_zmask= srl->lay_zmask;
601                 rl->layflag= srl->layflag;
602                 rl->passflag= srl->passflag; // for debugging: srl->passflag|SCE_PASS_RAYHITS;
603                 rl->pass_xor= srl->pass_xor;
604                 rl->light_override= srl->light_override;
605                 rl->mat_override= srl->mat_override;
606                 rl->rectx= rectx;
607                 rl->recty= recty;
608                 
609                 if(rr->exrhandle) {
610                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.R", 0, 0, NULL);
611                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.G", 0, 0, NULL);
612                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.B", 0, 0, NULL);
613                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.A", 0, 0, NULL);
614                 }
615                 else
616                         rl->rectf= MEM_mapallocN(rectx*recty*sizeof(float)*4, "Combined rgba");
617                 
618                 if(srl->passflag  & SCE_PASS_Z)
619                         render_layer_add_pass(rr, rl, 1, SCE_PASS_Z);
620                 if(srl->passflag  & SCE_PASS_VECTOR)
621                         render_layer_add_pass(rr, rl, 4, SCE_PASS_VECTOR);
622                 if(srl->passflag  & SCE_PASS_NORMAL)
623                         render_layer_add_pass(rr, rl, 3, SCE_PASS_NORMAL);
624                 if(srl->passflag  & SCE_PASS_UV) 
625                         render_layer_add_pass(rr, rl, 3, SCE_PASS_UV);
626                 if(srl->passflag  & SCE_PASS_RGBA)
627                         render_layer_add_pass(rr, rl, 4, SCE_PASS_RGBA);
628                 if(srl->passflag  & SCE_PASS_EMIT)
629                         render_layer_add_pass(rr, rl, 3, SCE_PASS_EMIT);
630                 if(srl->passflag  & SCE_PASS_DIFFUSE)
631                         render_layer_add_pass(rr, rl, 3, SCE_PASS_DIFFUSE);
632                 if(srl->passflag  & SCE_PASS_SPEC)
633                         render_layer_add_pass(rr, rl, 3, SCE_PASS_SPEC);
634                 if(srl->passflag  & SCE_PASS_AO)
635                         render_layer_add_pass(rr, rl, 3, SCE_PASS_AO);
636                 if(srl->passflag  & SCE_PASS_ENVIRONMENT)
637                         render_layer_add_pass(rr, rl, 3, SCE_PASS_ENVIRONMENT);
638                 if(srl->passflag  & SCE_PASS_INDIRECT)
639                         render_layer_add_pass(rr, rl, 3, SCE_PASS_INDIRECT);
640                 if(srl->passflag  & SCE_PASS_SHADOW)
641                         render_layer_add_pass(rr, rl, 3, SCE_PASS_SHADOW);
642                 if(srl->passflag  & SCE_PASS_REFLECT)
643                         render_layer_add_pass(rr, rl, 3, SCE_PASS_REFLECT);
644                 if(srl->passflag  & SCE_PASS_REFRACT)
645                         render_layer_add_pass(rr, rl, 3, SCE_PASS_REFRACT);
646                 if(srl->passflag  & SCE_PASS_INDEXOB)
647                         render_layer_add_pass(rr, rl, 1, SCE_PASS_INDEXOB);
648                 if(srl->passflag  & SCE_PASS_INDEXMA)
649                         render_layer_add_pass(rr, rl, 1, SCE_PASS_INDEXMA);
650                 if(srl->passflag  & SCE_PASS_MIST)
651                         render_layer_add_pass(rr, rl, 1, SCE_PASS_MIST);
652                 if(rl->passflag & SCE_PASS_RAYHITS)
653                         render_layer_add_pass(rr, rl, 4, SCE_PASS_RAYHITS);
654                 
655         }
656         /* sss, previewrender and envmap don't do layers, so we make a default one */
657         if(rr->layers.first==NULL) {
658                 rl= MEM_callocN(sizeof(RenderLayer), "new render layer");
659                 BLI_addtail(&rr->layers, rl);
660                 
661                 rl->rectx= rectx;
662                 rl->recty= recty;
663
664                 /* duplicate code... */
665                 if(rr->exrhandle) {
666                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.R", 0, 0, NULL);
667                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.G", 0, 0, NULL);
668                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.B", 0, 0, NULL);
669                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.A", 0, 0, NULL);
670                 }
671                 else
672                         rl->rectf= MEM_mapallocN(rectx*recty*sizeof(float)*4, "Combined rgba");
673                 
674                 /* note, this has to be in sync with scene.c */
675                 rl->lay= (1<<20) -1;
676                 rl->layflag= 0x7FFF;    /* solid ztra halo strand */
677                 rl->passflag= SCE_PASS_COMBINED;
678                 FRS_add_freestyle_config( srl );
679                 
680                 re->r.actlay= 0;
681         }
682         
683         /* border render; calculate offset for use in compositor. compo is centralized coords */
684         rr->xof= re->disprect.xmin + (re->disprect.xmax - re->disprect.xmin)/2 - re->winx/2;
685         rr->yof= re->disprect.ymin + (re->disprect.ymax - re->disprect.ymin)/2 - re->winy/2;
686         
687         return rr;
688 }
689
690 static int render_scene_needs_vector(Render *re)
691 {
692         SceneRenderLayer *srl;
693         
694         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
695                 if(!(srl->layflag & SCE_LAY_DISABLE))
696                         if(srl->passflag & SCE_PASS_VECTOR)
697                                 return 1;
698
699         return 0;
700 }
701
702 static void do_merge_tile(RenderResult *rr, RenderResult *rrpart, float *target, float *tile, int pixsize)
703 {
704         int y, ofs, copylen, tilex, tiley;
705         
706         copylen= tilex= rrpart->rectx;
707         tiley= rrpart->recty;
708         
709         if(rrpart->crop) {      /* filters add pixel extra */
710                 tile+= pixsize*(rrpart->crop + rrpart->crop*tilex);
711                 
712                 copylen= tilex - 2*rrpart->crop;
713                 tiley -= 2*rrpart->crop;
714                 
715                 ofs= (rrpart->tilerect.ymin + rrpart->crop)*rr->rectx + (rrpart->tilerect.xmin+rrpart->crop);
716                 target+= pixsize*ofs;
717         }
718         else {
719                 ofs= (rrpart->tilerect.ymin*rr->rectx + rrpart->tilerect.xmin);
720                 target+= pixsize*ofs;
721         }
722
723         copylen *= sizeof(float)*pixsize;
724         tilex *= pixsize;
725         ofs= pixsize*rr->rectx;
726
727         for(y=0; y<tiley; y++) {
728                 memcpy(target, tile, copylen);
729                 target+= ofs;
730                 tile+= tilex;
731         }
732 }
733
734 /* used when rendering to a full buffer, or when reading the exr part-layer-pass file */
735 /* no test happens here if it fits... we also assume layers are in sync */
736 /* is used within threads */
737 static void merge_render_result(RenderResult *rr, RenderResult *rrpart)
738 {
739         RenderLayer *rl, *rlp;
740         RenderPass *rpass, *rpassp;
741         
742         for(rl= rr->layers.first, rlp= rrpart->layers.first; rl && rlp; rl= rl->next, rlp= rlp->next) {
743                 
744                 /* combined */
745                 if(rl->rectf && rlp->rectf)
746                         do_merge_tile(rr, rrpart, rl->rectf, rlp->rectf, 4);
747                 
748                 /* passes are allocated in sync */
749                 for(rpass= rl->passes.first, rpassp= rlp->passes.first; rpass && rpassp; rpass= rpass->next, rpassp= rpassp->next) {
750                         do_merge_tile(rr, rrpart, rpass->rect, rpassp->rect, rpass->channels);
751                 }
752         }
753 }
754
755
756 static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart)
757 {
758         RenderLayer *rlp;
759         RenderPass *rpassp;
760         int offs, partx, party;
761         
762         BLI_lock_thread(LOCK_IMAGE);
763         
764         for(rlp= rrpart->layers.first; rlp; rlp= rlp->next) {
765                 
766                 if(rrpart->crop) {      /* filters add pixel extra */
767                         offs= (rrpart->crop + rrpart->crop*rrpart->rectx);
768                 }
769                 else {
770                         offs= 0;
771                 }
772                 
773                 /* combined */
774                 if(rlp->rectf) {
775                         int a, xstride= 4;
776                         for(a=0; a<xstride; a++)
777                                 IMB_exr_set_channel(rr->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a), 
778                                                                 xstride, xstride*rrpart->rectx, rlp->rectf+a + xstride*offs);
779                 }
780                 
781                 /* passes are allocated in sync */
782                 for(rpassp= rlp->passes.first; rpassp; rpassp= rpassp->next) {
783                         int a, xstride= rpassp->channels;
784                         for(a=0; a<xstride; a++)
785                                 IMB_exr_set_channel(rr->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a), 
786                                                                         xstride, xstride*rrpart->rectx, rpassp->rect+a + xstride*offs);
787                 }
788                 
789         }
790
791         party= rrpart->tilerect.ymin + rrpart->crop;
792         partx= rrpart->tilerect.xmin + rrpart->crop;
793         IMB_exrtile_write_channels(rr->exrhandle, partx, party, 0);
794
795         BLI_unlock_thread(LOCK_IMAGE);
796
797 }
798
799 static void save_empty_result_tiles(Render *re)
800 {
801         RenderPart *pa;
802         RenderResult *rr;
803         
804         for(rr= re->result; rr; rr= rr->next) {
805                 IMB_exrtile_clear_channels(rr->exrhandle);
806                 
807                 for(pa= re->parts.first; pa; pa= pa->next) {
808                         if(pa->ready==0) {
809                                 int party= pa->disprect.ymin - re->disprect.ymin + pa->crop;
810                                 int partx= pa->disprect.xmin - re->disprect.xmin + pa->crop;
811                                 IMB_exrtile_write_channels(rr->exrhandle, partx, party, 0);
812                         }
813                 }
814         }
815 }
816
817
818 /* for passes read from files, these have names stored */
819 static char *make_pass_name(RenderPass *rpass, int chan)
820 {
821         static char name[16];
822         int len;
823         
824         BLI_strncpy(name, rpass->name, EXR_PASS_MAXNAME);
825         len= strlen(name);
826         name[len]= '.';
827         name[len+1]= rpass->chan_id[chan];
828         name[len+2]= 0;
829
830         return name;
831 }
832
833 /* filename already made absolute */
834 /* called from within UI, saves both rendered result as a file-read result */
835 int RE_WriteRenderResult(ReportList *reports, RenderResult *rr, const char *filename, int compress)
836 {
837         RenderLayer *rl;
838         RenderPass *rpass;
839         void *exrhandle= IMB_exr_get_handle();
840         int success;
841
842         BLI_make_existing_file(filename);
843         
844         /* composite result */
845         if(rr->rectf) {
846                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.R", 4, 4*rr->rectx, rr->rectf);
847                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.G", 4, 4*rr->rectx, rr->rectf+1);
848                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.B", 4, 4*rr->rectx, rr->rectf+2);
849                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.A", 4, 4*rr->rectx, rr->rectf+3);
850         }
851         
852         /* add layers/passes and assign channels */
853         for(rl= rr->layers.first; rl; rl= rl->next) {
854                 
855                 /* combined */
856                 if(rl->rectf) {
857                         int a, xstride= 4;
858                         for(a=0; a<xstride; a++)
859                                 IMB_exr_add_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
860                                                                         xstride, xstride*rr->rectx, rl->rectf+a);
861                 }
862                 
863                 /* passes are allocated in sync */
864                 for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
865                         int a, xstride= rpass->channels;
866                         for(a=0; a<xstride; a++) {
867                                 if(rpass->passtype)
868                                         IMB_exr_add_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
869                                                                                 xstride, xstride*rr->rectx, rpass->rect+a);
870                                 else
871                                         IMB_exr_add_channel(exrhandle, rl->name, make_pass_name(rpass, a), 
872                                                                                 xstride, xstride*rr->rectx, rpass->rect+a);
873                         }
874                 }
875         }
876
877         /* when the filename has no permissions, this can fail */
878         if(IMB_exr_begin_write(exrhandle, filename, rr->rectx, rr->recty, compress)) {
879                 IMB_exr_write_channels(exrhandle);
880                 success= TRUE;
881         }
882         else {
883                 /* TODO, get the error from openexr's exception */
884                 BKE_report(reports, RPT_ERROR, "Error Writing Render Result, see console");
885                 success= FALSE;
886         }
887         IMB_exr_close(exrhandle);
888
889         return success;
890 }
891
892 /* callbacks for RE_MultilayerConvert */
893 static void *ml_addlayer_cb(void *base, char *str)
894 {
895         RenderResult *rr= base;
896         RenderLayer *rl;
897         
898         rl= MEM_callocN(sizeof(RenderLayer), "new render layer");
899         BLI_addtail(&rr->layers, rl);
900         
901         BLI_strncpy(rl->name, str, EXR_LAY_MAXNAME);
902         return rl;
903 }
904 static void ml_addpass_cb(void *UNUSED(base), void *lay, char *str, float *rect, int totchan, char *chan_id)
905 {
906         RenderLayer *rl= lay;   
907         RenderPass *rpass= MEM_callocN(sizeof(RenderPass), "loaded pass");
908         int a;
909         
910         BLI_addtail(&rl->passes, rpass);
911         rpass->channels= totchan;
912
913         rpass->passtype= passtype_from_name(str);
914         if(rpass->passtype==0) printf("unknown pass %s\n", str);
915         rl->passflag |= rpass->passtype;
916         
917         BLI_strncpy(rpass->name, str, EXR_PASS_MAXNAME);
918         /* channel id chars */
919         for(a=0; a<totchan; a++)
920                 rpass->chan_id[a]= chan_id[a];
921         
922         rpass->rect= rect;
923 }
924
925 /* from imbuf, if a handle was returned we convert this to render result */
926 RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty)
927 {
928         RenderResult *rr= MEM_callocN(sizeof(RenderResult), "loaded render result");
929         RenderLayer *rl;
930         RenderPass *rpass;
931         
932         rr->rectx= rectx;
933         rr->recty= recty;
934         
935         IMB_exr_multilayer_convert(exrhandle, rr, ml_addlayer_cb, ml_addpass_cb);
936
937         for(rl=rr->layers.first; rl; rl=rl->next) {
938                 rl->rectx= rectx;
939                 rl->recty= recty;
940
941                 for(rpass=rl->passes.first; rpass; rpass=rpass->next) {
942                         rpass->rectx= rectx;
943                         rpass->recty= recty;
944                 }
945         }
946         
947         return rr;
948 }
949
950 /* called in end of render, to add names to passes... for UI only */
951 static void renderresult_add_names(RenderResult *rr)
952 {
953         RenderLayer *rl;
954         RenderPass *rpass;
955         
956         for(rl= rr->layers.first; rl; rl= rl->next)
957                 for(rpass= rl->passes.first; rpass; rpass= rpass->next)
958                         BLI_strncpy(rpass->name, get_pass_name(rpass->passtype, -1), sizeof(rpass->name));
959 }
960
961 /* called for reading temp files, and for external engines */
962 static int read_render_result_from_file(const char *filename, RenderResult *rr)
963 {
964         RenderLayer *rl;
965         RenderPass *rpass;
966         void *exrhandle= IMB_exr_get_handle();
967         int rectx, recty;
968
969         if(IMB_exr_begin_read(exrhandle, filename, &rectx, &recty)==0) {
970                 printf("failed being read %s\n", filename);
971                 IMB_exr_close(exrhandle);
972                 return 0;
973         }
974
975         if(rr == NULL || rectx!=rr->rectx || recty!=rr->recty) {
976                 if(rr)
977                         printf("error in reading render result: dimensions don't match\n");
978                 else
979                         printf("error in reading render result: NULL result pointer\n");
980                 IMB_exr_close(exrhandle);
981                 return 0;
982         }
983         else {
984                 for(rl= rr->layers.first; rl; rl= rl->next) {
985                         
986                         /* combined */
987                         if(rl->rectf) {
988                                 int a, xstride= 4;
989                                 for(a=0; a<xstride; a++)
990                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
991                                                                                 xstride, xstride*rectx, rl->rectf+a);
992                         }
993                         
994                         /* passes are allocated in sync */
995                         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
996                                 int a, xstride= rpass->channels;
997                                 for(a=0; a<xstride; a++)
998                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
999                                                                                 xstride, xstride*rectx, rpass->rect+a);
1000                         }
1001                         
1002                 }
1003                 IMB_exr_read_channels(exrhandle);
1004                 renderresult_add_names(rr);
1005         }
1006         
1007         IMB_exr_close(exrhandle);
1008
1009         return 1;
1010 }
1011
1012 /* only for temp buffer files, makes exact copy of render result */
1013 static int read_render_result(Render *re, int sample)
1014 {
1015         char str[FILE_MAX];
1016         int success;
1017
1018         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1019
1020         RE_FreeRenderResult(re->result);
1021         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1022
1023         render_unique_exr_name(re, str, sample);
1024         printf("read exr tmp file: %s\n", str);
1025
1026         if(read_render_result_from_file(str, re->result)) {
1027                 success= TRUE;
1028         }
1029         else {
1030                 printf("cannot read: %s\n", str);
1031                 success= FALSE;
1032
1033         }
1034
1035         BLI_rw_mutex_unlock(&re->resultmutex);
1036
1037         return success;
1038 }
1039
1040 /* *************************************************** */
1041
1042 Render *RE_GetRender(const char *name)
1043 {
1044         Render *re;
1045
1046         /* search for existing renders */
1047         for(re= RenderGlobal.renderlist.first; re; re= re->next)
1048                 if(strncmp(re->name, name, RE_MAXNAME)==0)
1049                         break;
1050
1051         return re;
1052 }
1053
1054 /* if you want to know exactly what has been done */
1055 RenderResult *RE_AcquireResultRead(Render *re)
1056 {
1057         if(re) {
1058                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
1059                 return re->result;
1060         }
1061
1062         return NULL;
1063 }
1064
1065 RenderResult *RE_AcquireResultWrite(Render *re)
1066 {
1067         if(re) {
1068                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1069                 return re->result;
1070         }
1071
1072         return NULL;
1073 }
1074
1075 void RE_SwapResult(Render *re, RenderResult **rr)
1076 {
1077         /* for keeping render buffers */
1078         if(re) {
1079                 SWAP(RenderResult*, re->result, *rr);
1080         }
1081 }
1082
1083
1084 void RE_ReleaseResult(Render *re)
1085 {
1086         if(re)
1087                 BLI_rw_mutex_unlock(&re->resultmutex);
1088 }
1089
1090 /* displist.c util.... */
1091 Scene *RE_GetScene(Render *re)
1092 {
1093         if(re)
1094                 return re->scene;
1095         return NULL;
1096 }
1097
1098 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
1099 {
1100         RenderLayer *rl= BLI_findlink(&rr->layers, re->r.actlay);
1101         
1102         if(rl) 
1103                 return rl;
1104         else 
1105                 return rr->layers.first;
1106 }
1107
1108
1109 /* fill provided result struct with what's currently active or done */
1110 void RE_AcquireResultImage(Render *re, RenderResult *rr)
1111 {
1112         memset(rr, 0, sizeof(RenderResult));
1113
1114         if(re) {
1115                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
1116
1117                 if(re->result) {
1118                         RenderLayer *rl;
1119                         
1120                         rr->rectx= re->result->rectx;
1121                         rr->recty= re->result->recty;
1122                         
1123                         rr->rectf= re->result->rectf;
1124                         rr->rectz= re->result->rectz;
1125                         rr->rect32= re->result->rect32;
1126                         
1127                         /* active layer */
1128                         rl= render_get_active_layer(re, re->result);
1129
1130                         if(rl) {
1131                                 if(rr->rectf==NULL)
1132                                         rr->rectf= rl->rectf;
1133                                 if(rr->rectz==NULL)
1134                                         rr->rectz= RE_RenderLayerGetPass(rl, SCE_PASS_Z);       
1135                         }
1136
1137                         rr->have_combined= (re->result->rectf != NULL);
1138                         rr->layers= re->result->layers;
1139                 }
1140         }
1141 }
1142
1143 void RE_ReleaseResultImage(Render *re)
1144 {
1145         if(re)
1146                 BLI_rw_mutex_unlock(&re->resultmutex);
1147 }
1148
1149 /* caller is responsible for allocating rect in correct size! */
1150 void RE_ResultGet32(Render *re, unsigned int *rect)
1151 {
1152         RenderResult rres;
1153         
1154         RE_AcquireResultImage(re, &rres);
1155
1156         if(rres.rect32) 
1157                 memcpy(rect, rres.rect32, sizeof(int)*rres.rectx*rres.recty);
1158         else if(rres.rectf) {
1159                 float *fp= rres.rectf;
1160                 int tot= rres.rectx*rres.recty;
1161                 char *cp= (char *)rect;
1162                 
1163                 if (re->r.color_mgt_flag & R_COLOR_MANAGEMENT) {
1164                         /* Finally convert back to sRGB rendered image */ 
1165                         for(;tot>0; tot--, cp+=4, fp+=4) {
1166                                 cp[0] = FTOCHAR(linearrgb_to_srgb(fp[0]));
1167                                 cp[1] = FTOCHAR(linearrgb_to_srgb(fp[1]));
1168                                 cp[2] = FTOCHAR(linearrgb_to_srgb(fp[2]));
1169                                 cp[3] = FTOCHAR(fp[3]);
1170                         }
1171                 }
1172                 else {
1173                         /* Color management is off : no conversion necessary */
1174                         for(;tot>0; tot--, cp+=4, fp+=4) {
1175                                 cp[0] = FTOCHAR(fp[0]);
1176                                 cp[1] = FTOCHAR(fp[1]);
1177                                 cp[2] = FTOCHAR(fp[2]);
1178                                 cp[3] = FTOCHAR(fp[3]);
1179                         }
1180                 }
1181
1182         }
1183         else
1184                 /* else fill with black */
1185                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
1186
1187         RE_ReleaseResultImage(re);
1188 }
1189
1190 RenderStats *RE_GetStats(Render *re)
1191 {
1192         return &re->i;
1193 }
1194
1195 Render *RE_NewRender(const char *name)
1196 {
1197         Render *re;
1198
1199         /* only one render per name exists */
1200         re= RE_GetRender(name);
1201         if(re==NULL) {
1202                 
1203                 /* new render data struct */
1204                 re= MEM_callocN(sizeof(Render), "new render");
1205                 BLI_addtail(&RenderGlobal.renderlist, re);
1206                 strncpy(re->name, name, RE_MAXNAME);
1207                 BLI_rw_mutex_init(&re->resultmutex);
1208         }
1209         
1210         RE_InitRenderCB(re);
1211
1212         /* init some variables */
1213         re->ycor= 1.0f;
1214         
1215         return re;
1216 }
1217
1218 /* called for new renders and when finishing rendering so
1219  * we calways have valid callbacks on a render */
1220 void RE_InitRenderCB(Render *re)
1221 {
1222         /* set default empty callbacks */
1223         re->display_init= result_nothing;
1224         re->display_clear= result_nothing;
1225         re->display_draw= result_rcti_nothing;
1226         re->progress= float_nothing;
1227         re->test_break= default_break;
1228         if(G.background)
1229                 re->stats_draw= stats_background;
1230         else
1231                 re->stats_draw= stats_nothing;
1232         /* clear callback handles */
1233         re->dih= re->dch= re->ddh= re->sdh= re->prh= re->tbh= NULL;
1234 }
1235
1236 /* only call this while you know it will remove the link too */
1237 void RE_FreeRender(Render *re)
1238 {
1239         BLI_rw_mutex_end(&re->resultmutex);
1240         
1241         free_renderdata_tables(re);
1242         free_sample_tables(re);
1243         
1244         RE_FreeRenderResult(re->result);
1245         RE_FreeRenderResult(re->pushedresult);
1246         
1247         BLI_remlink(&RenderGlobal.renderlist, re);
1248         MEM_freeN(re);
1249 }
1250
1251 /* exit blender */
1252 void RE_FreeAllRender(void)
1253 {
1254         while(RenderGlobal.renderlist.first) {
1255                 RE_FreeRender(RenderGlobal.renderlist.first);
1256         }
1257 }
1258
1259 /* ********* initialize state ******** */
1260
1261
1262 /* what doesn't change during entire render sequence */
1263 /* disprect is optional, if NULL it assumes full window render */
1264 void RE_InitState(Render *re, Render *source, RenderData *rd, SceneRenderLayer *srl, int winx, int winy, rcti *disprect)
1265 {
1266         re->ok= TRUE;   /* maybe flag */
1267         
1268         re->i.starttime= PIL_check_seconds_timer();
1269         re->r= *rd;             /* hardcopy */
1270         
1271         re->winx= winx;
1272         re->winy= winy;
1273         if(disprect) {
1274                 re->disprect= *disprect;
1275                 re->rectx= disprect->xmax-disprect->xmin;
1276                 re->recty= disprect->ymax-disprect->ymin;
1277         }
1278         else {
1279                 re->disprect.xmin= re->disprect.ymin= 0;
1280                 re->disprect.xmax= winx;
1281                 re->disprect.ymax= winy;
1282                 re->rectx= winx;
1283                 re->recty= winy;
1284         }
1285         
1286         if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
1287                                                                                   (re->rectx < 16 || re->recty < 16) )) {
1288                 BKE_report(re->reports, RPT_ERROR, "Image too small");
1289                 re->ok= 0;
1290                 return;
1291         }
1292
1293         if((re->r.mode & (R_OSA))==0)
1294                 re->r.scemode &= ~R_FULL_SAMPLE;
1295
1296 #ifdef WITH_OPENEXR
1297         if(re->r.scemode & R_FULL_SAMPLE)
1298                 re->r.scemode |= R_EXR_TILE_FILE;       /* enable automatic */
1299
1300         /* Until use_border is made compatible with save_buffers/full_sample, render without the later instead of not rendering at all.*/
1301         if(re->r.mode & R_BORDER) 
1302         {
1303                 re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1304         }
1305
1306 #else
1307         /* can't do this without openexr support */
1308         re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1309 #endif
1310         
1311         /* fullsample wants uniform osa levels */
1312         if(source && (re->r.scemode & R_FULL_SAMPLE)) {
1313                 /* but, if source has no full sample we disable it */
1314                 if((source->r.scemode & R_FULL_SAMPLE)==0)
1315                         re->r.scemode &= ~R_FULL_SAMPLE;
1316                 else
1317                         re->r.osa= re->osa= source->osa;
1318         }
1319         else {
1320                 /* check state variables, osa? */
1321                 if(re->r.mode & (R_OSA)) {
1322                         re->osa= re->r.osa;
1323                         if(re->osa>16) re->osa= 16;
1324                 }
1325                 else re->osa= 0;
1326         }
1327         
1328         if (srl) {
1329                 int index = BLI_findindex(&re->r.layers, srl);
1330                 if (index != -1) {
1331                         re->r.actlay = index;
1332                         re->r.scemode |= R_SINGLE_LAYER;
1333                 }
1334         }
1335                 
1336         /* always call, checks for gamma, gamma tables and jitter too */
1337         make_sample_tables(re); 
1338         
1339         /* if preview render, we try to keep old result */
1340         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1341
1342         if(re->r.scemode & R_PREVIEWBUTS) {
1343                 if(re->result && re->result->rectx==re->rectx && re->result->recty==re->recty);
1344                 else {
1345                         RE_FreeRenderResult(re->result);
1346                         re->result= NULL;
1347                 }
1348         }
1349         else {
1350                 
1351                 /* make empty render result, so display callbacks can initialize */
1352                 RE_FreeRenderResult(re->result);
1353                 re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1354                 re->result->rectx= re->rectx;
1355                 re->result->recty= re->recty;
1356         }
1357
1358         BLI_rw_mutex_unlock(&re->resultmutex);
1359         
1360         /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1361         re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1362         
1363         re->mblur_offs = re->field_offs = 0.f;
1364         
1365         RE_init_threadcount(re);
1366 }
1367
1368 /* part of external api, not called for regular render pipeline */
1369 void RE_SetDispRect (struct Render *re, rcti *disprect)
1370 {
1371         re->disprect= *disprect;
1372         re->rectx= disprect->xmax-disprect->xmin;
1373         re->recty= disprect->ymax-disprect->ymin;
1374         
1375         /* initialize render result */
1376         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1377
1378         RE_FreeRenderResult(re->result);
1379         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1380
1381         BLI_rw_mutex_unlock(&re->resultmutex);
1382 }
1383
1384 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1385 {
1386         /* re->ok flag? */
1387         
1388         re->viewplane= *viewplane;
1389         re->clipsta= clipsta;
1390         re->clipend= clipend;
1391         re->r.mode &= ~R_ORTHO;
1392
1393         perspective_m4( re->winmat,re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
1394         
1395 }
1396
1397 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1398 {
1399         /* re->ok flag? */
1400         
1401         re->viewplane= *viewplane;
1402         re->clipsta= clipsta;
1403         re->clipend= clipend;
1404         re->r.mode |= R_ORTHO;
1405
1406         orthographic_m4( re->winmat,re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
1407 }
1408
1409 void RE_SetView(Render *re, float mat[][4])
1410 {
1411         /* re->ok flag? */
1412         copy_m4_m4(re->viewmat, mat);
1413         invert_m4_m4(re->viewinv, re->viewmat);
1414 }
1415
1416 /* image and movie output has to move to either imbuf or kernel */
1417 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1418 {
1419         re->display_init= f;
1420         re->dih= handle;
1421 }
1422 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1423 {
1424         re->display_clear= f;
1425         re->dch= handle;
1426 }
1427 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
1428 {
1429         re->display_draw= f;
1430         re->ddh= handle;
1431 }
1432 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
1433 {
1434         re->stats_draw= f;
1435         re->sdh= handle;
1436 }
1437 void RE_progress_cb(Render *re, void *handle, void (*f)(void *handle, float))
1438 {
1439         re->progress= f;
1440         re->prh= handle;
1441 }
1442
1443 void RE_draw_lock_cb(Render *re, void *handle, void (*f)(void *handle, int i))
1444 {
1445         re->draw_lock= f;
1446         re->tbh= handle;
1447 }
1448
1449 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
1450 {
1451         re->test_break= f;
1452         re->tbh= handle;
1453 }
1454
1455
1456 /* ********* add object data (later) ******** */
1457
1458 /* object is considered fully prepared on correct time etc */
1459 /* includes lights */
1460 void RE_AddObject(Render *UNUSED(re), Object *UNUSED(ob))
1461 {
1462         
1463 }
1464
1465 /* *************************************** */
1466
1467 static int render_display_draw_enabled(Render *re)
1468 {
1469         /* don't show preprocess for previewrender sss */
1470         if(re->sss_points)
1471                 return !(re->r.scemode & R_PREVIEWBUTS);
1472         else
1473                 return 1;
1474 }
1475
1476 /* allocate osa new results for samples */
1477 static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
1478 {
1479         int a;
1480         
1481         if(re->osa==0)
1482                 return new_render_result(re, partrct, crop, RR_USEMEM);
1483         
1484         for(a=0; a<re->osa; a++) {
1485                 RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
1486                 BLI_addtail(lb, rr);
1487                 rr->sample_nr= a;
1488         }
1489         
1490         return lb->first;
1491 }
1492
1493
1494 /* the main thread call, renders an entire part */
1495 static void *do_part_thread(void *pa_v)
1496 {
1497         RenderPart *pa= pa_v;
1498         
1499         /* need to return nicely all parts on esc */
1500         if(R.test_break(R.tbh)==0) {
1501                 
1502                 if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
1503                         pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
1504                 else
1505                         pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1506
1507                 if(R.sss_points)
1508                         zbufshade_sss_tile(pa);
1509                 else if(R.osa)
1510                         zbufshadeDA_tile(pa);
1511                 else
1512                         zbufshade_tile(pa);
1513                 
1514                 /* merge too on break! */
1515                 if(R.result->exrhandle) {
1516                         RenderResult *rr, *rrpart;
1517                         
1518                         for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
1519                                 save_render_result_tile(rr, rrpart);
1520                         
1521                 }
1522                 else if(render_display_draw_enabled(&R)) {
1523                         /* on break, don't merge in result for preview renders, looks nicer */
1524                         if(R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS));
1525                         else merge_render_result(R.result, pa->result);
1526                 }
1527         }
1528         
1529         pa->ready= 1;
1530         
1531         return NULL;
1532 }
1533
1534 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1535 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1536 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1537 float panorama_pixel_rot(Render *re)
1538 {
1539         float psize, phi, xfac;
1540         float borderfac= (float)(re->disprect.xmax - re->disprect.xmin) / (float)re->winx;
1541         
1542         /* size of 1 pixel mapped to viewplane coords */
1543         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)(re->winx);
1544         /* angle of a pixel */
1545         phi= atan(psize/re->clipsta);
1546         
1547         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1548         xfac= borderfac*((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1549         xfac= atan(0.5f*xfac/re->clipsta); 
1550         /* and how much the same viewplane angle is wrapped */
1551         psize= 0.5f*phi*((float)re->partx);
1552         
1553         /* the ratio applied to final per-pixel angle */
1554         phi*= xfac/psize;
1555         
1556         return phi;
1557 }
1558
1559 /* call when all parts stopped rendering, to find the next Y slice */
1560 /* if slice found, it rotates the dbase */
1561 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1562 {
1563         RenderPart *pa, *best= NULL;
1564         
1565         *minx= re->winx;
1566         
1567         /* most left part of the non-rendering parts */
1568         for(pa= re->parts.first; pa; pa= pa->next) {
1569                 if(pa->ready==0 && pa->nr==0) {
1570                         if(pa->disprect.xmin < *minx) {
1571                                 best= pa;
1572                                 *minx= pa->disprect.xmin;
1573                         }
1574                 }
1575         }
1576                         
1577         if(best) {
1578                 float phi= panorama_pixel_rot(re);
1579
1580                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1581                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)(re->winx);
1582                 
1583                 /* shift viewplane */
1584                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1585                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1586                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1587                 copy_m4_m4(R.winmat, re->winmat);
1588                 
1589                 /* rotate database according to part coordinates */
1590                 project_renderdata(re, projectverto, 1, -R.panodxp*phi, 1);
1591                 R.panosi= sin(R.panodxp*phi);
1592                 R.panoco= cos(R.panodxp*phi);
1593         }
1594         return best;
1595 }
1596
1597 static RenderPart *find_next_part(Render *re, int minx)
1598 {
1599         RenderPart *pa, *best= NULL;
1600
1601         /* long long int's needed because of overflow [#24414] */
1602         long long int centx=re->winx/2, centy=re->winy/2, tot=1;
1603         long long int mindist= (long long int)re->winx * (long long int)re->winy;
1604         
1605         /* find center of rendered parts, image center counts for 1 too */
1606         for(pa= re->parts.first; pa; pa= pa->next) {
1607                 if(pa->ready) {
1608                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1609                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1610                         tot++;
1611                 }
1612         }
1613         centx/=tot;
1614         centy/=tot;
1615         
1616         /* closest of the non-rendering parts */
1617         for(pa= re->parts.first; pa; pa= pa->next) {
1618                 if(pa->ready==0 && pa->nr==0) {
1619                         long long int distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1620                         long long int disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1621                         distx= (long long int)sqrt(distx*distx + disty*disty);
1622                         if(distx<mindist) {
1623                                 if(re->r.mode & R_PANORAMA) {
1624                                         if(pa->disprect.xmin==minx) {
1625                                                 best= pa;
1626                                                 mindist= distx;
1627                                         }
1628                                 }
1629                                 else {
1630                                         best= pa;
1631                                         mindist= distx;
1632                                 }
1633                         }
1634                 }
1635         }
1636         return best;
1637 }
1638
1639 static void print_part_stats(Render *re, RenderPart *pa)
1640 {
1641         char str[64];
1642         
1643         BLI_snprintf(str, sizeof(str), "%s, Part %d-%d", re->scene->id.name+2, pa->nr, re->i.totpart);
1644         re->i.infostr= str;
1645         re->stats_draw(re->sdh, &re->i);
1646         re->i.infostr= NULL;
1647 }
1648
1649 /* make osa new results for samples */
1650 static RenderResult *new_full_sample_buffers_exr(Render *re)
1651 {
1652         int a;
1653         
1654         for(a=0; a<re->osa; a++) {
1655                 RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
1656                 BLI_addtail(&re->fullresult, rr);
1657                 rr->sample_nr= a;
1658         }
1659         
1660         return re->fullresult.first;
1661 }
1662
1663 static void threaded_tile_processor(Render *re)
1664 {
1665         ListBase threads;
1666         RenderPart *pa, *nextpa;
1667         rctf viewplane= re->viewplane;
1668         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1669         
1670         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1671
1672         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
1673         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
1674                 RE_FreeRenderResult(re->result);
1675         
1676                 if(re->sss_points && render_display_draw_enabled(re))
1677                         re->result= new_render_result(re, &re->disprect, 0, 0);
1678                 else if(re->r.scemode & R_FULL_SAMPLE)
1679                         re->result= new_full_sample_buffers_exr(re);
1680                 else
1681                         re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
1682         }
1683
1684         BLI_rw_mutex_unlock(&re->resultmutex);
1685         
1686         if(re->result==NULL)
1687                 return;
1688         
1689         /* warning; no return here without closing exr file */
1690         
1691         initparts(re);
1692
1693         if(re->result->exrhandle) {
1694                 RenderResult *rr;
1695                 char str[FILE_MAX];
1696                 
1697                 for(rr= re->result; rr; rr= rr->next) {
1698                         render_unique_exr_name(re, str, rr->sample_nr);
1699                 
1700                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1701                         IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1702                 }
1703         }
1704         
1705         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1706         
1707         /* assuming no new data gets added to dbase... */
1708         R= *re;
1709         
1710         /* set threadsafe break */
1711         R.test_break= thread_break;
1712         
1713         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1714         if(re->r.mode & R_PANORAMA)
1715                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1716         else
1717                 nextpa= find_next_part(re, 0);
1718         
1719         while(rendering) {
1720                 
1721                 if(re->test_break(re->tbh))
1722                         PIL_sleep_ms(50);
1723                 else if(nextpa && BLI_available_threads(&threads)) {
1724                         drawtimer= 0;
1725                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1726                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1727                         BLI_insert_thread(&threads, nextpa);
1728
1729                         nextpa= find_next_part(re, minx);
1730                 }
1731                 else if(re->r.mode & R_PANORAMA) {
1732                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1733                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1734                         else {
1735                                 PIL_sleep_ms(50);
1736                                 drawtimer++;
1737                         }
1738                 }
1739                 else {
1740                         PIL_sleep_ms(50);
1741                         drawtimer++;
1742                 }
1743                 
1744                 /* check for ready ones to display, and if we need to continue */
1745                 rendering= 0;
1746                 hasdrawn= 0;
1747                 for(pa= re->parts.first; pa; pa= pa->next) {
1748                         if(pa->ready) {
1749                                 
1750                                 BLI_remove_thread(&threads, pa);
1751                                 
1752                                 if(pa->result) {
1753                                         if(render_display_draw_enabled(re))
1754                                                 re->display_draw(re->ddh, pa->result, NULL);
1755                                         print_part_stats(re, pa);
1756                                         
1757                                         free_render_result(&pa->fullresult, pa->result);
1758                                         pa->result= NULL;
1759                                         re->i.partsdone++;
1760                                         re->progress(re->prh, re->i.partsdone / (float)re->i.totpart);
1761                                         hasdrawn= 1;
1762                                 }
1763                         }
1764                         else {
1765                                 rendering= 1;
1766                                 if(pa->nr && pa->result && drawtimer>20) {
1767                                         if(render_display_draw_enabled(re))
1768                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
1769                                         hasdrawn= 1;
1770                                 }
1771                         }
1772                 }
1773                 if(hasdrawn)
1774                         drawtimer= 0;
1775
1776                 /* on break, wait for all slots to get freed */
1777                 if( (g_break=re->test_break(re->tbh)) && BLI_available_threads(&threads)==re->r.threads)
1778                         rendering= 0;
1779                 
1780         }
1781         
1782         if(re->result->exrhandle) {
1783                 RenderResult *rr;
1784
1785                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1786                 save_empty_result_tiles(re);
1787                 
1788                 for(rr= re->result; rr; rr= rr->next) {
1789                         IMB_exr_close(rr->exrhandle);
1790                         rr->exrhandle= NULL;
1791                 }
1792                 
1793                 free_render_result(&re->fullresult, re->result);
1794                 re->result= NULL;
1795
1796                 BLI_rw_mutex_unlock(&re->resultmutex);
1797                 
1798                 read_render_result(re, 0);
1799         }
1800         
1801         /* unset threadsafety */
1802         g_break= 0;
1803         
1804         BLI_end_threads(&threads);
1805         freeparts(re);
1806         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1807 }
1808
1809 /* currently only called by preview renders and envmap */
1810 void RE_TileProcessor(Render *re)
1811 {
1812         threaded_tile_processor(re);
1813 }
1814
1815 /* ************  This part uses API, for rendering Blender scenes ********** */
1816
1817 static int external_render_3d(Render *re, int do_all);
1818 static void add_freestyle(Render *re);
1819
1820 static void do_render_3d(Render *re)
1821 {
1822         /* try external */
1823         if(external_render_3d(re, 0))
1824                 return;
1825
1826         /* internal */
1827         
1828 //      re->cfra= cfra; /* <- unused! */
1829         re->scene->r.subframe = re->mblur_offs + re->field_offs;
1830         
1831         /* lock drawing in UI during data phase */
1832         if(re->draw_lock)
1833                 re->draw_lock(re->dlh, 1);
1834         
1835         /* make render verts/faces/halos/lamps */
1836         if(render_scene_needs_vector(re))
1837                 RE_Database_FromScene_Vectors(re, re->main, re->scene, re->lay);
1838         else
1839            RE_Database_FromScene(re, re->main, re->scene, re->lay, 1);
1840         
1841         /* clear UI drawing locks */
1842         if(re->draw_lock)
1843                 re->draw_lock(re->dlh, 0);
1844         
1845         threaded_tile_processor(re);
1846         
1847         /* do left-over 3d post effects (flares) */
1848         if(re->flag & R_HALO)
1849                 if(!re->test_break(re->tbh))
1850                         add_halo_flare(re);
1851         
1852         /* Freestyle  */
1853         if( re->r.mode & R_EDGE_FRS && re->r.renderer==R_INTERN)
1854                 if(!re->test_break(re->tbh))
1855                         add_freestyle(re);
1856                 
1857         /* free all render verts etc */
1858         RE_Database_Free(re);
1859         
1860         re->scene->r.subframe = 0.f;
1861 }
1862
1863 /* called by blur loop, accumulate RGBA key alpha */
1864 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
1865 {
1866         float mfac= 1.0f - blurfac;
1867         int a, b, stride= 4*rr->rectx;
1868         int len= stride*sizeof(float);
1869         
1870         for(a=0; a<rr->recty; a++) {
1871                 if(blurfac==1.0f) {
1872                         memcpy(rectf, rectf1, len);
1873                 }
1874                 else {
1875                         float *rf= rectf, *rf1= rectf1;
1876                         
1877                         for( b= rr->rectx; b>0; b--, rf+=4, rf1+=4) {
1878                                 if(rf1[3]<0.01f)
1879                                         rf[3]= mfac*rf[3];
1880                                 else if(rf[3]<0.01f) {
1881                                         rf[0]= rf1[0];
1882                                         rf[1]= rf1[1];
1883                                         rf[2]= rf1[2];
1884                                         rf[3]= blurfac*rf1[3];
1885                                 }
1886                                 else {
1887                                         rf[0]= mfac*rf[0] + blurfac*rf1[0];
1888                                         rf[1]= mfac*rf[1] + blurfac*rf1[1];
1889                                         rf[2]= mfac*rf[2] + blurfac*rf1[2];
1890                                         rf[3]= mfac*rf[3] + blurfac*rf1[3];
1891                                 }                               
1892                         }
1893                 }
1894                 rectf+= stride;
1895                 rectf1+= stride;
1896         }
1897 }
1898
1899 /* called by blur loop, accumulate renderlayers */
1900 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1901 {
1902         float mfac= 1.0f - blurfac;
1903         int a, b, stride= channels*rr->rectx;
1904         int len= stride*sizeof(float);
1905         
1906         for(a=0; a<rr->recty; a++) {
1907                 if(blurfac==1.0f) {
1908                         memcpy(rectf, rectf1, len);
1909                 }
1910                 else {
1911                         float *rf= rectf, *rf1= rectf1;
1912                         
1913                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1914                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1915                         }
1916                 }
1917                 rectf+= stride;
1918                 rectf1+= stride;
1919         }
1920 }
1921
1922
1923 /* called by blur loop, accumulate renderlayers */
1924 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1925 {
1926         RenderLayer *rl, *rl1;
1927         RenderPass *rpass, *rpass1;
1928         
1929         rl1= brr->layers.first;
1930         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1931                 
1932                 /* combined */
1933                 if(rl->rectf && rl1->rectf) {
1934                         if(key_alpha)
1935                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1936                         else
1937                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1938                 }
1939                 
1940                 /* passes are allocated in sync */
1941                 rpass1= rl1->passes.first;
1942                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1943                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1944                 }
1945         }
1946 }
1947
1948 /* main blur loop, can be called by fields too */
1949 static void do_render_blur_3d(Render *re)
1950 {
1951         RenderResult *rres;
1952         float blurfac;
1953         int blur= re->r.mblur_samples;
1954         
1955         /* create accumulation render result */
1956         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1957         
1958         /* do the blur steps */
1959         while(blur--) {
1960                 re->mblur_offs = re->r.blurfac*((float)(re->r.mblur_samples-blur))/(float)re->r.mblur_samples;
1961                 
1962                 re->i.curblur= re->r.mblur_samples-blur;        /* stats */
1963                 
1964                 do_render_3d(re);
1965                 
1966                 blurfac= 1.0f/(float)(re->r.mblur_samples-blur);
1967                 
1968                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1969                 if(re->test_break(re->tbh)) break;
1970         }
1971         
1972         /* swap results */
1973         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1974         RE_FreeRenderResult(re->result);
1975         re->result= rres;
1976         BLI_rw_mutex_unlock(&re->resultmutex);
1977         
1978         re->mblur_offs = 0.0f;
1979         re->i.curblur= 0;       /* stats */
1980         
1981         /* weak... the display callback wants an active renderlayer pointer... */
1982         re->result->renlay= render_get_active_layer(re, re->result);
1983         re->display_draw(re->ddh, re->result, NULL);    
1984 }
1985
1986
1987 /* function assumes rectf1 and rectf2 to be half size of rectf */
1988 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1989 {
1990         int a, stride= channels*rr->rectx;
1991         int len= stride*sizeof(float);
1992         
1993         for(a=0; a<rr->recty; a+=2) {
1994                 memcpy(rectf, rectf1, len);
1995                 rectf+= stride;
1996                 rectf1+= stride;
1997                 memcpy(rectf, rectf2, len);
1998                 rectf+= stride;
1999                 rectf2+= stride;
2000         }
2001 }
2002
2003 /* merge render results of 2 fields */
2004 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
2005 {
2006         RenderLayer *rl, *rl1, *rl2;
2007         RenderPass *rpass, *rpass1, *rpass2;
2008         
2009         rl1= rr1->layers.first;
2010         rl2= rr2->layers.first;
2011         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
2012                 
2013                 /* combined */
2014                 if(rl->rectf && rl1->rectf && rl2->rectf)
2015                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
2016                 
2017                 /* passes are allocated in sync */
2018                 rpass1= rl1->passes.first;
2019                 rpass2= rl2->passes.first;
2020                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
2021                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
2022                 }
2023         }
2024 }
2025
2026
2027 /* interleaves 2 frames */
2028 static void do_render_fields_3d(Render *re)
2029 {
2030         Object *camera= RE_GetCamera(re);
2031         RenderResult *rr1, *rr2= NULL;
2032         
2033         /* no render result was created, we can safely halve render y */
2034         re->winy /= 2;
2035         re->recty /= 2;
2036         re->disprect.ymin /= 2;
2037         re->disprect.ymax /= 2;
2038         
2039         re->i.curfield= 1;      /* stats */
2040         
2041         /* first field, we have to call camera routine for correct aspect and subpixel offset */
2042         RE_SetCamera(re, camera);
2043         if(re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE)==0)
2044                 do_render_blur_3d(re);
2045         else
2046                 do_render_3d(re);
2047
2048         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2049         rr1= re->result;
2050         re->result= NULL;
2051         BLI_rw_mutex_unlock(&re->resultmutex);
2052         
2053         /* second field */
2054         if(!re->test_break(re->tbh)) {
2055                 
2056                 re->i.curfield= 2;      /* stats */
2057                 
2058                 re->flag |= R_SEC_FIELD;
2059                 if((re->r.mode & R_FIELDSTILL)==0) {
2060                         re->field_offs = 0.5f;
2061                 }
2062                 RE_SetCamera(re, camera);
2063                 if(re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE)==0)
2064                         do_render_blur_3d(re);
2065                 else
2066                         do_render_3d(re);
2067                 re->flag &= ~R_SEC_FIELD;
2068                 
2069                 re->field_offs = 0.0f;
2070                 
2071                 rr2= re->result;
2072         }
2073         
2074         /* allocate original height new buffers */
2075         re->winy *= 2;
2076         re->recty *= 2;
2077         re->disprect.ymin *= 2;
2078         re->disprect.ymax *= 2;
2079
2080         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2081         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2082
2083         if(rr2) {
2084                 if(re->r.mode & R_ODDFIELD)
2085                         merge_renderresult_fields(re->result, rr2, rr1);
2086                 else
2087                         merge_renderresult_fields(re->result, rr1, rr2);
2088                 
2089                 RE_FreeRenderResult(rr2);
2090         }
2091
2092         RE_FreeRenderResult(rr1);
2093         
2094         re->i.curfield= 0;      /* stats */
2095         
2096         /* weak... the display callback wants an active renderlayer pointer... */
2097         re->result->renlay= render_get_active_layer(re, re->result);
2098
2099         BLI_rw_mutex_unlock(&re->resultmutex);
2100
2101         re->display_draw(re->ddh, re->result, NULL);
2102 }
2103
2104 /* main render routine, no compositing */
2105 static void do_render_fields_blur_3d(Render *re)
2106 {
2107         Object *camera= RE_GetCamera(re);
2108         /* also check for camera here */
2109         if(camera == NULL) {
2110                 printf("ERROR: Cannot render, no camera\n");
2111                 G.afbreek= 1;
2112                 return;
2113         }
2114
2115         /* now use renderdata and camera to set viewplane */
2116         RE_SetCamera(re, camera);
2117         
2118         if(re->r.mode & R_FIELDS)
2119                 do_render_fields_3d(re);
2120         else if(re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE)==0)
2121                 do_render_blur_3d(re);
2122         else
2123                 do_render_3d(re);
2124         
2125         /* when border render, check if we have to insert it in black */
2126         if(re->result) {
2127                 if(re->r.mode & R_BORDER) {
2128                         if((re->r.mode & R_CROP)==0) {
2129                                 RenderResult *rres;
2130                                 
2131                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2132
2133                                 /* sub-rect for merge call later on */
2134                                 re->result->tilerect= re->disprect;
2135                                 
2136                                 /* this copying sequence could become function? */
2137                                 /* weak is: it chances disprect from border */
2138                                 re->disprect.xmin= re->disprect.ymin= 0;
2139                                 re->disprect.xmax= re->winx;
2140                                 re->disprect.ymax= re->winy;
2141                                 re->rectx= re->winx;
2142                                 re->recty= re->winy;
2143                                 
2144                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2145                                 
2146                                 merge_render_result(rres, re->result);
2147                                 RE_FreeRenderResult(re->result);
2148                                 re->result= rres;
2149                                 
2150                                 /* weak... the display callback wants an active renderlayer pointer... */
2151                                 re->result->renlay= render_get_active_layer(re, re->result);
2152                                 
2153                                 BLI_rw_mutex_unlock(&re->resultmutex);
2154                 
2155                                 re->display_init(re->dih, re->result);
2156                                 re->display_draw(re->ddh, re->result, NULL);
2157                         }
2158                         else {
2159                                 /* set offset (again) for use in compositor, disprect was manipulated. */
2160                                 re->result->xof= 0;
2161                                 re->result->yof= 0;
2162                         }
2163                 }
2164         }
2165 }
2166
2167
2168 /* within context of current Render *re, render another scene.
2169    it uses current render image size and disprect, but doesn't execute composite
2170 */
2171 static void render_scene(Render *re, Scene *sce, int cfra)
2172 {
2173         Render *resc= RE_NewRender(sce->id.name);
2174         int winx= re->winx, winy= re->winy;
2175         
2176         sce->r.cfra= cfra;
2177
2178         scene_camera_switch_update(sce);
2179
2180         /* exception: scene uses own size (unfinished code) */
2181         if(0) {
2182                 winx= (sce->r.size*sce->r.xsch)/100;
2183                 winy= (sce->r.size*sce->r.ysch)/100;
2184         }
2185         
2186         /* initial setup */
2187         RE_InitState(resc, re, &sce->r, NULL, winx, winy, &re->disprect);
2188         
2189         /* still unsure entity this... */
2190         resc->main= re->main;
2191         resc->scene= sce;
2192         resc->lay= sce->lay;
2193         
2194         /* ensure scene has depsgraph, base flags etc OK */
2195         set_scene_bg(re->main, sce);
2196
2197         /* copy callbacks */
2198         resc->display_draw= re->display_draw;
2199         resc->ddh= re->ddh;
2200         resc->test_break= re->test_break;
2201         resc->tbh= re->tbh;
2202         resc->stats_draw= re->stats_draw;
2203         resc->sdh= re->sdh;
2204         
2205         do_render_fields_blur_3d(resc);
2206 }
2207
2208 /* helper call to detect if this scene needs a render, or if there's a any render layer to render */
2209 static int composite_needs_render(Scene *sce, int this_scene)
2210 {
2211         bNodeTree *ntree= sce->nodetree;
2212         bNode *node;
2213         
2214         if(ntree==NULL) return 1;
2215         if(sce->use_nodes==0) return 1;
2216         if((sce->r.scemode & R_DOCOMP)==0) return 1;
2217         
2218         for(node= ntree->nodes.first; node; node= node->next) {
2219                 if(node->type==CMP_NODE_R_LAYERS)
2220                         if(this_scene==0 || node->id==NULL || node->id==&sce->id)
2221                                 return 1;
2222         }
2223         return 0;
2224 }
2225
2226 static void tag_scenes_for_render(Render *re)
2227 {
2228         bNode *node;
2229         Scene *sce;
2230         
2231         for(sce= re->main->scene.first; sce; sce= sce->id.next)
2232                 sce->id.flag &= ~LIB_DOIT;
2233         
2234         if(RE_GetCamera(re) && composite_needs_render(re->scene, 1))
2235                 re->scene->id.flag |= LIB_DOIT;
2236         
2237         if(re->scene->nodetree==NULL) return;
2238         
2239         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
2240         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2241                 if(node->type==CMP_NODE_R_LAYERS) {
2242                         if(node->id) {
2243                                 if(node->id != (ID *)re->scene)
2244                                         node->id->flag |= LIB_DOIT;
2245                         }
2246                 }
2247         }
2248         
2249 }
2250
2251 static void ntree_render_scenes(Render *re)
2252 {
2253         bNode *node;
2254         int cfra= re->scene->r.cfra;
2255         int restore_scene= 0;
2256         
2257         if(re->scene->nodetree==NULL) return;
2258         
2259         tag_scenes_for_render(re);
2260         
2261         /* now foreach render-result node tagged we do a full render */
2262         /* results are stored in a way compisitor will find it */
2263         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2264                 if(node->type==CMP_NODE_R_LAYERS) {
2265                         if(node->id && node->id != (ID *)re->scene) {
2266                                 if(node->id->flag & LIB_DOIT) {
2267                                         Scene *scene = (Scene*)node->id;
2268
2269                                         render_scene(re, scene, cfra);
2270                                         restore_scene= (scene != re->scene);
2271                                         node->id->flag &= ~LIB_DOIT;
2272                                         
2273                                         NodeTagChanged(re->scene->nodetree, node);
2274                                 }
2275                         }
2276                 }
2277         }
2278
2279         /* restore scene if we rendered another last */
2280         if(restore_scene)
2281                 set_scene_bg(re->main, re->scene);
2282 }
2283
2284 /* bad call... need to think over proper method still */
2285 static void render_composit_stats(void *UNUSED(arg), char *str)
2286 {
2287         R.i.infostr= str;
2288         R.stats_draw(R.sdh, &R.i);
2289         R.i.infostr= NULL;
2290 }
2291
2292
2293 /* invokes Freestyle stroke rendering */
2294 static void add_freestyle(Render *re)
2295 {
2296         SceneRenderLayer *srl;
2297         LinkData *link;
2298
2299         FRS_init_stroke_rendering(re);
2300
2301         for(srl= (SceneRenderLayer *)re->scene->r.layers.first; srl; srl= srl->next) {
2302
2303                 link = (LinkData *)MEM_callocN(sizeof(LinkData), "LinkData to Freestyle render");
2304                 BLI_addtail(&re->freestyle_renders, link);
2305
2306                 if( FRS_is_freestyle_enabled(srl) ) {
2307                         link->data = (void *)FRS_do_stroke_rendering(re, srl);
2308                 }
2309         }
2310
2311         FRS_finish_stroke_rendering(re);
2312 }
2313
2314 /* merges the results of Freestyle stroke rendering into a given render result */
2315 static void composite_freestyle_renders(Render *re, int sample)
2316 {
2317         Render *freestyle_render;
2318         SceneRenderLayer *srl;
2319         LinkData *link;
2320
2321         link = (LinkData *)re->freestyle_renders.first;
2322         for(srl= (SceneRenderLayer *)re->scene->r.layers.first; srl; srl= srl->next) {
2323                 if( FRS_is_freestyle_enabled(srl) ) {
2324                         freestyle_render = (Render *)link->data;
2325                         read_render_result(freestyle_render, sample);
2326                         FRS_composite_result(re, srl, freestyle_render);
2327                         RE_FreeRenderResult(freestyle_render->result);
2328                         freestyle_render->result = NULL;
2329                 }
2330                 link = link->next;
2331         }
2332 }
2333
2334 /* releases temporary scenes and renders for Freestyle stroke rendering */
2335 static void free_all_freestyle_renders(void)
2336 {
2337         Render *re1, *freestyle_render;
2338         LinkData *link;
2339
2340         for(re1= RenderGlobal.renderlist.first; re1; re1= re1->next) {
2341                 for (link = (LinkData *)re1->freestyle_renders.first; link; link = link->next) {
2342                         if (link->data) {
2343                                 freestyle_render = (Render *)link->data;
2344                                 free_libblock(&G.main->scene, freestyle_render->scene);
2345                                 RE_FreeRender(freestyle_render);
2346                         }
2347                 }
2348                 BLI_freelistN( &re1->freestyle_renders );
2349         }
2350 }
2351
2352
2353 /* reads all buffers, calls optional composite, merges in first result->rectf */
2354 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
2355 {
2356         float *rectf, filt[3][3];
2357         int sample;
2358         
2359         /* interaction callbacks */
2360         if(ntree) {
2361                 ntree->stats_draw= render_composit_stats;
2362                 ntree->test_break= re->test_break;
2363                 ntree->progress= re->progress;
2364                 ntree->sdh= re->sdh;
2365                 ntree->tbh= re->tbh;
2366                 ntree->prh= re->prh;
2367         }
2368         
2369         /* filtmask needs it */
2370         R= *re;
2371         
2372         /* we accumulate in here */
2373         rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
2374         
2375         for(sample=0; sample<re->r.osa; sample++) {
2376                 Render *re1;
2377                 RenderResult rres;
2378                 int x, y, mask;
2379                 
2380                 /* enable full sample print */
2381                 R.i.curfsa= sample+1;
2382                 
2383                 /* set all involved renders on the samplebuffers (first was done by render itself, but needs tagged) */
2384                 /* also function below assumes this */
2385                         
2386                 tag_scenes_for_render(re);
2387                 for(re1= RenderGlobal.renderlist.first; re1; re1= re1->next) {
2388                         if(re1->scene->id.flag & LIB_DOIT) {
2389                                 if(re1->r.scemode & R_FULL_SAMPLE) {
2390                                         if(sample) {
2391                                                 read_render_result(re1, sample);
2392                                                 composite_freestyle_renders(re1, sample);
2393                                         }
2394                                         ntreeCompositTagRender(re1->scene); /* ensure node gets exec to put buffers on stack */
2395                                 }
2396                         }
2397                 }
2398                 
2399                 /* composite */
2400                 if(ntree) {
2401                         ntreeCompositTagRender(re->scene);
2402                         ntreeCompositTagAnimated(ntree);
2403                         
2404                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2405                 }
2406                 
2407                 /* ensure we get either composited result or the active layer */
2408                 RE_AcquireResultImage(re, &rres);
2409                 
2410                 /* accumulate with filter, and clip */
2411                 mask= (1<<sample);
2412                 mask_array(mask, filt);
2413
2414                 for(y=0; y<re->recty; y++) {
2415                         float *rf= rectf + 4*y*re->rectx;
2416                         float *col= rres.rectf + 4*y*re->rectx;
2417                                 
2418                         for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
2419                                 /* clamping to 1.0 is needed for correct AA */
2420                                 if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
2421                                 if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
2422                                 if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
2423                                 
2424                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
2425                         }
2426                 }
2427                 
2428                 RE_ReleaseResultImage(re);
2429
2430                 /* show stuff */
2431                 if(sample!=re->osa-1) {
2432                         /* weak... the display callback wants an active renderlayer pointer... */
2433                         re->result->renlay= render_get_active_layer(re, re->result);
2434                         re->display_draw(re->ddh, re->result, NULL);
2435                 }
2436                 
2437                 if(re->test_break(re->tbh))
2438                         break;
2439         }
2440         
2441         /* clear interaction callbacks */
2442         if(ntree) {
2443                 ntree->stats_draw= NULL;
2444                 ntree->test_break= NULL;
2445                 ntree->progress= NULL;
2446                 ntree->tbh= ntree->sdh= ntree->prh= NULL;
2447         }
2448         
2449         /* disable full sample print */
2450         R.i.curfsa= 0;
2451         
2452         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2453         if(re->result->rectf) 
2454                 MEM_freeN(re->result->rectf);
2455         re->result->rectf= rectf;
2456         BLI_rw_mutex_unlock(&re->resultmutex);
2457 }
2458
2459 /* called externally, via compositor */
2460 void RE_MergeFullSample(Render *re, Main *bmain, Scene *sce, bNodeTree *ntree)
2461 {
2462         Scene *scene;
2463         bNode *node;
2464
2465         /* default start situation */
2466         G.afbreek= 0;
2467         
2468         re->main= bmain;
2469         re->scene= sce;
2470         
2471         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
2472         
2473         /* tag scenes unread */
2474         for(scene= re->main->scene.first; scene; scene= scene->id.next) 
2475                 scene->id.flag |= LIB_DOIT;
2476         
2477         for(node= ntree->nodes.first; node; node= node->next) {
2478                 if(node->type==CMP_NODE_R_LAYERS) {
2479                         Scene *nodescene= (Scene *)node->id;
2480                         
2481                         if(nodescene==NULL) nodescene= sce;
2482                         if(nodescene->id.flag & LIB_DOIT) {
2483                                 nodescene->r.mode |= R_OSA;     /* render struct needs tables */
2484                                 RE_ReadRenderResult(sce, nodescene);
2485                                 nodescene->id.flag &= ~LIB_DOIT;
2486                         }
2487                 }
2488         }
2489         
2490         /* own render result should be read/allocated */
2491         if(re->scene->id.flag & LIB_DOIT) {
2492                 RE_ReadRenderResult(re->scene, re->scene);
2493                 re->scene->id.flag &= ~LIB_DOIT;
2494         }
2495         
2496         /* and now we can draw (result is there) */
2497         re->display_init(re->dih, re->result);
2498         re->display_clear(re->dch, re->result);
2499         
2500         do_merge_fullsample(re, ntree);
2501 }
2502
2503 /* returns fully composited render-result on given time step (in RenderData) */
2504 static void do_render_composite_fields_blur_3d(Render *re)
2505 {
2506         bNodeTree *ntree= re->scene->nodetree;
2507         int update_newframe=0;
2508         
2509         /* INIT seeding, compositor can use random texture */
2510         BLI_srandom(re->r.cfra);
2511         
2512         if(composite_needs_render(re->scene, 1)) {
2513                 /* save memory... free all cached images */
2514                 ntreeFreeCache(ntree);
2515                 
2516                 do_render_fields_blur_3d(re);
2517         } 
2518         else {
2519                 /* ensure new result gets added, like for regular renders */
2520                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2521                 
2522                 RE_FreeRenderResult(re->result);
2523                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2524
2525                 BLI_rw_mutex_unlock(&re->resultmutex);
2526                 
2527                 /* scene render process already updates animsys */
2528                 update_newframe = 1;
2529         }
2530         
2531         /* swap render result */
2532         if(re->r.scemode & R_SINGLE_LAYER)
2533                 pop_render_result(re);
2534         
2535         if(!re->test_break(re->tbh)) {
2536                 
2537                 if(ntree) {
2538                         ntreeCompositTagRender(re->scene);
2539                         ntreeCompositTagAnimated(ntree);
2540                 }
2541                 
2542                 if(ntree && re->r.scemode & R_DOCOMP) {
2543                         /* checks if there are render-result nodes that need scene */
2544                         if((re->r.scemode & R_SINGLE_LAYER)==0)
2545                                 ntree_render_scenes(re);
2546                         
2547                         if(!re->test_break(re->tbh)) {
2548                                 ntree->stats_draw= render_composit_stats;
2549                                 ntree->test_break= re->test_break;
2550                                 ntree->progress= re->progress;
2551                                 ntree->sdh= re->sdh;
2552                                 ntree->tbh= re->tbh;
2553                                 ntree->prh= re->prh;
2554                                 
2555                                 /* in case it was never initialized */
2556                                 R.sdh= re->sdh;
2557                                 R.stats_draw= re->stats_draw;
2558                                 
2559                                 if (update_newframe)
2560                                         scene_update_for_newframe(re->main, re->scene, re->lay);
2561                                 
2562                                 if(re->r.scemode & R_FULL_SAMPLE) 
2563                                         do_merge_fullsample(re, ntree);
2564                                 else {
2565                                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2566                                 }
2567                                 
2568                                 ntree->stats_draw= NULL;
2569                                 ntree->test_break= NULL;
2570                                 ntree->progress= NULL;
2571                                 ntree->tbh= ntree->sdh= ntree->prh= NULL;
2572                         }
2573                 }
2574                 else if(re->r.scemode & R_FULL_SAMPLE)
2575                         do_merge_fullsample(re, NULL);
2576         }
2577
2578         free_all_freestyle_renders();
2579
2580         /* weak... the display callback wants an active renderlayer pointer... */
2581         re->result->renlay= render_get_active_layer(re, re->result);
2582         re->display_draw(re->ddh, re->result, NULL);
2583 }
2584
2585 static void renderresult_stampinfo(Render *re)
2586 {
2587         RenderResult rres;
2588
2589         /* this is the basic trick to get the displayed float or char rect from render result */
2590         RE_AcquireResultImage(re, &rres);
2591         BKE_stamp_buf(re->scene, RE_GetCamera(re), (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
2592         RE_ReleaseResultImage(re);
2593 }
2594
2595 static int seq_render_active(Render *re)
2596 {
2597         Editing *ed;
2598         Sequence *seq;
2599
2600         ed = re->scene->ed;
2601         
2602         if (!(re->r.scemode & R_DOSEQ) || !ed || !ed->seqbase.first)
2603                 return 0;
2604         
2605         for (seq= ed->seqbase.first; seq; seq= seq->next) {
2606                 if (seq->type != SEQ_SOUND)
2607                         return 1;
2608         }
2609         
2610         return 0;
2611 }
2612
2613 static void do_render_seq(Render * re)
2614 {
2615         static int recurs_depth = 0;
2616         struct ImBuf *ibuf;
2617         RenderResult *rr; /* don't assign re->result here as it might change during give_ibuf_seq */
2618         int cfra = re->r.cfra;
2619         SeqRenderData context;
2620
2621         re->i.cfra= cfra;
2622
2623         if(recurs_depth==0) {
2624                 /* otherwise sequencer animation isnt updated */
2625                 BKE_animsys_evaluate_all_animation(re->main, re->scene, (float)cfra); // XXX, was BKE_curframe(re->scene)
2626         }
2627
2628         recurs_depth++;
2629
2630         context = seq_new_render_data(re->main, re->scene,
2631                                       re->result->rectx, re->result->recty, 
2632                                       100);
2633
2634         ibuf = give_ibuf_seq(context, cfra, 0);
2635
2636         recurs_depth--;
2637
2638         rr = re->result;
2639         
2640         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2641
2642         if(ibuf) {
2643                 if(ibuf->rect_float) {
2644                         if (!rr->rectf)
2645                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
2646                         
2647                         /* color management: when off ensure rectf is non-lin, since thats what the internal
2648                          * render engine delivers */
2649                         if(re->r.color_mgt_flag & R_COLOR_MANAGEMENT) {
2650                                 if(ibuf->profile == IB_PROFILE_LINEAR_RGB)
2651                                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2652                                 else
2653                                         srgb_to_linearrgb_rgba_rgba_buf(rr->rectf, ibuf->rect_float, rr->rectx*rr->recty);
2654                                         
2655                         }
2656                         else {
2657                                 if(ibuf->profile != IB_PROFILE_LINEAR_RGB)
2658                                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2659                                 else
2660                                         linearrgb_to_srgb_rgba_rgba_buf(rr->rectf, ibuf->rect_float, rr->rectx*rr->recty);
2661                         }
2662                         
2663                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
2664                            can hang around when sequence render has rendered a 32 bits one before */
2665                         if(rr->rect32) {
2666                                 MEM_freeN(rr->rect32);
2667                                 rr->rect32= NULL;
2668                         }
2669                 }
2670                 else if(ibuf->rect) {
2671                         if (!rr->rect32)
2672                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2673
2674                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
2675
2676                         /* if (ibuf->zbuf) { */
2677                         /*      if (R.rectz) freeN(R.rectz); */
2678                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
2679                         /* } */
2680
2681                         /* Same things as above, old rectf can hang around from previous render. */
2682                         if(rr->rectf) {
2683                                 MEM_freeN(rr->rectf);
2684                                 rr->rectf= NULL;
2685                         }
2686                 }
2687                 
2688                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
2689                         Editing * ed = re->scene->ed;
2690                         if (ed) {
2691                                 free_imbuf_seq(re->scene, &ed->seqbase, TRUE, TRUE);
2692                         }
2693                 }
2694                 IMB_freeImBuf(ibuf);
2695         }
2696         else {
2697                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
2698                 if (rr->rectf)
2699                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
2700                 else if (rr->rect32)
2701                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
2702                 else
2703                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2704         }
2705
2706         BLI_rw_mutex_unlock(&re->resultmutex);
2707
2708         /* just in case this flag went missing at some point */
2709         re->r.scemode |= R_DOSEQ;
2710 }
2711
2712 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2713
2714 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2715 static void do_render_all_options(Render *re)
2716 {
2717         scene_camera_switch_update(re->scene);
2718
2719         re->i.starttime= PIL_check_seconds_timer();
2720
2721         /* ensure no images are in memory from previous animated sequences */
2722         BKE_image_all_free_anim_ibufs(re->r.cfra);
2723
2724         if(external_render_3d(re, 1)) {
2725                 /* in this case external render overrides all */
2726         }
2727         else if(seq_render_active(re)) {
2728                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2729                 if(!re->test_break(re->tbh)) 
2730                         do_render_seq(re);
2731                 
2732                 re->stats_draw(re->sdh, &re->i);
2733                 re->display_draw(re->ddh, re->result, NULL);
2734         }
2735         else {
2736                 do_render_composite_fields_blur_3d(re);
2737         }
2738         
2739         /* for UI only */
2740         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2741         renderresult_add_names(re->result);
2742         BLI_rw_mutex_unlock(&re->resultmutex);
2743         
2744         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2745         
2746         re->stats_draw(re->sdh, &re->i);
2747         
2748         /* stamp image info here */
2749         if((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
2750                 renderresult_stampinfo(re);
2751                 re->display_draw(re->ddh, re->result, NULL);
2752         }
2753 }
2754
2755 static int check_valid_camera(Scene *scene, Object *camera_override)
2756 {
2757         int check_comp= 1;
2758
2759         if (camera_override == NULL && scene->camera == NULL)
2760                 scene->camera= scene_find_camera(scene);
2761
2762         if(scene->r.scemode&R_DOSEQ) {
2763                 if(scene->ed) {
2764                         Sequence *seq= scene->ed->seqbase.first;
2765
2766                         check_comp= 0;
2767
2768                         while(seq) {
2769                                 if(seq->type == SEQ_SCENE) {
2770                                         if(!seq->scene_camera) {
2771                                                 if(!seq->scene->camera && !scene_find_camera(seq->scene)) {
2772                                                         if(seq->scene == scene) {
2773                                                                 /* for current scene camera could be unneeded due to compisite nodes */
2774                                                                 check_comp= 1;
2775                                                         } else {
2776                                                                 /* for other scenes camera is necessary */
2777                                                                 return 0;
2778                                                         }
2779                                                 }
2780                                         }
2781                                 }
2782
2783                                 seq= seq->next;
2784                         }
2785                 }
2786         }
2787
2788         if(check_comp) { /* no sequencer or sequencer depends on compositor */
2789                 if(scene->r.scemode&R_DOCOMP && scene->use_nodes) {
2790                         bNode *node= scene->nodetree->nodes.first;
2791
2792                         while(node) {
2793                                 if(node->type == CMP_NODE_R_LAYERS) {
2794                                         Scene *sce= node->id ? (Scene*)node->id : scene;
2795
2796                                         if(!sce->camera && !scene_find_camera(sce)) {
2797                                                 /* all render layers nodes need camera */
2798                                                 return 0;
2799                                         }
2800                                 }
2801
2802                                 node= node->next;
2803                         }
2804                 } else {
2805                         return (camera_override != NULL || scene->camera != NULL);
2806                 }
2807         }
2808
2809         return 1;
2810 }
2811
2812 int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *reports)
2813 {
2814         SceneRenderLayer *srl;
2815         
2816         if(scene->r.mode & R_BORDER) {
2817                 if(scene->r.border.xmax <= scene->r.border.xmin ||
2818                    scene->r.border.ymax <= scene->r.border.ymin) {
2819                         BKE_report(reports, RPT_ERROR, "No border area selected.");
2820                         return 0;
2821                 }
2822         }
2823         
2824         if(scene->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2825                 char str[FILE_MAX];
2826                 
2827                 scene_unique_exr_name(scene, str, 0);
2828                 
2829                 if (BLI_is_writable(str)==0) {
2830                         BKE_report(reports, RPT_ERROR, "Can not save render buffers, check the temp default path");
2831                         return 0;
2832                 }
2833                 
2834                 /* no fullsample and edge */
2835                 if((scene->r.scemode & R_FULL_SAMPLE) && (scene->r.mode & R_EDGE)) {
2836                         BKE_report(reports, RPT_ERROR, "Full Sample doesn't support Edge Enhance");
2837                         return 0;
2838                 }
2839                 
2840         }
2841         else
2842                 scene->r.scemode &= ~R_FULL_SAMPLE;     /* clear to be sure */
2843         
2844         if(scene->r.scemode & R_DOCOMP) {
2845                 if(scene->use_nodes) {
2846                         bNodeTree *ntree= scene->nodetree;
2847                         bNode *node;
2848                 
2849                         if(ntree==NULL) {
2850                                 BKE_report(reports, RPT_ERROR, "No Nodetree in Scene");
2851                                 return 0;
2852                         }
2853                         
2854                         for(node= ntree->nodes.first; node; node= node->next)
2855                                 if(node->type==CMP_NODE_COMPOSITE)
2856                                         break;
2857                         
2858                         if(node==NULL) {
2859                                 BKE_report(reports, RPT_ERROR, "No Render Output Node in Scene");
2860                                 return 0;
2861                         }
2862                         
2863                         if(scene->r.scemode & R_FULL_SAMPLE) {
2864                                 if(composite_needs_render(scene, 0)==0) {
2865                                         BKE_report(reports, RPT_ERROR, "Full Sample AA not supported without 3d rendering");
2866                                         return 0;
2867                                 }
2868                         }
2869                 }
2870         }
2871         
2872          /* check valid camera, without camera render is OK (compo, seq) */
2873         if(!check_valid_camera(scene, camera_override)) {
2874                 BKE_report(reports, RPT_ERROR, "No camera");
2875                 return 0;
2876         }
2877         
2878         /* get panorama & ortho, only after camera is set */
2879         object_camera_mode(&scene->r, camera_override ? camera_override : scene->camera);
2880
2881         /* forbidden combinations */
2882         if(scene->r.mode & R_PANORAMA) {
2883                 if(scene->r.mode & R_ORTHO) {
2884                         BKE_report(reports, RPT_ERROR, "No Ortho render possible for Panorama");
2885                         return 0;
2886                 }
2887         }
2888
2889         /* layer flag tests */
2890         if(scene->r.scemode & R_SINGLE_LAYER) {
2891                 srl= BLI_findlink(&scene->r.layers, scene->r.actlay);
2892                 /* force layer to be enabled */
2893                 srl->layflag &= ~SCE_LAY_DISABLE;
2894         }
2895         
2896         for(srl= scene->r.layers.first; srl; srl= srl->next)
2897                 if(!(srl->layflag & SCE_LAY_DISABLE))
2898                         break;
2899         if(srl==NULL) {
2900                 BKE_report(reports, RPT_ERROR, "All RenderLayers are disabled");
2901                 return 0;
2902         }
2903         
2904         /* renderer */
2905         if(!ELEM(scene->r.renderer, R_INTERN, R_YAFRAY)) {
2906                 BKE_report(reports, RPT_ERROR, "Unknown render engine set");
2907                 return 0;
2908         }
2909
2910         return 1;
2911 }
2912
2913 static void validate_render_settings(Render *re)
2914 {
2915         if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2916                 /* no osa + fullsample won't work... */
2917                 if(re->r.osa==0)
2918                         re->r.scemode &= ~R_FULL_SAMPLE;
2919         } else re->r.scemode &= ~R_FULL_SAMPLE; /* clear to be sure */
2920 }
2921
2922 static void update_physics_cache(Render *re, Scene *scene, int UNUSED(anim_init))
2923 {
2924         PTCacheBaker baker;
2925
2926         baker.main = re->main;
2927         baker.scene = scene;
2928         baker.pid = NULL;
2929         baker.bake = 0;
2930         baker.render = 1;
2931         baker.anim_init = 1;
2932         baker.quick_step = 1;
2933         baker.break_test = re->test_break;
2934         baker.break_data = re->tbh;
2935         baker.progressbar = NULL;
2936
2937         BKE_ptcache_bake(&baker);
2938 }
2939 /* evaluating scene options for general Blender render */
2940 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)
2941 {
2942         int winx, winy;
2943         rcti disprect;
2944         
2945         /* r.xsch and r.ysch has the actual view window size
2946                 r.border is the clipping rect */
2947         
2948         /* calculate actual render result and display size */
2949         winx= (scene->r.size*scene->r.xsch)/100;
2950         winy= (scene->r.size*scene->r.ysch)/100;
2951         
2952         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2953         if(scene->r.mode & R_BORDER) {
2954                 disprect.xmin= scene->r.border.xmin*winx;
2955                 disprect.xmax= scene->r.border.xmax*winx;
2956                 
2957                 disprect.ymin= scene->r.border.ymin*winy;
2958                 disprect.ymax= scene->r.border.ymax*winy;
2959         }
2960         else {
2961                 disprect.xmin= disprect.ymin= 0;
2962                 disprect.xmax= winx;
2963                 disprect.ymax= winy;
2964         }
2965         
2966         re->main= bmain;
2967         re->scene= scene;
2968         re->camera_override= camera_override;
2969         re->lay= lay;
2970         
2971         /* not too nice, but it survives anim-border render */
2972         if(anim) {
2973                 re->disprect= disprect;
2974                 return 1;
2975         }
2976         
2977         /* check all scenes involved */
2978         tag_scenes_for_render(re);
2979
2980         /*
2981          * Disabled completely for now,
2982          * can be later set as render profile option
2983          * and default for background render.
2984         */
2985         if(0) {
2986                 /* make sure dynamics are up to date */
2987                 update_physics_cache(re, scene, anim_init);
2988         }
2989         
2990         if(srl || scene->r.scemode & R_SINGLE_LAYER)
2991                 push_render_result(re);
2992         
2993         RE_InitState(re, NULL, &scene->r, srl, winx, winy, &disprect);
2994         if(!re->ok)  /* if an error was printed, abort */
2995                 return 0;
2996         
2997         /* initstate makes new result, have to send changed tags around */
2998         ntreeCompositTagRender(re->scene);
2999
3000         validate_render_settings(re);
3001
3002         re->display_init(re->dih, re->result);
3003         re->display_clear(re->dch, re->result);
3004         
3005         return 1;
3006 }
3007
3008 void RE_SetReports(Render *re, ReportList *reports)
3009 {
3010         re->reports= reports;
3011 }
3012
3013 /* general Blender frame render call */
3014 void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int frame, const short write_still)
3015 {
3016         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
3017         G.rendering= 1;
3018         
3019         scene->r.cfra= frame;
3020         
3021         if(render_initialize_from_main(re, bmain, scene, srl, camera_override, lay, 0, 0)) {
3022                 MEM_reset_peak_memory();
3023
3024                 BLI_exec_cb(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
3025
3026                 do_render_all_options(re);
3027                 
3028                 if(write_still && !G.afbreek) {
3029                         if(BKE_imtype_is_movie(scene->r.imtype)) {
3030                                 /* operator checks this but incase its called from elsewhere */
3031                                 printf("Error: cant write single images with a movie format!\n");
3032                         }
3033                         else {
3034                                 char name[FILE_MAX];
3035                                 BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype, scene->r.scemode & R_EXTENSION, FALSE);
3036         
3037                                 /* reports only used for Movie */
3038                                 do_write_image_or_movie(re, scene, NULL, name);
3039                         }
3040                 }
3041
3042                 BLI_exec_cb(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
3043         }
3044
3045         /* UGLY WARNING */
3046         G.rendering= 0;
3047 }
3048
3049 void RE_RenderFreestyleStrokes(Render *re, Main *bmain, Scene *scene)
3050 {
3051         re->result_ok= 0;
3052         if(render_initialize_from_main(re, bmain, scene, NULL, NULL, scene->lay, 0, 0)) {
3053                 do_render_fields_blur_3d(re);
3054         }
3055         re->result_ok= 1;
3056 }
3057
3058 static int do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh, const char *name_override)
3059 {
3060         char name[FILE_MAX];
3061         RenderResult rres;
3062         Object *camera= RE_GetCamera(re);
3063         int ok= 1;
3064         
3065         RE_AcquireResultImage(re, &rres);
3066
3067         /* write movie or image */
3068         if(BKE_imtype_is_movie(scene->r.imtype)) {
3069                 int dofree = 0;
3070                 /* note; the way it gets 32 bits rects is weak... */
3071                 if(rres.rect32==NULL) {
3072                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
3073                         dofree = 1;
3074                 }
3075                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
3076                 ok= mh->append_movie(&re->r, scene->r.cfra, rres.rect32, rres.rectx, rres.recty, re->reports);
3077                 if(dofree) {
3078                         MEM_freeN(rres.rect32);
3079                 }
3080                 printf("Append frame %d", scene->r.cfra);
3081         } 
3082         else {
3083                 if(name_override)
3084                         BLI_strncpy(name, name_override, sizeof(name));
3085                 else
3086                         BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype, scene->r.scemode & R_EXTENSION, TRUE);
3087                 
3088                 if(re->r.imtype==R_MULTILAYER) {
3089                         if(re->result) {
3090                                 RE_WriteRenderResult(re->reports, re->result, name, scene->r.quality);
3091                                 printf("Saved: %s", name);
3092                         }
3093                 }
3094                 else {
3095                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0);
3096                         
3097                         /* if not exists, BKE_write_ibuf makes one */
3098                         ibuf->rect= (unsigned int *)rres.rect32;    
3099                         ibuf->rect_float= rres.rectf;
3100                         ibuf->zbuf_float= rres.rectz;
3101                         
3102                         /* float factor for random dither, imbuf takes care of it */
3103                         ibuf->dither= scene->r.dither_intensity;
3104                         
3105                         /* prepare to gamma correct to sRGB color space */
3106                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) {
3107                                 /* sequence editor can generate 8bpc render buffers */
3108                                 if (ibuf->rect) {
3109                                         ibuf->profile = IB_PROFILE_SRGB;
3110                                         if (ELEM(scene->r.imtype, R_OPENEXR, R_RADHDR))
3111                                                 IMB_float_from_rect(ibuf);
3112                                 } else {                                
3113                                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
3114                                 }
3115                         }
3116
3117                         /* color -> greyscale */
3118                         /* editing directly would alter the render view */
3119                         if(scene->r.planes == 8) {
3120                                 ImBuf *ibuf_bw= IMB_dupImBuf(ibuf);
3121                                 IMB_color_to_bw(ibuf_bw);
3122                                 IMB_freeImBuf(ibuf);
3123                                 ibuf= ibuf_bw;
3124                         }
3125
3126                         ok= BKE_write_ibuf_stamp(scene, camera, ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
3127                         
3128                         if(ok==0) {
3129                                 printf("Render error: cannot save %s\n", name);
3130                         }
3131                         else printf("Saved: %s", name);
3132                         
3133                         /* optional preview images for exr */
3134                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
3135                                 if(BLI_testextensie(name, ".exr")) 
3136                                         name[strlen(name)-4]= 0;
3137                                 BKE_add_image_extension(name, R_JPEG90);
3138                                 ibuf->depth= 24; 
3139                                 BKE_write_ibuf_stamp(scene, camera, ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
3140                                 printf("\nSaved: %s", name);
3141                         }
3142                         
3143                                         /* imbuf knows which rects are not part of ibuf */
3144                         IMB_freeImBuf(ibuf);
3145                 }
3146         }
3147         
3148         RE_ReleaseResultImage(re);
3149
3150         BLI_timestr(re->i.lastframetime, name);
3151         printf(" Time: %s\n", name);
3152         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
3153
3154         return ok;
3155 }
3156
3157 /* saves images to disk */
3158 void RE_BlenderAnim(Render *re, Main *bmain, Scene *scene, Object *camera_override, unsigned int lay, int sfra, int efra, int tfra)