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