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