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