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