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