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