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