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