f2015bcd4948ac8ea11f1b63753efb833a6a0777
[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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2006 Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <math.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "DNA_group_types.h"
35 #include "DNA_image_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_userdef_types.h"
40
41 #include "BKE_global.h"
42 #include "BKE_image.h"
43 #include "BKE_main.h"
44 #include "BKE_node.h"
45 #include "BKE_object.h"
46 #include "BKE_scene.h"
47 #include "BKE_writeavi.h"       /* <------ should be replaced once with generic movie module */
48
49 #include "MEM_guardedalloc.h"
50
51 #include "BLI_arithb.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_rand.h"
54 #include "BLI_threads.h"
55
56 #include "PIL_time.h"
57 #include "IMB_imbuf.h"
58 #include "IMB_imbuf_types.h"
59
60 #include "intern/openexr/openexr_multi.h"
61
62 #include "RE_pipeline.h"
63 #include "radio.h"
64
65 #include "BSE_sequence.h"  /* <----------------- bad!!! */
66
67 #ifndef DISABLE_YAFRAY
68 /* yafray: include for yafray export/render */
69 #include "YafRay_Api.h"
70
71 #endif /* disable yafray */
72
73 /* internal */
74 #include "render_types.h"
75 #include "renderpipeline.h"
76 #include "renderdatabase.h"
77 #include "rendercore.h"
78 #include "envmap.h"
79 #include "initrender.h"
80 #include "shadbuf.h"
81 #include "zbuf.h"
82
83
84 /* render flow
85
86 1) Initialize state
87 - state data, tables
88 - movie/image file init
89 - everything that doesn't change during animation
90
91 2) Initialize data
92 - camera, world, matrices
93 - make render verts, faces, halos, strands
94 - everything can change per frame/field
95
96 3) Render Processor
97 - multiple layers
98 - tiles, rect, baking
99 - layers/tiles optionally to disk or directly in Render Result
100
101 4) Composit Render Result
102 - also read external files etc
103
104 5) Image Files
105 - save file or append in movie
106
107 */
108
109
110 /* ********* globals ******** */
111
112 /* here we store all renders */
113 static struct ListBase RenderList= {NULL, NULL};
114
115 /* hardcopy of current render, used while rendering for speed */
116 Render R;
117
118 /* commandline thread override */
119 static int commandline_threads= 0;
120
121 /* ********* alloc and free ******** */
122
123
124 static volatile int g_break= 0;
125 static int thread_break(void)
126 {
127         return g_break;
128 }
129
130 /* default callbacks, set in each new render */
131 static void result_nothing(RenderResult *rr) {}
132 static void result_rcti_nothing(RenderResult *rr, volatile struct rcti *rect) {}
133 static void stats_nothing(RenderStats *rs) {}
134 static void int_nothing(int val) {}
135 static int void_nothing(void) {return 0;}
136 static void print_error(char *str) {printf("ERROR: %s\n", str);}
137
138 static void stats_background(RenderStats *rs)
139 {
140         extern unsigned long mem_in_use;
141         float megs_used_memory= mem_in_use/(1024.0*1024.0);
142         char str[400], *spos= str;
143         
144         if(rs->convertdone) {
145                 
146                 spos+= sprintf(spos, "Fra:%d Mem:%.2fM ", G.scene->r.cfra, megs_used_memory);
147                 
148                 if(rs->curfield)
149                         spos+= sprintf(spos, "Field %d ", rs->curfield);
150                 if(rs->curblur)
151                         spos+= sprintf(spos, "Blur %d ", rs->curblur);
152                 
153                 if(rs->infostr) {
154                         spos+= sprintf(spos, "| %s", rs->infostr);
155                 }
156                 else {
157                         if(rs->tothalo)
158                                 spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
159                         else 
160                                 spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->totlamp);
161                 }
162                 printf(str); printf("\n");
163         }       
164 }
165
166 void RE_FreeRenderResult(RenderResult *res)
167 {
168         if(res==NULL) return;
169
170         while(res->layers.first) {
171                 RenderLayer *rl= res->layers.first;
172                 
173                 if(rl->rectf) MEM_freeN(rl->rectf);
174                 /* acolrect is optionally allocated in shade_tile, only free here since it can be used for drawing */
175                 if(rl->acolrect) MEM_freeN(rl->acolrect);
176                 
177                 while(rl->passes.first) {
178                         RenderPass *rpass= rl->passes.first;
179                         if(rpass->rect) MEM_freeN(rpass->rect);
180                         BLI_remlink(&rl->passes, rpass);
181                         MEM_freeN(rpass);
182                 }
183                 BLI_remlink(&res->layers, rl);
184                 MEM_freeN(rl);
185         }
186         
187         if(res->rect32)
188                 MEM_freeN(res->rect32);
189         if(res->rectz)
190                 MEM_freeN(res->rectz);
191         if(res->rectf)
192                 MEM_freeN(res->rectf);
193         
194         MEM_freeN(res);
195 }
196
197 /* all layers except the active one get temporally pushed away */
198 static void push_render_result(Render *re)
199 {
200         /* officially pushed result should be NULL... error can happen with do_seq */
201         RE_FreeRenderResult(re->pushedresult);
202         
203         re->pushedresult= re->result;
204         re->result= NULL;
205 }
206
207 /* if scemode is R_SINGLE_LAYER, at end of rendering, merge the both render results */
208 static void pop_render_result(Render *re)
209 {
210         
211         if(re->result==NULL) {
212                 printf("pop render result error; no current result!\n");
213                 return;
214         }
215         if(re->pushedresult) {
216                 if(re->pushedresult->rectx==re->result->rectx && re->pushedresult->recty==re->result->recty) {
217                         /* find which layer in pushedresult should be replaced */
218                         SceneRenderLayer *srl;
219                         RenderLayer *rlpush;
220                         RenderLayer *rl= re->result->layers.first;
221                         int nr;
222                         
223                         /* render result should be empty after this */
224                         BLI_remlink(&re->result->layers, rl);
225                         
226                         /* reconstruct render result layers */
227                         for(nr=0, srl= re->scene->r.layers.first; srl; srl= srl->next, nr++) {
228                                 if(nr==re->r.actlay)
229                                         BLI_addtail(&re->result->layers, rl);
230                                 else {
231                                         rlpush= RE_GetRenderLayer(re->pushedresult, srl->name);
232                                         if(rlpush) {
233                                                 BLI_remlink(&re->pushedresult->layers, rlpush);
234                                                 BLI_addtail(&re->result->layers, rlpush);
235                                         }
236                                 }
237                         }
238                 }
239                 
240                 RE_FreeRenderResult(re->pushedresult);
241                 re->pushedresult= NULL;
242         }
243 }
244
245 /* NOTE: OpenEXR only supports 32 chars for layer+pass names
246    In blender we now use max 10 chars for pass, max 20 for layer */
247 static char *get_pass_name(int passtype, int channel)
248 {
249         
250         if(passtype == SCE_PASS_COMBINED) {
251                 if(channel==-1) return "Combined";
252                 if(channel==0) return "Combined.R";
253                 if(channel==1) return "Combined.G";
254                 if(channel==2) return "Combined.B";
255                 return "Combined.A";
256         }
257         if(passtype == SCE_PASS_Z) {
258                 if(channel==-1) return "Depth";
259                 return "Depth.Z";
260         }
261         if(passtype == SCE_PASS_VECTOR) {
262                 if(channel==-1) return "Vector";
263                 if(channel==0) return "Vector.X";
264                 if(channel==1) return "Vector.Y";
265                 if(channel==2) return "Vector.Z";
266                 return "Vector.W";
267         }
268         if(passtype == SCE_PASS_NORMAL) {
269                 if(channel==-1) return "Normal";
270                 if(channel==0) return "Normal.X";
271                 if(channel==1) return "Normal.Y";
272                 return "Normal.Z";
273         }
274         if(passtype == SCE_PASS_UV) {
275                 if(channel==-1) return "UV";
276                 if(channel==0) return "UV.U";
277                 if(channel==1) return "UV.V";
278                 return "UV.A";
279         }
280         if(passtype == SCE_PASS_RGBA) {
281                 if(channel==-1) return "Color";
282                 if(channel==0) return "Color.R";
283                 if(channel==1) return "Color.G";
284                 if(channel==2) return "Color.B";
285                 return "Color.A";
286         }
287         if(passtype == SCE_PASS_DIFFUSE) {
288                 if(channel==-1) return "Diffuse";
289                 if(channel==0) return "Diffuse.R";
290                 if(channel==1) return "Diffuse.G";
291                 return "Diffuse.B";
292         }
293         if(passtype == SCE_PASS_SPEC) {
294                 if(channel==-1) return "Spec";
295                 if(channel==0) return "Spec.R";
296                 if(channel==1) return "Spec.G";
297                 return "Spec.B";
298         }
299         if(passtype == SCE_PASS_SHADOW) {
300                 if(channel==-1) return "Shadow";
301                 if(channel==0) return "Shadow.R";
302                 if(channel==1) return "Shadow.G";
303                 return "Shadow.B";
304         }
305         if(passtype == SCE_PASS_AO) {
306                 if(channel==-1) return "AO";
307                 if(channel==0) return "AO.R";
308                 if(channel==1) return "AO.G";
309                 return "AO.B";
310         }
311         if(passtype == SCE_PASS_REFLECT) {
312                 if(channel==-1) return "Reflect";
313                 if(channel==0) return "Reflect.R";
314                 if(channel==1) return "Reflect.G";
315                 return "Reflect.B";
316         }
317         if(passtype == SCE_PASS_REFRACT) {
318                 if(channel==-1) return "Refract";
319                 if(channel==0) return "Refract.R";
320                 if(channel==1) return "Refract.G";
321                 return "Refract.B";
322         }
323         if(passtype == SCE_PASS_RADIO) {
324                 if(channel==-1) return "Radio";
325                 if(channel==0) return "Radio.R";
326                 if(channel==1) return "Radio.G";
327                 return "Radio.B";
328         }
329         if(passtype == SCE_PASS_INDEXOB) {
330                 if(channel==-1) return "IndexOB";
331                 return "IndexOB.X";
332         }
333         return "Unknown";
334 }
335
336 static int passtype_from_name(char *str)
337 {
338         
339         if(strcmp(str, "Combined")==0)
340                 return SCE_PASS_COMBINED;
341
342         if(strcmp(str, "Depth")==0)
343                 return SCE_PASS_Z;
344
345         if(strcmp(str, "Vector")==0)
346                 return SCE_PASS_VECTOR;
347
348         if(strcmp(str, "Normal")==0)
349                 return SCE_PASS_NORMAL;
350
351         if(strcmp(str, "UV")==0)
352                 return SCE_PASS_UV;
353
354         if(strcmp(str, "Color")==0)
355                 return SCE_PASS_RGBA;
356
357         if(strcmp(str, "Diffuse")==0)
358                 return SCE_PASS_DIFFUSE;
359
360         if(strcmp(str, "Spec")==0)
361                 return SCE_PASS_SPEC;
362
363         if(strcmp(str, "Shadow")==0)
364                 return SCE_PASS_SHADOW;
365         
366         if(strcmp(str, "AO")==0)
367                 return SCE_PASS_AO;
368
369         if(strcmp(str, "Reflect")==0)
370                 return SCE_PASS_REFLECT;
371
372         if(strcmp(str, "Refract")==0)
373                 return SCE_PASS_REFRACT;
374
375         if(strcmp(str, "Radio")==0)
376                 return SCE_PASS_RADIO;
377
378         if(strcmp(str, "IndexOB")==0)
379                 return SCE_PASS_INDEXOB;
380
381         return 0;
382 }
383
384
385
386 static void render_unique_exr_name(Render *re, char *str)
387 {
388         char di[FILE_MAX], name[FILE_MAXFILE], fi[FILE_MAXFILE];
389         
390         BLI_strncpy(di, G.sce, FILE_MAX);
391         BLI_splitdirstring(di, fi);
392         sprintf(name, "%s_%s.exr", fi, re->scene->id.name+2);
393         if(G.background)
394                 BLI_make_file_string("/", str, "/tmp/", name);
395         else
396                 BLI_make_file_string("/", str, U.tempdir, name);
397                 
398 }
399
400 static void render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, int passtype)
401 {
402         char *typestr= get_pass_name(passtype, 0);
403         RenderPass *rpass= MEM_callocN(sizeof(RenderPass), typestr);
404         int rectsize= rr->rectx*rr->recty*channels;
405         
406         BLI_addtail(&rl->passes, rpass);
407         rpass->passtype= passtype;
408         rpass->channels= channels;
409         
410         if(rr->exrhandle) {
411                 int a;
412                 for(a=0; a<channels; a++)
413                         IMB_exr_add_channel(rr->exrhandle, rl->name, get_pass_name(passtype, a), 0, 0, NULL);
414         }
415         else {
416                 if(passtype==SCE_PASS_VECTOR) {
417                         float *rect;
418                         int x;
419                         
420                         /* initialize to max speed */
421                         rect= rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
422                         for(x= rectsize-1; x>=0; x--)
423                                 rect[x]= PASS_VECTOR_MAX;
424                 }
425                 else
426                         rpass->rect= MEM_mapallocN(sizeof(float)*rectsize, typestr);
427         }
428 }
429
430 float *RE_RenderLayerGetPass(RenderLayer *rl, int passtype)
431 {
432         RenderPass *rpass;
433         
434         for(rpass=rl->passes.first; rpass; rpass= rpass->next)
435                 if(rpass->passtype== passtype)
436                         return rpass->rect;
437         return NULL;
438 }
439
440 RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
441 {
442         RenderLayer *rl;
443         
444         if(rr==NULL) return NULL;
445         
446         for(rl= rr->layers.first; rl; rl= rl->next)
447                 if(strncmp(rl->name, name, RE_MAXNAME)==0)
448                         return rl;
449         return NULL;
450 }
451
452 #define RR_USEMEM       0
453 /* called by main render as well for parts */
454 /* will read info from Render *re to define layers */
455 /* called in threads */
456 /* re->winx,winy is coordinate space of entire image, partrct the part within */
457 static RenderResult *new_render_result(Render *re, rcti *partrct, int crop, int savebuffers)
458 {
459         RenderResult *rr;
460         RenderLayer *rl;
461         SceneRenderLayer *srl;
462         int rectx, recty, nr;
463         
464         rectx= partrct->xmax - partrct->xmin;
465         recty= partrct->ymax - partrct->ymin;
466         
467         if(rectx<=0 || recty<=0)
468                 return NULL;
469         
470         rr= MEM_callocN(sizeof(RenderResult), "new render result");
471         rr->rectx= rectx;
472         rr->recty= recty;
473         rr->renrect.xmin= 0; rr->renrect.xmax= rectx-2*crop;
474         /* crop is one or two extra pixels rendered for filtering, is used for merging and display too */
475         rr->crop= crop;
476         
477         /* tilerect is relative coordinates within render disprect. do not subtract crop yet */
478         rr->tilerect.xmin= partrct->xmin - re->disprect.xmin;
479         rr->tilerect.xmax= partrct->xmax - re->disprect.xmax;
480         rr->tilerect.ymin= partrct->ymin - re->disprect.ymin;
481         rr->tilerect.ymax= partrct->ymax - re->disprect.ymax;
482         
483         if(savebuffers) {
484                 rr->exrhandle= IMB_exr_get_handle();
485         }
486         
487         /* check renderdata for amount of layers */
488         for(nr=0, srl= re->r.layers.first; srl; srl= srl->next, nr++) {
489                 
490                 if((re->r.scemode & R_SINGLE_LAYER) && nr!=re->r.actlay)
491                         continue;
492                 if(srl->layflag & SCE_LAY_DISABLE)
493                         continue;
494                 
495                 rl= MEM_callocN(sizeof(RenderLayer), "new render layer");
496                 BLI_addtail(&rr->layers, rl);
497                 
498                 strcpy(rl->name, srl->name);
499                 rl->lay= srl->lay;
500                 rl->layflag= srl->layflag;
501                 rl->passflag= srl->passflag;
502                 rl->pass_xor= srl->pass_xor;
503                 rl->light_override= srl->light_override;
504                 rl->mat_override= srl->mat_override;
505                 
506                 if(rr->exrhandle) {
507                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.R", 0, 0, NULL);
508                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.G", 0, 0, NULL);
509                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.B", 0, 0, NULL);
510                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.A", 0, 0, NULL);
511                 }
512                 else
513                         rl->rectf= MEM_mapallocN(rectx*recty*sizeof(float)*4, "Combined rgba");
514                 
515                 if(srl->passflag  & SCE_PASS_Z)
516                         render_layer_add_pass(rr, rl, 1, SCE_PASS_Z);
517                 if(srl->passflag  & SCE_PASS_VECTOR)
518                         render_layer_add_pass(rr, rl, 4, SCE_PASS_VECTOR);
519                 if(srl->passflag  & SCE_PASS_NORMAL)
520                         render_layer_add_pass(rr, rl, 3, SCE_PASS_NORMAL);
521                 if(srl->passflag  & SCE_PASS_UV) 
522                         render_layer_add_pass(rr, rl, 3, SCE_PASS_UV);
523                 if(srl->passflag  & SCE_PASS_RGBA)
524                         render_layer_add_pass(rr, rl, 4, SCE_PASS_RGBA);
525                 if(srl->passflag  & SCE_PASS_DIFFUSE)
526                         render_layer_add_pass(rr, rl, 3, SCE_PASS_DIFFUSE);
527                 if(srl->passflag  & SCE_PASS_SPEC)
528                         render_layer_add_pass(rr, rl, 3, SCE_PASS_SPEC);
529                 if(re->r.mode & R_SHADOW)
530                         if(srl->passflag  & SCE_PASS_SHADOW)
531                                 render_layer_add_pass(rr, rl, 3, SCE_PASS_SHADOW);
532                 if(re->r.mode & R_RAYTRACE) {
533                         if(srl->passflag  & SCE_PASS_AO)
534                                 render_layer_add_pass(rr, rl, 3, SCE_PASS_AO);
535                         if(srl->passflag  & SCE_PASS_REFLECT)
536                                 render_layer_add_pass(rr, rl, 3, SCE_PASS_REFLECT);
537                         if(srl->passflag  & SCE_PASS_REFRACT)
538                                 render_layer_add_pass(rr, rl, 3, SCE_PASS_REFRACT);
539                 }
540                 if(re->r.mode & R_RADIO)
541                         if(srl->passflag  & SCE_PASS_RADIO)
542                                 render_layer_add_pass(rr, rl, 3, SCE_PASS_RADIO);
543                 if(srl->passflag  & SCE_PASS_INDEXOB)
544                         render_layer_add_pass(rr, rl, 1, SCE_PASS_INDEXOB);
545                 
546         }
547         /* previewrender and envmap don't do layers, so we make a default one */
548         if(rr->layers.first==NULL) {
549                 rl= MEM_callocN(sizeof(RenderLayer), "new render layer");
550                 BLI_addtail(&rr->layers, rl);
551                 
552                 rl->rectf= MEM_mapallocN(rectx*recty*sizeof(float)*4, "prev/env float rgba");
553                 
554                 /* note, this has to be in sync with scene.c */
555                 rl->lay= (1<<20) -1;
556                 rl->layflag= 0x7FFF;    /* solid ztra halo strand */
557                 rl->passflag= SCE_PASS_COMBINED;
558                 
559                 re->r.actlay= 0;
560         }
561         
562         /* border render; calculate offset for use in compositor. compo is centralized coords */
563         rr->xof= re->disprect.xmin + (re->disprect.xmax - re->disprect.xmin)/2 - re->winx/2;
564         rr->yof= re->disprect.ymin + (re->disprect.ymax - re->disprect.ymin)/2 - re->winy/2;
565         
566         return rr;
567 }
568
569 static int render_scene_needs_vector(Render *re)
570 {
571         if(re->r.scemode & R_DOCOMP) {
572                 SceneRenderLayer *srl;
573         
574                 for(srl= re->scene->r.layers.first; srl; srl= srl->next)
575                         if(!(srl->layflag & SCE_LAY_DISABLE))
576                                 if(srl->passflag & SCE_PASS_VECTOR)
577                                         return 1;
578         }
579         return 0;
580 }
581
582 static void do_merge_tile(RenderResult *rr, RenderResult *rrpart, float *target, float *tile, int pixsize)
583 {
584         int y, ofs, copylen, tilex, tiley;
585         
586         copylen= tilex= rrpart->rectx;
587         tiley= rrpart->recty;
588         
589         if(rrpart->crop) {      /* filters add pixel extra */
590                 tile+= pixsize*(rrpart->crop + rrpart->crop*tilex);
591                 
592                 copylen= tilex - 2*rrpart->crop;
593                 tiley -= 2*rrpart->crop;
594                 
595                 ofs= (rrpart->tilerect.ymin + rrpart->crop)*rr->rectx + (rrpart->tilerect.xmin+rrpart->crop);
596                 target+= pixsize*ofs;
597         }
598         else {
599                 ofs= (rrpart->tilerect.ymin*rr->rectx + rrpart->tilerect.xmin);
600                 target+= pixsize*ofs;
601         }
602
603         copylen *= sizeof(float)*pixsize;
604         tilex *= pixsize;
605         ofs= pixsize*rr->rectx;
606
607         for(y=0; y<tiley; y++) {
608                 memcpy(target, tile, copylen);
609                 target+= ofs;
610                 tile+= tilex;
611         }
612 }
613
614 /* used when rendering to a full buffer, or when reading the exr part-layer-pass file */
615 /* no test happens here if it fits... we also assume layers are in sync */
616 /* is used within threads */
617 static void merge_render_result(RenderResult *rr, RenderResult *rrpart)
618 {
619         RenderLayer *rl, *rlp;
620         RenderPass *rpass, *rpassp;
621         
622         for(rl= rr->layers.first, rlp= rrpart->layers.first; rl && rlp; rl= rl->next, rlp= rlp->next) {
623                 
624                 /* combined */
625                 if(rl->rectf && rlp->rectf)
626                         do_merge_tile(rr, rrpart, rl->rectf, rlp->rectf, 4);
627                 
628                 /* passes are allocated in sync */
629                 for(rpass= rl->passes.first, rpassp= rlp->passes.first; rpass && rpassp; rpass= rpass->next, rpassp= rpassp->next) {
630                         do_merge_tile(rr, rrpart, rpass->rect, rpassp->rect, rpass->channels);
631                 }
632         }
633 }
634
635
636 static void save_render_result_tile(Render *re, RenderPart *pa)
637 {
638         RenderResult *rrpart= pa->result;
639         RenderLayer *rlp;
640         RenderPass *rpassp;
641         int offs, partx, party;
642         
643         BLI_lock_thread(LOCK_IMAGE);
644         
645         for(rlp= rrpart->layers.first; rlp; rlp= rlp->next) {
646                 
647                 if(rrpart->crop) {      /* filters add pixel extra */
648                         offs= (rrpart->crop + rrpart->crop*rrpart->rectx);
649                 }
650                 else {
651                         offs= 0;
652                 }
653                 
654                 /* combined */
655                 if(rlp->rectf) {
656                         int a, xstride= 4;
657                         for(a=0; a<xstride; a++)
658                                 IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a), 
659                                                                 xstride, xstride*pa->rectx, rlp->rectf+a + xstride*offs);
660                 }
661                 
662                 /* passes are allocated in sync */
663                 for(rpassp= rlp->passes.first; rpassp; rpassp= rpassp->next) {
664                         int a, xstride= rpassp->channels;
665                         for(a=0; a<xstride; a++)
666                                 IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a), 
667                                                                         xstride, xstride*pa->rectx, rpassp->rect+a + xstride*offs);
668                 }
669                 
670         }
671
672         party= rrpart->tilerect.ymin + rrpart->crop;
673         partx= rrpart->tilerect.xmin + rrpart->crop;
674         IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
675
676         BLI_unlock_thread(LOCK_IMAGE);
677
678 }
679
680 /* for passes read from files, these have names stored */
681 static char *make_pass_name(RenderPass *rpass, int chan)
682 {
683         static char name[16];
684         int len;
685         
686         BLI_strncpy(name, rpass->name, EXR_PASS_MAXNAME);
687         len= strlen(name);
688         name[len]= '.';
689         name[len+1]= rpass->chan_id[chan];
690         name[len+2]= 0;
691
692         return name;
693 }
694
695 /* filename already made absolute */
696 /* called from within UI, saves both rendered result as a file-read result */
697 void RE_WriteRenderResult(RenderResult *rr, char *filename, int compress)
698 {
699         RenderLayer *rl;
700         RenderPass *rpass;
701         void *exrhandle= IMB_exr_get_handle();
702         
703         /* composite result */
704         if(rr->rectf) {
705                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.R", 4, 4*rr->rectx, rr->rectf);
706                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.G", 4, 4*rr->rectx, rr->rectf+1);
707                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.B", 4, 4*rr->rectx, rr->rectf+2);
708                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.A", 4, 4*rr->rectx, rr->rectf+3);
709         }
710         
711         /* add layers/passes and assign channels */
712         for(rl= rr->layers.first; rl; rl= rl->next) {
713                 
714                 /* combined */
715                 if(rl->rectf) {
716                         int a, xstride= 4;
717                         for(a=0; a<xstride; a++)
718                                 IMB_exr_add_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
719                                                                         xstride, xstride*rr->rectx, rl->rectf+a);
720                 }
721                 
722                 /* passes are allocated in sync */
723                 for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
724                         int a, xstride= rpass->channels;
725                         for(a=0; a<xstride; a++) {
726                                 if(rpass->passtype)
727                                         IMB_exr_add_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
728                                                                                 xstride, xstride*rr->rectx, rpass->rect+a);
729                                 else
730                                         IMB_exr_add_channel(exrhandle, rl->name, make_pass_name(rpass, a), 
731                                                                                 xstride, xstride*rr->rectx, rpass->rect+a);
732                         }
733                 }
734         }
735         
736         IMB_exr_begin_write(exrhandle, filename, rr->rectx, rr->recty, compress);
737         
738         IMB_exr_write_channels(exrhandle);
739         IMB_exr_close(exrhandle);
740 }
741
742 /* callbacks for RE_MultilayerConvert */
743 static void *ml_addlayer_cb(void *base, char *str)
744 {
745         RenderResult *rr= base;
746         RenderLayer *rl;
747         
748         rl= MEM_callocN(sizeof(RenderLayer), "new render layer");
749         BLI_addtail(&rr->layers, rl);
750         
751         BLI_strncpy(rl->name, str, EXR_LAY_MAXNAME);
752         return rl;
753 }
754 static void ml_addpass_cb(void *base, void *lay, char *str, float *rect, int totchan, char *chan_id)
755 {
756         RenderLayer *rl= lay;   
757         RenderPass *rpass= MEM_callocN(sizeof(RenderPass), "loaded pass");
758         int a;
759         
760         BLI_addtail(&rl->passes, rpass);
761         rpass->channels= totchan;
762         
763         rpass->passtype= passtype_from_name(str);
764         if(rpass->passtype==0) printf("unknown pass %s\n", str);
765         rl->passflag |= rpass->passtype;
766         
767         BLI_strncpy(rpass->name, str, EXR_PASS_MAXNAME);
768         /* channel id chars */
769         for(a=0; a<totchan; a++)
770                 rpass->chan_id[a]= chan_id[a];
771         
772         rpass->rect= rect;
773 }
774
775 /* from imbuf, if a handle was returned we convert this to render result */
776 RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty)
777 {
778         RenderResult *rr= MEM_callocN(sizeof(RenderResult), "loaded render result");
779         
780         rr->rectx= rectx;
781         rr->recty= recty;
782         
783         IMB_exr_multilayer_convert(exrhandle, rr, ml_addlayer_cb, ml_addpass_cb);
784         
785         return rr;
786 }
787
788 /* called in end of render, to add names to passes... for UI only */
789 static void renderresult_add_names(RenderResult *rr)
790 {
791         RenderLayer *rl;
792         RenderPass *rpass;
793         
794         for(rl= rr->layers.first; rl; rl= rl->next)
795                 for(rpass= rl->passes.first; rpass; rpass= rpass->next)
796                         strcpy(rpass->name, get_pass_name(rpass->passtype, -1));
797 }
798
799
800 /* only for temp buffer files, makes exact copy of render result */
801 static void read_render_result(Render *re)
802 {
803         RenderLayer *rl;
804         RenderPass *rpass;
805         void *exrhandle= IMB_exr_get_handle();
806         int rectx, recty;
807         char str[FILE_MAX];
808         
809         RE_FreeRenderResult(re->result);
810         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
811
812         render_unique_exr_name(re, str);
813         if(IMB_exr_begin_read(exrhandle, str, &rectx, &recty)==0) {
814                 IMB_exr_close(exrhandle);
815                 printf("cannot read: %s\n", str);
816                 return;
817         }
818         
819         if(rectx!=re->result->rectx || recty!=re->result->recty) {
820                 printf("error in reading render result\n");
821         }
822         else {
823                 for(rl= re->result->layers.first; rl; rl= rl->next) {
824                         
825                         /* combined */
826                         if(rl->rectf) {
827                                 int a, xstride= 4;
828                                 for(a=0; a<xstride; a++)
829                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
830                                                                                 xstride, xstride*rectx, rl->rectf+a);
831                         }
832                         
833                         /* passes are allocated in sync */
834                         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
835                                 int a, xstride= rpass->channels;
836                                 for(a=0; a<xstride; a++)
837                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
838                                                                                 xstride, xstride*rectx, rpass->rect+a);
839                         }
840                         
841                 }
842                 IMB_exr_read_channels(exrhandle);
843                 renderresult_add_names(re->result);
844         }
845         
846         IMB_exr_close(exrhandle);
847 }
848
849 /* *************************************************** */
850
851 Render *RE_GetRender(const char *name)
852 {
853         Render *re;
854         
855         /* search for existing renders */
856         for(re= RenderList.first; re; re= re->next) {
857                 if(strncmp(re->name, name, RE_MAXNAME)==0) {
858                         break;
859                 }
860         }
861         return re;
862 }
863
864 /* if you want to know exactly what has been done */
865 RenderResult *RE_GetResult(Render *re)
866 {
867         if(re)
868                 return re->result;
869         return NULL;
870 }
871
872 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
873 {
874         RenderLayer *rl= BLI_findlink(&rr->layers, re->r.actlay);
875         
876         if(rl) 
877                 return rl;
878         else 
879                 return rr->layers.first;
880 }
881
882
883 /* fill provided result struct with what's currently active or done */
884 void RE_GetResultImage(Render *re, RenderResult *rr)
885 {
886         memset(rr, 0, sizeof(RenderResult));
887
888         if(re && re->result) {
889                 RenderLayer *rl;
890                 
891                 rr->rectx= re->result->rectx;
892                 rr->recty= re->result->recty;
893                 
894                 rr->rectf= re->result->rectf;
895                 rr->rectz= re->result->rectz;
896                 rr->rect32= re->result->rect32;
897                 
898                 /* active layer */
899                 rl= render_get_active_layer(re, re->result);
900
901                 if(rl) {
902                         if(rr->rectf==NULL)
903                                 rr->rectf= rl->rectf;
904                         if(rr->rectz==NULL)
905                                 rr->rectz= RE_RenderLayerGetPass(rl, SCE_PASS_Z);       
906                 }
907         }
908 }
909
910 #define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
911 /* caller is responsible for allocating rect in correct size! */
912 void RE_ResultGet32(Render *re, unsigned int *rect)
913 {
914         RenderResult rres;
915         
916         RE_GetResultImage(re, &rres);
917         if(rres.rect32) 
918                 memcpy(rect, rres.rect32, sizeof(int)*rres.rectx*rres.recty);
919         else if(rres.rectf) {
920                 float *fp= rres.rectf;
921                 int tot= rres.rectx*rres.recty;
922                 char *cp= (char *)rect;
923                 
924                 for(;tot>0; tot--, cp+=4, fp+=4) {
925                         cp[0] = FTOCHAR(fp[0]);
926                         cp[1] = FTOCHAR(fp[1]);
927                         cp[2] = FTOCHAR(fp[2]);
928                         cp[3] = FTOCHAR(fp[3]);
929                 }
930         }
931         else
932                 /* else fill with black */
933                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
934 }
935
936
937 RenderStats *RE_GetStats(Render *re)
938 {
939         return &re->i;
940 }
941
942 Render *RE_NewRender(const char *name)
943 {
944         Render *re;
945         
946         /* only one render per name exists */
947         re= RE_GetRender(name);
948         if(re==NULL) {
949                 
950                 /* new render data struct */
951                 re= MEM_callocN(sizeof(Render), "new render");
952                 BLI_addtail(&RenderList, re);
953                 strncpy(re->name, name, RE_MAXNAME);
954         }
955         
956         /* set default empty callbacks */
957         re->display_init= result_nothing;
958         re->display_clear= result_nothing;
959         re->display_draw= result_rcti_nothing;
960         re->timecursor= int_nothing;
961         re->test_break= void_nothing;
962         re->test_return= void_nothing;
963         re->error= print_error;
964         if(G.background)
965                 re->stats_draw= stats_background;
966         else
967                 re->stats_draw= stats_nothing;
968         
969         /* init some variables */
970         re->ycor= 1.0f;
971         
972         return re;
973 }
974
975 /* only call this while you know it will remove the link too */
976 void RE_FreeRender(Render *re)
977 {
978         
979         free_renderdata_tables(re);
980         free_sample_tables(re);
981         
982         RE_FreeRenderResult(re->result);
983         RE_FreeRenderResult(re->pushedresult);
984         
985         BLI_remlink(&RenderList, re);
986         MEM_freeN(re);
987 }
988
989 /* exit blender */
990 void RE_FreeAllRender(void)
991 {
992         while(RenderList.first) {
993                 RE_FreeRender(RenderList.first);
994         }
995 }
996
997 /* ********* initialize state ******** */
998
999
1000 /* what doesn't change during entire render sequence */
1001 /* disprect is optional, if NULL it assumes full window render */
1002 void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect)
1003 {
1004         re->ok= TRUE;   /* maybe flag */
1005         
1006         re->i.starttime= PIL_check_seconds_timer();
1007         re->r= *rd;             /* hardcopy */
1008         
1009         re->winx= winx;
1010         re->winy= winy;
1011         if(disprect) {
1012                 re->disprect= *disprect;
1013                 re->rectx= disprect->xmax-disprect->xmin;
1014                 re->recty= disprect->ymax-disprect->ymin;
1015         }
1016         else {
1017                 re->disprect.xmin= re->disprect.ymin= 0;
1018                 re->disprect.xmax= winx;
1019                 re->disprect.ymax= winy;
1020                 re->rectx= winx;
1021                 re->recty= winy;
1022         }
1023         
1024         if(re->rectx < 2 || re->recty < 2) {
1025                 re->error("Image too small");
1026                 re->ok= 0;
1027         }
1028         else {
1029                 /* check state variables, osa? */
1030                 if(re->r.mode & (R_OSA)) {
1031                         re->osa= re->r.osa;
1032                         if(re->osa>16) re->osa= 16;
1033                 }
1034                 else re->osa= 0;
1035                 
1036                 /* always call, checks for gamma, gamma tables and jitter too */
1037                 make_sample_tables(re); 
1038                 
1039                 /* make empty render result, so display callbacks can initialize */
1040                 RE_FreeRenderResult(re->result);
1041                 re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1042                 re->result->rectx= re->rectx;
1043                 re->result->recty= re->recty;
1044                 
1045                 if(commandline_threads>0 && commandline_threads<=BLENDER_MAX_THREADS)
1046                         re->r.threads= commandline_threads;
1047         }
1048 }
1049
1050 void RE_SetDispRect (struct Render *re, rcti *disprect)
1051 {
1052         re->disprect= *disprect;
1053         re->rectx= disprect->xmax-disprect->xmin;
1054         re->recty= disprect->ymax-disprect->ymin;
1055         
1056         /* initialize render result */
1057         RE_FreeRenderResult(re->result);
1058         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1059 }
1060
1061 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1062 {
1063         /* re->ok flag? */
1064         
1065         re->viewplane= *viewplane;
1066         re->clipsta= clipsta;
1067         re->clipend= clipend;
1068         re->r.mode &= ~R_ORTHO;
1069
1070         i_window(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1071 }
1072
1073 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1074 {
1075         /* re->ok flag? */
1076         
1077         re->viewplane= *viewplane;
1078         re->clipsta= clipsta;
1079         re->clipend= clipend;
1080         re->r.mode |= R_ORTHO;
1081
1082         i_ortho(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1083 }
1084
1085 void RE_SetView(Render *re, float mat[][4])
1086 {
1087         /* re->ok flag? */
1088         Mat4CpyMat4(re->viewmat, mat);
1089         Mat4Invert(re->viewinv, re->viewmat);
1090 }
1091
1092 /* image and movie output has to move to either imbuf or kernel */
1093 void RE_display_init_cb(Render *re, void (*f)(RenderResult *rr))
1094 {
1095         re->display_init= f;
1096 }
1097 void RE_display_clear_cb(Render *re, void (*f)(RenderResult *rr))
1098 {
1099         re->display_clear= f;
1100 }
1101 void RE_display_draw_cb(Render *re, void (*f)(RenderResult *rr, volatile rcti *rect))
1102 {
1103         re->display_draw= f;
1104 }
1105
1106 void RE_stats_draw_cb(Render *re, void (*f)(RenderStats *rs))
1107 {
1108         re->stats_draw= f;
1109 }
1110 void RE_timecursor_cb(Render *re, void (*f)(int))
1111 {
1112         re->timecursor= f;
1113 }
1114
1115 void RE_test_break_cb(Render *re, int (*f)(void))
1116 {
1117         re->test_break= f;
1118 }
1119 void RE_test_return_cb(Render *re, int (*f)(void))
1120 {
1121         re->test_return= f;
1122 }
1123 void RE_error_cb(Render *re, void (*f)(char *str))
1124 {
1125         re->error= f;
1126 }
1127
1128
1129 /* ********* add object data (later) ******** */
1130
1131 /* object is considered fully prepared on correct time etc */
1132 /* includes lights */
1133 void RE_AddObject(Render *re, Object *ob)
1134 {
1135         
1136 }
1137
1138 /* *************************************** */
1139
1140 static void *do_part_thread(void *pa_v)
1141 {
1142         RenderPart *pa= pa_v;
1143         
1144         /* need to return nicely all parts on esc */
1145         if(R.test_break()==0) {
1146                 
1147                 pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1148                 
1149                 if(R.osa)
1150                         zbufshadeDA_tile(pa);
1151                 else
1152                         zbufshade_tile(pa);
1153                 
1154                 /* merge too on break! */
1155                 if(R.result->exrhandle)
1156                         save_render_result_tile(&R, pa);
1157                 else
1158                         merge_render_result(R.result, pa->result);
1159         }
1160         
1161         pa->ready= 1;
1162         
1163         return NULL;
1164 }
1165
1166 /* returns with render result filled, not threaded, used for preview now only */
1167 static void render_tile_processor(Render *re, int firsttile)
1168 {
1169         RenderPart *pa;
1170         
1171         if(re->test_break())
1172                 return;
1173
1174         /* hrmf... exception, this is used for preview render, re-entrant, so render result has to be re-used */
1175         if(re->result==NULL || re->result->layers.first==NULL) {
1176                 if(re->result) RE_FreeRenderResult(re->result);
1177                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1178         }
1179         
1180         re->stats_draw(&re->i);
1181  
1182         if(re->result==NULL)
1183                 return;
1184         
1185         initparts(re);
1186         
1187         /* assuming no new data gets added to dbase... */
1188         R= *re;
1189         
1190         for(pa= re->parts.first; pa; pa= pa->next) {
1191                 if(firsttile) {
1192                         re->i.partsdone++;      /* was reset in initparts */
1193                         firsttile--;
1194                 }
1195                 else {
1196                         do_part_thread(pa);
1197                         
1198                         if(pa->result) {
1199                                 if(!re->test_break()) {
1200                                         re->display_draw(pa->result, NULL);
1201                                         
1202                                         re->i.partsdone++;
1203                                         re->stats_draw(&re->i);
1204                                 }
1205                                 RE_FreeRenderResult(pa->result);
1206                                 pa->result= NULL;
1207                         }               
1208                         if(re->test_break())
1209                                 break;
1210                 }
1211         }
1212         
1213         freeparts(re);
1214 }
1215
1216 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1217 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1218 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1219 float panorama_pixel_rot(Render *re)
1220 {
1221         float psize, phi, xfac;
1222         
1223         /* size of 1 pixel mapped to viewplane coords */
1224         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
1225         /* angle of a pixel */
1226         phi= atan(psize/re->clipsta);
1227         
1228         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1229         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1230         xfac= atan(0.5f*xfac/re->clipsta); 
1231         /* and how much the same viewplane angle is wrapped */
1232         psize= 0.5f*phi*((float)re->partx);
1233         
1234         /* the ratio applied to final per-pixel angle */
1235         phi*= xfac/psize;
1236         
1237         return phi;
1238 }
1239
1240 /* call when all parts stopped rendering, to find the next Y slice */
1241 /* if slice found, it rotates the dbase */
1242 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1243 {
1244         RenderPart *pa, *best= NULL;
1245         
1246         *minx= re->winx;
1247         
1248         /* most left part of the non-rendering parts */
1249         for(pa= re->parts.first; pa; pa= pa->next) {
1250                 if(pa->ready==0 && pa->nr==0) {
1251                         if(pa->disprect.xmin < *minx) {
1252                                 best= pa;
1253                                 *minx= pa->disprect.xmin;
1254                         }
1255                 }
1256         }
1257                         
1258         if(best) {
1259                 float phi= panorama_pixel_rot(re);
1260
1261                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1262                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
1263                 
1264                 /* shift viewplane */
1265                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1266                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1267                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1268                 Mat4CpyMat4(R.winmat, re->winmat);
1269                 
1270                 /* rotate database according to part coordinates */
1271                 project_renderdata(re, projectverto, 1, -R.panodxp*phi);
1272                 R.panosi= sin(R.panodxp*phi);
1273                 R.panoco= cos(R.panodxp*phi);
1274         }
1275         return best;
1276 }
1277
1278 static RenderPart *find_next_part(Render *re, int minx)
1279 {
1280         RenderPart *pa, *best= NULL;
1281         int centx=re->winx/2, centy=re->winy/2, tot=1;
1282         int mindist, distx, disty;
1283         
1284         /* find center of rendered parts, image center counts for 1 too */
1285         for(pa= re->parts.first; pa; pa= pa->next) {
1286                 if(pa->ready) {
1287                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1288                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1289                         tot++;
1290                 }
1291         }
1292         centx/=tot;
1293         centy/=tot;
1294         
1295         /* closest of the non-rendering parts */
1296         mindist= re->winx*re->winy;
1297         for(pa= re->parts.first; pa; pa= pa->next) {
1298                 if(pa->ready==0 && pa->nr==0) {
1299                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1300                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1301                         distx= (int)sqrt(distx*distx + disty*disty);
1302                         if(distx<mindist) {
1303                                 if(re->r.mode & R_PANORAMA) {
1304                                         if(pa->disprect.xmin==minx) {
1305                                                 best= pa;
1306                                                 mindist= distx;
1307                                         }
1308                                 }
1309                                 else {
1310                                         best= pa;
1311                                         mindist= distx;
1312                                 }
1313                         }
1314                 }
1315         }
1316         return best;
1317 }
1318
1319 static void print_part_stats(Render *re, RenderPart *pa)
1320 {
1321         char str[64];
1322         
1323         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1324         re->i.infostr= str;
1325         re->stats_draw(&re->i);
1326         re->i.infostr= NULL;
1327 }
1328
1329 static void threaded_tile_processor(Render *re)
1330 {
1331         ListBase threads;
1332         RenderPart *pa, *nextpa;
1333         RenderResult *rr;
1334         rctf viewplane= re->viewplane;
1335         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1336         
1337         /* first step; the entire render result, or prepare exr buffer saving */
1338         RE_FreeRenderResult(re->result);
1339         rr= re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & R_EXR_TILE_FILE);
1340         
1341         if(rr==NULL)
1342                 return;
1343         /* warning; no return here without closing exr file */
1344 //      if(re->re->test_break())
1345 //              return;
1346         
1347         initparts(re);
1348         
1349         if(rr->exrhandle) {
1350                 char str[FILE_MAX];
1351                 
1352                 render_unique_exr_name(re, str);
1353                 
1354                 printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1355                 IMB_exrtile_begin_write(rr->exrhandle, str, rr->rectx, rr->recty, rr->rectx/re->xparts, rr->recty/re->yparts);
1356         }
1357         
1358         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1359         
1360         /* assuming no new data gets added to dbase... */
1361         R= *re;
1362         
1363         /* set threadsafe break */
1364         R.test_break= thread_break;
1365         
1366         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1367         if(re->r.mode & R_PANORAMA)
1368                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1369         else
1370                 nextpa= find_next_part(re, 0);
1371         
1372         while(rendering) {
1373                 
1374                 if(re->test_break())
1375                         PIL_sleep_ms(50);
1376                 else if(nextpa && BLI_available_threads(&threads)) {
1377                         drawtimer= 0;
1378                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1379                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1380                         BLI_insert_thread(&threads, nextpa);
1381
1382                         nextpa= find_next_part(re, minx);
1383                 }
1384                 else if(re->r.mode & R_PANORAMA) {
1385                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1386                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1387                         else {
1388                                 PIL_sleep_ms(50);
1389                                 drawtimer++;
1390                         }
1391                 }
1392                 else {
1393                         PIL_sleep_ms(50);
1394                         drawtimer++;
1395                 }
1396                 
1397                 /* check for ready ones to display, and if we need to continue */
1398                 rendering= 0;
1399                 hasdrawn= 0;
1400                 for(pa= re->parts.first; pa; pa= pa->next) {
1401                         if(pa->ready) {
1402                                 if(pa->result) {
1403                                         BLI_remove_thread(&threads, pa);
1404
1405                                         re->display_draw(pa->result, NULL);
1406                                         print_part_stats(re, pa);
1407                                         
1408                                         RE_FreeRenderResult(pa->result);
1409                                         pa->result= NULL;
1410                                         re->i.partsdone++;
1411                                         hasdrawn= 1;
1412                                 }
1413                         }
1414                         else {
1415                                 rendering= 1;
1416                                 if(pa->nr && pa->result && drawtimer>20) {
1417                                         re->display_draw(pa->result, &pa->result->renrect);
1418                                         hasdrawn= 1;
1419                                 }
1420                         }
1421                 }
1422                 if(hasdrawn)
1423                         drawtimer= 0;
1424
1425                 /* on break, wait for all slots to get freed */
1426                 if( (g_break=re->test_break()) && BLI_available_threads(&threads)==re->r.threads)
1427                         rendering= 0;
1428                 
1429         }
1430         
1431         if(rr->exrhandle) {
1432                 IMB_exr_close(rr->exrhandle);
1433                 rr->exrhandle= NULL;
1434                 if(!re->test_break())
1435                         read_render_result(re);
1436         }
1437         
1438         /* unset threadsafety */
1439         g_break= 0;
1440         
1441         BLI_end_threads(&threads);
1442         freeparts(re);
1443 }
1444
1445 /* currently only called by preview renders and envmap */
1446 void RE_TileProcessor(Render *re, int firsttile)
1447 {
1448         /* the partsdone variable has to be reset to firsttile, to survive esc before it was set to zero */
1449         
1450         re->i.partsdone= firsttile;
1451
1452         re->i.starttime= PIL_check_seconds_timer();
1453
1454         //      threaded_tile_processor(re);
1455         render_tile_processor(re, firsttile);
1456                 
1457         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1458         re->stats_draw(&re->i);
1459 }
1460
1461
1462 /* ************  This part uses API, for rendering Blender scenes ********** */
1463
1464 static void do_render_3d(Render *re)
1465 {
1466         
1467 //      re->cfra= cfra; /* <- unused! */
1468         
1469         /* make render verts/faces/halos/lamps */
1470         if(render_scene_needs_vector(re))
1471                 RE_Database_FromScene_Vectors(re, re->scene);
1472         else
1473            RE_Database_FromScene(re, re->scene, 1);
1474         
1475         threaded_tile_processor(re);
1476         
1477         /* do left-over 3d post effects (flares) */
1478         if(re->flag & R_HALO)
1479                 if(!re->test_break())
1480                         add_halo_flare(re);
1481
1482         
1483         /* free all render verts etc */
1484         RE_Database_Free(re);
1485 }
1486
1487 /* called by blur loop, accumulate renderlayers */
1488 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1489 {
1490         float mfac= 1.0f - blurfac;
1491         int a, b, stride= channels*rr->rectx;
1492         int len= stride*sizeof(float);
1493         
1494         for(a=0; a<rr->recty; a++) {
1495                 if(blurfac==1.0f) {
1496                         memcpy(rectf, rectf1, len);
1497                 }
1498                 else {
1499                         float *rf= rectf, *rf1= rectf1;
1500                         
1501                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1502                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1503                         }
1504                 }
1505                 rectf+= stride;
1506                 rectf1+= stride;
1507         }
1508 }
1509
1510 /* called by blur loop, accumulate renderlayers */
1511 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac)
1512 {
1513         RenderLayer *rl, *rl1;
1514         RenderPass *rpass, *rpass1;
1515         
1516         rl1= brr->layers.first;
1517         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1518                 
1519                 /* combined */
1520                 if(rl->rectf && rl1->rectf)
1521                         addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1522                 
1523                 /* passes are allocated in sync */
1524                 rpass1= rl1->passes.first;
1525                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1526                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1527                 }
1528         }
1529 }
1530
1531 /* main blur loop, can be called by fields too */
1532 static void do_render_blur_3d(Render *re)
1533 {
1534         RenderResult *rres;
1535         float blurfac;
1536         int blur= re->r.osa;
1537         
1538         /* create accumulation render result */
1539         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1540         
1541         /* do the blur steps */
1542         while(blur--) {
1543                 set_mblur_offs( re->r.blurfac*((float)(re->r.osa-blur))/(float)re->r.osa );
1544                 
1545                 re->i.curblur= re->r.osa-blur;  /* stats */
1546                 
1547                 do_render_3d(re);
1548                 
1549                 blurfac= 1.0f/(float)(re->r.osa-blur);
1550                 
1551                 merge_renderresult_blur(rres, re->result, blurfac);
1552                 if(re->test_break()) break;
1553         }
1554         
1555         /* swap results */
1556         RE_FreeRenderResult(re->result);
1557         re->result= rres;
1558         
1559         set_mblur_offs(0.0f);
1560         re->i.curblur= 0;       /* stats */
1561         
1562         /* weak... the display callback wants an active renderlayer pointer... */
1563         re->result->renlay= render_get_active_layer(re, re->result);
1564         re->display_draw(re->result, NULL);     
1565 }
1566
1567
1568 /* function assumes rectf1 and rectf2 to be half size of rectf */
1569 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1570 {
1571         int a, stride= channels*rr->rectx;
1572         int len= stride*sizeof(float);
1573         
1574         for(a=0; a<rr->recty; a+=2) {
1575                 memcpy(rectf, rectf1, len);
1576                 rectf+= stride;
1577                 rectf1+= stride;
1578                 memcpy(rectf, rectf2, len);
1579                 rectf+= stride;
1580                 rectf2+= stride;
1581         }
1582 }
1583
1584 /* merge render results of 2 fields */
1585 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1586 {
1587         RenderLayer *rl, *rl1, *rl2;
1588         RenderPass *rpass, *rpass1, *rpass2;
1589         
1590         rl1= rr1->layers.first;
1591         rl2= rr2->layers.first;
1592         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1593                 
1594                 /* combined */
1595                 if(rl->rectf && rl1->rectf && rl2->rectf)
1596                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1597                 
1598                 /* passes are allocated in sync */
1599                 rpass1= rl1->passes.first;
1600                 rpass2= rl2->passes.first;
1601                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1602                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1603                 }
1604         }
1605 }
1606
1607
1608 /* interleaves 2 frames */
1609 static void do_render_fields_3d(Render *re)
1610 {
1611         RenderResult *rr1, *rr2= NULL;
1612         
1613         /* no render result was created, we can safely halve render y */
1614         re->winy /= 2;
1615         re->recty /= 2;
1616         re->disprect.ymin /= 2;
1617         re->disprect.ymax /= 2;
1618         
1619         re->i.curfield= 1;      /* stats */
1620         
1621         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1622         RE_SetCamera(re, re->scene->camera);
1623         if(re->r.mode & R_MBLUR)
1624                 do_render_blur_3d(re);
1625         else
1626                 do_render_3d(re);
1627         rr1= re->result;
1628         re->result= NULL;
1629         
1630         /* second field */
1631         if(!re->test_break()) {
1632                 
1633                 re->i.curfield= 2;      /* stats */
1634                 
1635                 re->flag |= R_SEC_FIELD;
1636                 if((re->r.mode & R_FIELDSTILL)==0) 
1637                         set_field_offs(0.5f);
1638                 RE_SetCamera(re, re->scene->camera);
1639                 if(re->r.mode & R_MBLUR)
1640                         do_render_blur_3d(re);
1641                 else
1642                         do_render_3d(re);
1643                 re->flag &= ~R_SEC_FIELD;
1644                 set_field_offs(0.0f);
1645                 
1646                 rr2= re->result;
1647         }
1648         
1649         /* allocate original height new buffers */
1650         re->winy *= 2;
1651         re->recty *= 2;
1652         re->disprect.ymin *= 2;
1653         re->disprect.ymax *= 2;
1654         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1655         
1656         if(rr2) {
1657                 if(re->r.mode & R_ODDFIELD)
1658                         merge_renderresult_fields(re->result, rr2, rr1);
1659                 else
1660                         merge_renderresult_fields(re->result, rr1, rr2);
1661                 
1662                 RE_FreeRenderResult(rr2);
1663         }
1664         RE_FreeRenderResult(rr1);
1665         
1666         re->i.curfield= 0;      /* stats */
1667         
1668         /* weak... the display callback wants an active renderlayer pointer... */
1669         re->result->renlay= render_get_active_layer(re, re->result);
1670         re->display_draw(re->result, NULL);
1671 }
1672
1673 static void load_backbuffer(Render *re)
1674 {
1675         if(re->r.alphamode == R_ADDSKY) {
1676                 ImBuf *ibuf;
1677                 char name[256];
1678                 
1679                 strcpy(name, re->r.backbuf);
1680                 BLI_convertstringcode(name, G.sce, re->r.cfra);
1681                 
1682                 if(re->backbuf) {
1683                         re->backbuf->id.us--;
1684                         if(re->backbuf->id.us<1)
1685                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
1686                 }
1687                 
1688                 re->backbuf= BKE_add_image_file(name);
1689                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
1690                 if(ibuf==NULL) {
1691                         // error() doesnt work with render window open
1692                         //error("No backbuf there!");
1693                         printf("Error: No backbuf %s\n", name);
1694                 }
1695                 else {
1696                         if (re->r.mode & R_FIELDS)
1697                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
1698                 }
1699         }
1700 }
1701
1702 /* main render routine, no compositing */
1703 static void do_render_fields_blur_3d(Render *re)
1704 {
1705         /* also check for camera here */
1706         if(re->scene->camera==NULL) {
1707                 printf("ERROR: Cannot render, no camera\n");
1708                 G.afbreek= 1;
1709                 return;
1710         }
1711         
1712         /* backbuffer initialize */
1713         if(re->r.bufflag & 1)
1714                 load_backbuffer(re);
1715
1716         /* now use renderdata and camera to set viewplane */
1717         RE_SetCamera(re, re->scene->camera);
1718         
1719         if(re->r.mode & R_FIELDS)
1720                 do_render_fields_3d(re);
1721         else if(re->r.mode & R_MBLUR)
1722                 do_render_blur_3d(re);
1723         else
1724                 do_render_3d(re);
1725         
1726         /* when border render, check if we have to insert it in black */
1727         if(re->result) {
1728                 if(re->r.mode & R_BORDER) {
1729                         if((re->r.mode & R_CROP)==0) {
1730                                 RenderResult *rres;
1731                                 
1732                                 /* sub-rect for merge call later on */
1733                                 re->result->tilerect= re->disprect;
1734                                 
1735                                 /* this copying sequence could become function? */
1736                                 re->disprect.xmin= re->disprect.ymin= 0;
1737                                 re->disprect.xmax= re->winx;
1738                                 re->disprect.ymax= re->winy;
1739                                 re->rectx= re->winx;
1740                                 re->recty= re->winy;
1741                                 
1742                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1743                                 
1744                                 merge_render_result(rres, re->result);
1745                                 RE_FreeRenderResult(re->result);
1746                                 re->result= rres;
1747                                 
1748                                 /* weak... the display callback wants an active renderlayer pointer... */
1749                                 re->result->renlay= render_get_active_layer(re, re->result);
1750                                 
1751                                 re->display_init(re->result);
1752                                 re->display_draw(re->result, NULL);
1753                         }
1754                 }
1755         }
1756 }
1757
1758
1759 /* within context of current Render *re, render another scene.
1760    it uses current render image size and disprect, but doesn't execute composite
1761 */
1762 static void render_scene(Render *re, Scene *sce, int cfra)
1763 {
1764         Render *resc= RE_NewRender(sce->id.name);
1765         
1766         sce->r.cfra= cfra;
1767                 
1768         /* initial setup */
1769         RE_InitState(resc, &sce->r, re->winx, re->winy, &re->disprect);
1770         
1771         /* this to enable this scene to create speed vectors */
1772         resc->r.scemode |= R_DOCOMP;
1773         
1774         /* still unsure entity this... */
1775         resc->scene= sce;
1776         
1777         /* ensure scene has depsgraph, base flags etc OK. Warning... also sets G.scene */
1778         set_scene_bg(sce);
1779
1780         /* copy callbacks */
1781         resc->display_draw= re->display_draw;
1782         resc->test_break= re->test_break;
1783         resc->stats_draw= re->stats_draw;
1784         
1785         do_render_fields_blur_3d(resc);
1786 }
1787
1788 static void ntree_render_scenes(Render *re)
1789 {
1790         bNode *node;
1791         int cfra= re->scene->r.cfra;
1792         
1793         if(re->scene->nodetree==NULL) return;
1794         
1795         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
1796         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1797                 if(node->type==CMP_NODE_R_LAYERS) {
1798                         if(node->id) {
1799                                 if(node->id != (ID *)re->scene)
1800                                         node->id->flag |= LIB_DOIT;
1801                                 else
1802                                         node->id->flag &= ~LIB_DOIT;
1803                         }
1804                 }
1805         }
1806         
1807         /* now foreach render-result node tagged we do a full render */
1808         /* results are stored in a way compisitor will find it */
1809         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1810                 if(node->type==CMP_NODE_R_LAYERS) {
1811                         if(node->id && node->id != (ID *)re->scene) {
1812                                 if(node->id->flag & LIB_DOIT) {
1813                                         render_scene(re, (Scene *)node->id, cfra);
1814                                         node->id->flag &= ~LIB_DOIT;
1815                                 }
1816                         }
1817                 }
1818         }
1819         
1820         /* still the global... */
1821         if(G.scene!=re->scene)
1822                 set_scene_bg(re->scene);
1823         
1824 }
1825
1826 /* helper call to detect if theres a composite with render-result node */
1827 static int composite_needs_render(Scene *sce)
1828 {
1829         bNodeTree *ntree= sce->nodetree;
1830         bNode *node;
1831         
1832         if(ntree==NULL) return 1;
1833         if(sce->use_nodes==0) return 1;
1834         if((sce->r.scemode & R_DOCOMP)==0) return 1;
1835                 
1836         for(node= ntree->nodes.first; node; node= node->next) {
1837                 if(node->type==CMP_NODE_R_LAYERS)
1838                         if(node->id==NULL || node->id==&sce->id)
1839                                 return 1;
1840         }
1841         return 0;
1842 }
1843
1844 /* bad call... need to think over proper method still */
1845 static void render_composit_stats(char *str)
1846 {
1847         R.i.infostr= str;
1848         R.stats_draw(&R.i);
1849         R.i.infostr= NULL;
1850 }
1851
1852 /* returns fully composited render-result on given time step (in RenderData) */
1853 static void do_render_composite_fields_blur_3d(Render *re)
1854 {
1855         bNodeTree *ntree= re->scene->nodetree;
1856         
1857         /* INIT seeding, compositor can use random texture */
1858         BLI_srandom(re->r.cfra);
1859         
1860         if(composite_needs_render(re->scene)) {
1861                 /* save memory... free all cached images */
1862                 ntreeFreeCache(ntree);
1863                 
1864                 do_render_fields_blur_3d(re);
1865         }
1866         
1867         /* swap render result */
1868         if(re->r.scemode & R_SINGLE_LAYER)
1869                 pop_render_result(re);
1870         
1871         if(!re->test_break() && ntree) {
1872                 ntreeCompositTagRender(ntree);
1873                 ntreeCompositTagAnimated(ntree);
1874                 
1875                 if(re->r.scemode & R_DOCOMP) {
1876                         /* checks if there are render-result nodes that need scene */
1877                         if((re->r.scemode & R_SINGLE_LAYER)==0)
1878                                 ntree_render_scenes(re);
1879                         
1880                         if(!re->test_break()) {
1881                                 ntree->stats_draw= render_composit_stats;
1882                                 ntree->test_break= re->test_break;
1883                                 /* in case it was never initialized */
1884                                 R.stats_draw= re->stats_draw;
1885                                 
1886                                 ntreeCompositExecTree(ntree, &re->r, G.background==0);
1887                                 ntree->stats_draw= NULL;
1888                                 ntree->test_break= NULL;
1889                         }
1890                 }
1891         }
1892
1893         re->display_draw(re->result, NULL);
1894 }
1895
1896 #ifndef DISABLE_YAFRAY
1897 /* yafray: main yafray render/export call */
1898 static void yafrayRender(Render *re)
1899 {
1900         RE_FreeRenderResult(re->result);
1901         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1902         
1903         // need this too, for aspect/ortho/etc info
1904         RE_SetCamera(re, re->scene->camera);
1905
1906         // switch must be done before prepareScene()
1907         if (!re->r.YFexportxml)
1908                 YAF_switchFile();
1909         else
1910                 YAF_switchPlugin();
1911         
1912         printf("Starting scene conversion.\n");
1913         RE_Database_FromScene(re, re->scene, 1);
1914         printf("Scene conversion done.\n");
1915         
1916         re->i.starttime = PIL_check_seconds_timer();
1917         
1918         YAF_exportScene(re);
1919
1920         /* also needed for yafray border render, straight copy from do_render_fields_blur_3d() */
1921         /* when border render, check if we have to insert it in black */
1922         if(re->result) {
1923                 if(re->r.mode & R_BORDER) {
1924                         if((re->r.mode & R_CROP)==0) {
1925                                 RenderResult *rres;
1926                                 
1927                                 /* sub-rect for merge call later on */
1928                                 re->result->tilerect= re->disprect;
1929                                 
1930                                 /* this copying sequence could become function? */
1931                                 re->disprect.xmin= re->disprect.ymin= 0;
1932                                 re->disprect.xmax= re->winx;
1933                                 re->disprect.ymax= re->winy;
1934                                 re->rectx= re->winx;
1935                                 re->recty= re->winy;
1936                                 
1937                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1938                                 
1939                                 merge_render_result(rres, re->result);
1940                                 RE_FreeRenderResult(re->result);
1941                                 re->result= rres;
1942                                 
1943                                 re->display_init(re->result);
1944                                 re->display_draw(re->result, NULL);
1945                         }
1946                 }
1947         }
1948
1949         re->i.lastframetime = PIL_check_seconds_timer()- re->i.starttime;
1950         re->stats_draw(&re->i);
1951         
1952         RE_Database_Free(re);
1953 }
1954
1955 #endif /* disable yafray */
1956
1957
1958 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1959
1960 /* main loop: doing sequence + fields + blur + 3d render + compositing */
1961 static void do_render_all_options(Render *re)
1962 {
1963         re->i.starttime= PIL_check_seconds_timer();
1964
1965         /* ensure no images are in memory from previous animated sequences */
1966         BKE_image_all_free_anim_ibufs(re->r.cfra);
1967         
1968         if(re->r.scemode & R_DOSEQ) {
1969                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
1970                 if(!re->test_break()) 
1971                         do_render_seq(re->result, re->r.cfra);
1972                 
1973                 re->stats_draw(&re->i);
1974                 re->display_draw(re->result, NULL);
1975                 
1976         }
1977         else {
1978 #ifndef DISABLE_YAFRAY
1979                 if(re->r.renderer==R_YAFRAY)
1980                         yafrayRender(re);
1981                 else
1982                         do_render_composite_fields_blur_3d(re);
1983 #else
1984                 do_render_composite_fields_blur_3d(re);
1985 #endif
1986         }
1987         
1988         /* for UI only */
1989         renderresult_add_names(re->result);
1990         
1991         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1992         re->stats_draw(&re->i);
1993 }
1994
1995 static int is_rendering_allowed(Render *re)
1996 {
1997         SceneRenderLayer *srl;
1998         
1999         /* forbidden combinations */
2000         if(re->r.mode & R_PANORAMA) {
2001                 if(re->r.mode & R_BORDER) {
2002                         re->error("No border supported for Panorama");
2003                         return 0;
2004                 }
2005                 if(re->r.mode & R_ORTHO) {
2006                         re->error("No Ortho render possible for Panorama");
2007                         return 0;
2008                 }
2009         }
2010         
2011         if(re->r.mode & R_BORDER) {
2012                 if(re->r.border.xmax <= re->r.border.xmin || 
2013                    re->r.border.ymax <= re->r.border.ymin) {
2014                         re->error("No border area selected.");
2015                         return 0;
2016                 }
2017                 if(re->r.scemode & R_EXR_TILE_FILE) {
2018                         re->error("Border render and Buffer-save not supported yet");
2019                         return 0;
2020                 }
2021         }
2022         
2023         if(re->r.scemode & R_EXR_TILE_FILE) {
2024                 char str[FILE_MAX];
2025                 
2026                 render_unique_exr_name(re, str);
2027                 
2028                 if (BLI_is_writable(str)==0) {
2029                         re->error("Can not save render buffers, check the temp default path");
2030                         return 0;
2031                 }
2032                 
2033         }
2034         
2035         if(re->r.scemode & R_DOCOMP) {
2036                 if(re->scene->use_nodes) {
2037                         bNodeTree *ntree= re->scene->nodetree;
2038                         bNode *node;
2039                 
2040                         if(ntree==NULL) {
2041                                 re->error("No Nodetree in Scene");
2042                                 return 0;
2043                         }
2044                 
2045                         for(node= ntree->nodes.first; node; node= node->next)
2046                                 if(node->type==CMP_NODE_COMPOSITE)
2047                                         break;
2048                         
2049                         if(node==NULL) {
2050                                 re->error("No Render Output Node in Scene");
2051                                 return 0;
2052                         }
2053                 }
2054         }
2055         
2056         /* check valid camera, without camera render is OK (compo, seq) */
2057         if(re->scene->camera==NULL)
2058                 re->scene->camera= scene_find_camera(re->scene);
2059         
2060         if(!(re->r.scemode & (R_DOSEQ|R_DOCOMP))) {
2061                 if(re->scene->camera==NULL) {
2062                         re->error("No camera");
2063                         return 0;
2064                 }
2065         }
2066         /* layer flag tests */
2067         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
2068                 if(!(srl->layflag & SCE_LAY_DISABLE))
2069                         break;
2070         if(srl==NULL) {
2071                 re->error("All RenderLayers are disabled");
2072                 return 0;
2073         }
2074         
2075         return 1;
2076 }
2077
2078 /* evaluating scene options for general Blender render */
2079 static int render_initialize_from_scene(Render *re, Scene *scene)
2080 {
2081         int winx, winy;
2082         rcti disprect;
2083         
2084         /* r.xsch and r.ysch has the actual view window size
2085                 r.border is the clipping rect */
2086         
2087         /* calculate actual render result and display size */
2088         winx= (scene->r.size*scene->r.xsch)/100;
2089         winy= (scene->r.size*scene->r.ysch)/100;
2090         
2091         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2092         if(scene->r.mode & R_BORDER) {
2093                 disprect.xmin= scene->r.border.xmin*winx;
2094                 disprect.xmax= scene->r.border.xmax*winx;
2095                 
2096                 disprect.ymin= scene->r.border.ymin*winy;
2097                 disprect.ymax= scene->r.border.ymax*winy;
2098         }
2099         else {
2100                 disprect.xmin= disprect.ymin= 0;
2101                 disprect.xmax= winx;
2102                 disprect.ymax= winy;
2103         }
2104         
2105         if(scene->r.scemode & R_EXR_TILE_FILE) {
2106                 int partx= winx/scene->r.xparts, party= winy/scene->r.yparts;
2107                 
2108                 /* stupid exr tiles dont like different sizes */
2109                 if(winx != partx*scene->r.xparts || winy != party*scene->r.yparts) {
2110                         re->error("Sorry... exr tile saving only allowed with equally sized parts");
2111                         return 0;
2112                 }
2113                 if((scene->r.mode & R_FIELDS) && (party & 1)) {
2114                         re->error("Sorry... exr tile saving only allowed with equally sized parts");
2115                         return 0;
2116                 }
2117         }
2118         
2119         if(scene->r.scemode & R_SINGLE_LAYER)
2120                 push_render_result(re);
2121         
2122         RE_InitState(re, &scene->r, winx, winy, &disprect);
2123         
2124         re->scene= scene;
2125         if(!is_rendering_allowed(re))
2126                 return 0;
2127         
2128         re->display_init(re->result);
2129         re->display_clear(re->result);
2130         
2131         return 1;
2132 }
2133
2134 /* general Blender frame render call */
2135 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
2136 {
2137         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2138         /* is also set by caller renderwin.c */
2139         G.rendering= 1;
2140         
2141         scene->r.cfra= frame;
2142         
2143         if(render_initialize_from_scene(re, scene)) {
2144                 do_render_all_options(re);
2145         }
2146         
2147         /* UGLY WARNING */
2148         G.rendering= 0;
2149 }
2150
2151 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
2152 {
2153         char name[FILE_MAX];
2154         RenderResult rres;
2155         
2156         RE_GetResultImage(re, &rres);
2157
2158         /* write movie or image */
2159         if(BKE_imtype_is_movie(scene->r.imtype)) {
2160                 int dofree = 0;
2161                 /* note; the way it gets 32 bits rects is weak... */
2162                 if(rres.rect32==NULL) {
2163                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2164                         dofree = 1;
2165                 }
2166                 RE_ResultGet32(re, rres.rect32);
2167                 mh->append_movie(scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
2168                 if(dofree) {
2169                         MEM_freeN(rres.rect32);
2170                 }
2171                 printf("Append frame %d", scene->r.cfra);
2172         } 
2173         else {
2174                 BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2175                 
2176                 if(re->r.imtype==R_MULTILAYER) {
2177                         if(re->result) {
2178                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2179                                 printf("Saved: %s", name);
2180                         }
2181                 }
2182                 else {
2183                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
2184                         int ok;
2185                         
2186                                         /* if not exists, BKE_write_ibuf makes one */
2187                         ibuf->rect= rres.rect32;    
2188                         ibuf->rect_float= rres.rectf;
2189                         ibuf->zbuf_float= rres.rectz;
2190                         
2191                         /* float factor for random dither, imbuf takes care of it */
2192                         ibuf->dither= scene->r.dither_intensity;
2193
2194                         ok= BKE_write_ibuf(ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2195                         
2196                         if(ok==0) {
2197                                 printf("Render error: cannot save %s\n", name);
2198                                 G.afbreek=1;
2199                         }
2200                         else printf("Saved: %s", name);
2201                         
2202                         /* optional preview images for exr */
2203                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
2204                                 if(BLI_testextensie(name, ".exr")) 
2205                                         name[strlen(name)-4]= 0;
2206                                 BKE_add_image_extension(name, R_JPEG90);
2207                                 ibuf->depth= 24; 
2208                                 BKE_write_ibuf(ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
2209                                 printf("\nSaved: %s", name);
2210                         }
2211                         
2212                                         /* imbuf knows which rects are not part of ibuf */
2213                         IMB_freeImBuf(ibuf);
2214                 }
2215         }
2216         
2217         BLI_timestr(re->i.lastframetime, name);
2218         printf(" Time: %s\n", name);
2219         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2220 }
2221
2222 /* saves images to disk */
2223 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
2224 {
2225         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
2226         int cfrao= scene->r.cfra;
2227         
2228         /* do not call for each frame, it initializes & pops output window */
2229         if(!render_initialize_from_scene(re, scene))
2230                 return;
2231         
2232         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2233         /* is also set by caller renderwin.c */
2234         G.rendering= 1;
2235         
2236         if(BKE_imtype_is_movie(scene->r.imtype))
2237                 mh->start_movie(&re->r, re->rectx, re->recty);
2238         
2239         if (mh->get_next_frame) {
2240                 while (!(G.afbreek == 1)) {
2241                         int nf = mh->get_next_frame();
2242                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2243                                 scene->r.cfra = re->r.cfra = nf;
2244                                 
2245                                 do_render_all_options(re);
2246
2247                                 if(re->test_break() == 0) {
2248                                         do_write_image_or_movie(re, scene, mh);
2249                                 }
2250                         } else {
2251                                 re->test_break();
2252                         }
2253                 }
2254         } else {
2255                 for(scene->r.cfra= sfra; 
2256                     scene->r.cfra<=efra; scene->r.cfra++) {
2257                         re->r.cfra= scene->r.cfra;         /* weak.... */
2258                 
2259                         do_render_all_options(re);
2260
2261                         if(re->test_break() == 0) {
2262                                 do_write_image_or_movie(re, scene, mh);
2263                         }
2264                 
2265                         if(G.afbreek==1) break;
2266                 }
2267         }
2268         
2269         /* end movie */
2270         if(BKE_imtype_is_movie(scene->r.imtype))
2271                 mh->end_movie();
2272
2273         scene->r.cfra= cfrao;
2274         
2275         /* UGLY WARNING */
2276         G.rendering= 0;
2277 }
2278
2279 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2280
2281 /* only temp file! */
2282 void RE_ReadRenderResult(Scene *scene, Scene *scenode)
2283 {
2284         Render *re;
2285         int winx, winy;
2286         rcti disprect;
2287         
2288         /* calculate actual render result and display size */
2289         winx= (scene->r.size*scene->r.xsch)/100;
2290         winy= (scene->r.size*scene->r.ysch)/100;
2291         
2292         /* only in movie case we render smaller part */
2293         if(scene->r.mode & R_BORDER) {
2294                 disprect.xmin= scene->r.border.xmin*winx;
2295                 disprect.xmax= scene->r.border.xmax*winx;
2296                 
2297                 disprect.ymin= scene->r.border.ymin*winy;
2298                 disprect.ymax= scene->r.border.ymax*winy;
2299         }
2300         else {
2301                 disprect.xmin= disprect.ymin= 0;
2302                 disprect.xmax= winx;
2303                 disprect.ymax= winy;
2304         }
2305         
2306         if(scenode)
2307                 scene= scenode;
2308         
2309         re= RE_NewRender(scene->id.name);
2310         RE_InitState(re, &scene->r, winx, winy, &disprect);
2311         re->scene= scene;
2312         
2313         read_render_result(re);
2314 }
2315
2316 void RE_set_max_threads(int threads)
2317 {
2318         if(threads>0 && threads<=BLENDER_MAX_THREADS)
2319                 commandline_threads= threads;
2320         else
2321                 printf("Error, threads has to be in range 1-%d\n", BLENDER_MAX_THREADS);
2322 }