render stamp drawing is now done everywhere - (not just when saving
[blender-staging.git] / source / blender / render / intern / source / pipeline.c
1 /**  
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. 
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2006 Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <math.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "DNA_group_types.h"
35 #include "DNA_image_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_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         /* sss, 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                 /* duplicate code... */
553                 if(rr->exrhandle) {
554                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.R", 0, 0, NULL);
555                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.G", 0, 0, NULL);
556                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.B", 0, 0, NULL);
557                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.A", 0, 0, NULL);
558                 }
559                 else
560                         rl->rectf= MEM_mapallocN(rectx*recty*sizeof(float)*4, "Combined rgba");
561                 
562                 /* note, this has to be in sync with scene.c */
563                 rl->lay= (1<<20) -1;
564                 rl->layflag= 0x7FFF;    /* solid ztra halo strand */
565                 rl->passflag= SCE_PASS_COMBINED;
566                 
567                 re->r.actlay= 0;
568         }
569         
570         /* border render; calculate offset for use in compositor. compo is centralized coords */
571         rr->xof= re->disprect.xmin + (re->disprect.xmax - re->disprect.xmin)/2 - re->winx/2;
572         rr->yof= re->disprect.ymin + (re->disprect.ymax - re->disprect.ymin)/2 - re->winy/2;
573         
574         return rr;
575 }
576
577 static int render_scene_needs_vector(Render *re)
578 {
579         if((re->r.scemode & R_DOCOMP) || re->r.imtype==R_MULTILAYER) {
580                 SceneRenderLayer *srl;
581         
582                 for(srl= re->scene->r.layers.first; srl; srl= srl->next)
583                         if(!(srl->layflag & SCE_LAY_DISABLE))
584                                 if(srl->passflag & SCE_PASS_VECTOR)
585                                         return 1;
586         }
587         return 0;
588 }
589
590 static void do_merge_tile(RenderResult *rr, RenderResult *rrpart, float *target, float *tile, int pixsize)
591 {
592         int y, ofs, copylen, tilex, tiley;
593         
594         copylen= tilex= rrpart->rectx;
595         tiley= rrpart->recty;
596         
597         if(rrpart->crop) {      /* filters add pixel extra */
598                 tile+= pixsize*(rrpart->crop + rrpart->crop*tilex);
599                 
600                 copylen= tilex - 2*rrpart->crop;
601                 tiley -= 2*rrpart->crop;
602                 
603                 ofs= (rrpart->tilerect.ymin + rrpart->crop)*rr->rectx + (rrpart->tilerect.xmin+rrpart->crop);
604                 target+= pixsize*ofs;
605         }
606         else {
607                 ofs= (rrpart->tilerect.ymin*rr->rectx + rrpart->tilerect.xmin);
608                 target+= pixsize*ofs;
609         }
610
611         copylen *= sizeof(float)*pixsize;
612         tilex *= pixsize;
613         ofs= pixsize*rr->rectx;
614
615         for(y=0; y<tiley; y++) {
616                 memcpy(target, tile, copylen);
617                 target+= ofs;
618                 tile+= tilex;
619         }
620 }
621
622 /* used when rendering to a full buffer, or when reading the exr part-layer-pass file */
623 /* no test happens here if it fits... we also assume layers are in sync */
624 /* is used within threads */
625 static void merge_render_result(RenderResult *rr, RenderResult *rrpart)
626 {
627         RenderLayer *rl, *rlp;
628         RenderPass *rpass, *rpassp;
629         
630         for(rl= rr->layers.first, rlp= rrpart->layers.first; rl && rlp; rl= rl->next, rlp= rlp->next) {
631                 
632                 /* combined */
633                 if(rl->rectf && rlp->rectf)
634                         do_merge_tile(rr, rrpart, rl->rectf, rlp->rectf, 4);
635                 
636                 /* passes are allocated in sync */
637                 for(rpass= rl->passes.first, rpassp= rlp->passes.first; rpass && rpassp; rpass= rpass->next, rpassp= rpassp->next) {
638                         do_merge_tile(rr, rrpart, rpass->rect, rpassp->rect, rpass->channels);
639                 }
640         }
641 }
642
643
644 static void save_render_result_tile(Render *re, RenderPart *pa)
645 {
646         RenderResult *rrpart= pa->result;
647         RenderLayer *rlp;
648         RenderPass *rpassp;
649         int offs, partx, party;
650         
651         BLI_lock_thread(LOCK_IMAGE);
652         
653         for(rlp= rrpart->layers.first; rlp; rlp= rlp->next) {
654                 
655                 if(rrpart->crop) {      /* filters add pixel extra */
656                         offs= (rrpart->crop + rrpart->crop*rrpart->rectx);
657                 }
658                 else {
659                         offs= 0;
660                 }
661                 
662                 /* combined */
663                 if(rlp->rectf) {
664                         int a, xstride= 4;
665                         for(a=0; a<xstride; a++)
666                                 IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a), 
667                                                                 xstride, xstride*pa->rectx, rlp->rectf+a + xstride*offs);
668                 }
669                 
670                 /* passes are allocated in sync */
671                 for(rpassp= rlp->passes.first; rpassp; rpassp= rpassp->next) {
672                         int a, xstride= rpassp->channels;
673                         for(a=0; a<xstride; a++)
674                                 IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a), 
675                                                                         xstride, xstride*pa->rectx, rpassp->rect+a + xstride*offs);
676                 }
677                 
678         }
679
680         party= rrpart->tilerect.ymin + rrpart->crop;
681         partx= rrpart->tilerect.xmin + rrpart->crop;
682         IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
683
684         BLI_unlock_thread(LOCK_IMAGE);
685
686 }
687
688 static void save_empty_result_tiles(Render *re)
689 {
690         RenderPart *pa;
691         
692         IMB_exrtile_clear_channels(re->result->exrhandle);
693                 
694         for(pa= re->parts.first; pa; pa= pa->next) {
695                 if(pa->ready==0) {
696                         int party= pa->disprect.ymin - re->disprect.ymin + pa->crop;
697                         int partx= pa->disprect.xmin - re->disprect.xmin + pa->crop;
698                         IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
699                 }
700         }
701 }
702
703
704 /* for passes read from files, these have names stored */
705 static char *make_pass_name(RenderPass *rpass, int chan)
706 {
707         static char name[16];
708         int len;
709         
710         BLI_strncpy(name, rpass->name, EXR_PASS_MAXNAME);
711         len= strlen(name);
712         name[len]= '.';
713         name[len+1]= rpass->chan_id[chan];
714         name[len+2]= 0;
715
716         return name;
717 }
718
719 /* filename already made absolute */
720 /* called from within UI, saves both rendered result as a file-read result */
721 void RE_WriteRenderResult(RenderResult *rr, char *filename, int compress)
722 {
723         RenderLayer *rl;
724         RenderPass *rpass;
725         void *exrhandle= IMB_exr_get_handle();
726         
727         /* composite result */
728         if(rr->rectf) {
729                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.R", 4, 4*rr->rectx, rr->rectf);
730                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.G", 4, 4*rr->rectx, rr->rectf+1);
731                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.B", 4, 4*rr->rectx, rr->rectf+2);
732                 IMB_exr_add_channel(exrhandle, "Composite", "Combined.A", 4, 4*rr->rectx, rr->rectf+3);
733         }
734         
735         /* add layers/passes and assign channels */
736         for(rl= rr->layers.first; rl; rl= rl->next) {
737                 
738                 /* combined */
739                 if(rl->rectf) {
740                         int a, xstride= 4;
741                         for(a=0; a<xstride; a++)
742                                 IMB_exr_add_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
743                                                                         xstride, xstride*rr->rectx, rl->rectf+a);
744                 }
745                 
746                 /* passes are allocated in sync */
747                 for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
748                         int a, xstride= rpass->channels;
749                         for(a=0; a<xstride; a++) {
750                                 if(rpass->passtype)
751                                         IMB_exr_add_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
752                                                                                 xstride, xstride*rr->rectx, rpass->rect+a);
753                                 else
754                                         IMB_exr_add_channel(exrhandle, rl->name, make_pass_name(rpass, a), 
755                                                                                 xstride, xstride*rr->rectx, rpass->rect+a);
756                         }
757                 }
758         }
759         
760         IMB_exr_begin_write(exrhandle, filename, rr->rectx, rr->recty, compress);
761         
762         IMB_exr_write_channels(exrhandle);
763         IMB_exr_close(exrhandle);
764 }
765
766 /* callbacks for RE_MultilayerConvert */
767 static void *ml_addlayer_cb(void *base, char *str)
768 {
769         RenderResult *rr= base;
770         RenderLayer *rl;
771         
772         rl= MEM_callocN(sizeof(RenderLayer), "new render layer");
773         BLI_addtail(&rr->layers, rl);
774         
775         BLI_strncpy(rl->name, str, EXR_LAY_MAXNAME);
776         return rl;
777 }
778 static void ml_addpass_cb(void *base, void *lay, char *str, float *rect, int totchan, char *chan_id)
779 {
780         RenderLayer *rl= lay;   
781         RenderPass *rpass= MEM_callocN(sizeof(RenderPass), "loaded pass");
782         int a;
783         
784         BLI_addtail(&rl->passes, rpass);
785         rpass->channels= totchan;
786         
787         rpass->passtype= passtype_from_name(str);
788         if(rpass->passtype==0) printf("unknown pass %s\n", str);
789         rl->passflag |= rpass->passtype;
790         
791         BLI_strncpy(rpass->name, str, EXR_PASS_MAXNAME);
792         /* channel id chars */
793         for(a=0; a<totchan; a++)
794                 rpass->chan_id[a]= chan_id[a];
795         
796         rpass->rect= rect;
797 }
798
799 /* from imbuf, if a handle was returned we convert this to render result */
800 RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty)
801 {
802         RenderResult *rr= MEM_callocN(sizeof(RenderResult), "loaded render result");
803         
804         rr->rectx= rectx;
805         rr->recty= recty;
806         
807         IMB_exr_multilayer_convert(exrhandle, rr, ml_addlayer_cb, ml_addpass_cb);
808         
809         return rr;
810 }
811
812 /* called in end of render, to add names to passes... for UI only */
813 static void renderresult_add_names(RenderResult *rr)
814 {
815         RenderLayer *rl;
816         RenderPass *rpass;
817         
818         for(rl= rr->layers.first; rl; rl= rl->next)
819                 for(rpass= rl->passes.first; rpass; rpass= rpass->next)
820                         strcpy(rpass->name, get_pass_name(rpass->passtype, -1));
821 }
822
823
824 /* only for temp buffer files, makes exact copy of render result */
825 static void read_render_result(Render *re)
826 {
827         RenderLayer *rl;
828         RenderPass *rpass;
829         void *exrhandle= IMB_exr_get_handle();
830         int rectx, recty;
831         char str[FILE_MAX];
832         
833         RE_FreeRenderResult(re->result);
834         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
835
836         render_unique_exr_name(re, str);
837         if(IMB_exr_begin_read(exrhandle, str, &rectx, &recty)==0) {
838                 IMB_exr_close(exrhandle);
839                 printf("cannot read: %s\n", str);
840                 return;
841         }
842         
843         if(rectx!=re->result->rectx || recty!=re->result->recty) {
844                 printf("error in reading render result\n");
845         }
846         else {
847                 for(rl= re->result->layers.first; rl; rl= rl->next) {
848                         
849                         /* combined */
850                         if(rl->rectf) {
851                                 int a, xstride= 4;
852                                 for(a=0; a<xstride; a++)
853                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
854                                                                                 xstride, xstride*rectx, rl->rectf+a);
855                         }
856                         
857                         /* passes are allocated in sync */
858                         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
859                                 int a, xstride= rpass->channels;
860                                 for(a=0; a<xstride; a++)
861                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
862                                                                                 xstride, xstride*rectx, rpass->rect+a);
863                         }
864                         
865                 }
866                 IMB_exr_read_channels(exrhandle);
867                 renderresult_add_names(re->result);
868         }
869         
870         IMB_exr_close(exrhandle);
871 }
872
873 /* *************************************************** */
874
875 Render *RE_GetRender(const char *name)
876 {
877         Render *re;
878         
879         /* search for existing renders */
880         for(re= RenderList.first; re; re= re->next) {
881                 if(strncmp(re->name, name, RE_MAXNAME)==0) {
882                         break;
883                 }
884         }
885         return re;
886 }
887
888 /* if you want to know exactly what has been done */
889 RenderResult *RE_GetResult(Render *re)
890 {
891         if(re)
892                 return re->result;
893         return NULL;
894 }
895
896 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
897 {
898         RenderLayer *rl= BLI_findlink(&rr->layers, re->r.actlay);
899         
900         if(rl) 
901                 return rl;
902         else 
903                 return rr->layers.first;
904 }
905
906
907 /* fill provided result struct with what's currently active or done */
908 void RE_GetResultImage(Render *re, RenderResult *rr)
909 {
910         memset(rr, 0, sizeof(RenderResult));
911
912         if(re && re->result) {
913                 RenderLayer *rl;
914                 
915                 rr->rectx= re->result->rectx;
916                 rr->recty= re->result->recty;
917                 
918                 rr->rectf= re->result->rectf;
919                 rr->rectz= re->result->rectz;
920                 rr->rect32= re->result->rect32;
921                 
922                 /* active layer */
923                 rl= render_get_active_layer(re, re->result);
924
925                 if(rl) {
926                         if(rr->rectf==NULL)
927                                 rr->rectf= rl->rectf;
928                         if(rr->rectz==NULL)
929                                 rr->rectz= RE_RenderLayerGetPass(rl, SCE_PASS_Z);       
930                 }
931         }
932 }
933
934 #define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
935 /* caller is responsible for allocating rect in correct size! */
936 void RE_ResultGet32(Render *re, unsigned int *rect)
937 {
938         RenderResult rres;
939         
940         RE_GetResultImage(re, &rres);
941         if(rres.rect32) 
942                 memcpy(rect, rres.rect32, sizeof(int)*rres.rectx*rres.recty);
943         else if(rres.rectf) {
944                 float *fp= rres.rectf;
945                 int tot= rres.rectx*rres.recty;
946                 char *cp= (char *)rect;
947                 
948                 for(;tot>0; tot--, cp+=4, fp+=4) {
949                         cp[0] = FTOCHAR(fp[0]);
950                         cp[1] = FTOCHAR(fp[1]);
951                         cp[2] = FTOCHAR(fp[2]);
952                         cp[3] = FTOCHAR(fp[3]);
953                 }
954         }
955         else
956                 /* else fill with black */
957                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
958 }
959
960
961 RenderStats *RE_GetStats(Render *re)
962 {
963         return &re->i;
964 }
965
966 Render *RE_NewRender(const char *name)
967 {
968         Render *re;
969         
970         /* only one render per name exists */
971         re= RE_GetRender(name);
972         if(re==NULL) {
973                 
974                 /* new render data struct */
975                 re= MEM_callocN(sizeof(Render), "new render");
976                 BLI_addtail(&RenderList, re);
977                 strncpy(re->name, name, RE_MAXNAME);
978         }
979         
980         /* set default empty callbacks */
981         re->display_init= result_nothing;
982         re->display_clear= result_nothing;
983         re->display_draw= result_rcti_nothing;
984         re->timecursor= int_nothing;
985         re->test_break= void_nothing;
986         re->test_return= void_nothing;
987         re->error= print_error;
988         if(G.background)
989                 re->stats_draw= stats_background;
990         else
991                 re->stats_draw= stats_nothing;
992         
993         /* init some variables */
994         re->ycor= 1.0f;
995         
996         return re;
997 }
998
999 /* only call this while you know it will remove the link too */
1000 void RE_FreeRender(Render *re)
1001 {
1002         
1003         free_renderdata_tables(re);
1004         free_sample_tables(re);
1005         
1006         RE_FreeRenderResult(re->result);
1007         RE_FreeRenderResult(re->pushedresult);
1008         
1009         BLI_remlink(&RenderList, re);
1010         MEM_freeN(re);
1011 }
1012
1013 /* exit blender */
1014 void RE_FreeAllRender(void)
1015 {
1016         while(RenderList.first) {
1017                 RE_FreeRender(RenderList.first);
1018         }
1019 }
1020
1021 /* ********* initialize state ******** */
1022
1023
1024 /* what doesn't change during entire render sequence */
1025 /* disprect is optional, if NULL it assumes full window render */
1026 void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect)
1027 {
1028         re->ok= TRUE;   /* maybe flag */
1029         
1030         re->i.starttime= PIL_check_seconds_timer();
1031         re->r= *rd;             /* hardcopy */
1032         
1033         re->winx= winx;
1034         re->winy= winy;
1035         if(disprect) {
1036                 re->disprect= *disprect;
1037                 re->rectx= disprect->xmax-disprect->xmin;
1038                 re->recty= disprect->ymax-disprect->ymin;
1039         }
1040         else {
1041                 re->disprect.xmin= re->disprect.ymin= 0;
1042                 re->disprect.xmax= winx;
1043                 re->disprect.ymax= winy;
1044                 re->rectx= winx;
1045                 re->recty= winy;
1046         }
1047         
1048         if(re->rectx < 2 || re->recty < 2) {
1049                 re->error("Image too small");
1050                 re->ok= 0;
1051         }
1052         else {
1053                 /* check state variables, osa? */
1054                 if(re->r.mode & (R_OSA)) {
1055                         re->osa= re->r.osa;
1056                         if(re->osa>16) re->osa= 16;
1057                 }
1058                 else re->osa= 0;
1059                 
1060                 /* always call, checks for gamma, gamma tables and jitter too */
1061                 make_sample_tables(re); 
1062                 
1063                 /* make empty render result, so display callbacks can initialize */
1064                 RE_FreeRenderResult(re->result);
1065                 re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1066                 re->result->rectx= re->rectx;
1067                 re->result->recty= re->recty;
1068                 
1069                 /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1070                 re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1071                 
1072                 if(commandline_threads>0 && commandline_threads<=BLENDER_MAX_THREADS)
1073                         re->r.threads= commandline_threads;
1074         }
1075 }
1076
1077 void RE_SetDispRect (struct Render *re, rcti *disprect)
1078 {
1079         re->disprect= *disprect;
1080         re->rectx= disprect->xmax-disprect->xmin;
1081         re->recty= disprect->ymax-disprect->ymin;
1082         
1083         /* initialize render result */
1084         RE_FreeRenderResult(re->result);
1085         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1086 }
1087
1088 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1089 {
1090         /* re->ok flag? */
1091         
1092         re->viewplane= *viewplane;
1093         re->clipsta= clipsta;
1094         re->clipend= clipend;
1095         re->r.mode &= ~R_ORTHO;
1096
1097         i_window(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1098         
1099 }
1100
1101 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1102 {
1103         /* re->ok flag? */
1104         
1105         re->viewplane= *viewplane;
1106         re->clipsta= clipsta;
1107         re->clipend= clipend;
1108         re->r.mode |= R_ORTHO;
1109
1110         i_ortho(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1111 }
1112
1113 void RE_SetView(Render *re, float mat[][4])
1114 {
1115         /* re->ok flag? */
1116         Mat4CpyMat4(re->viewmat, mat);
1117         Mat4Invert(re->viewinv, re->viewmat);
1118 }
1119
1120 /* image and movie output has to move to either imbuf or kernel */
1121 void RE_display_init_cb(Render *re, void (*f)(RenderResult *rr))
1122 {
1123         re->display_init= f;
1124 }
1125 void RE_display_clear_cb(Render *re, void (*f)(RenderResult *rr))
1126 {
1127         re->display_clear= f;
1128 }
1129 void RE_display_draw_cb(Render *re, void (*f)(RenderResult *rr, volatile rcti *rect))
1130 {
1131         re->display_draw= f;
1132 }
1133
1134 void RE_stats_draw_cb(Render *re, void (*f)(RenderStats *rs))
1135 {
1136         re->stats_draw= f;
1137 }
1138 void RE_timecursor_cb(Render *re, void (*f)(int))
1139 {
1140         re->timecursor= f;
1141 }
1142
1143 void RE_test_break_cb(Render *re, int (*f)(void))
1144 {
1145         re->test_break= f;
1146 }
1147 void RE_test_return_cb(Render *re, int (*f)(void))
1148 {
1149         re->test_return= f;
1150 }
1151 void RE_error_cb(Render *re, void (*f)(char *str))
1152 {
1153         re->error= f;
1154 }
1155
1156
1157 /* ********* add object data (later) ******** */
1158
1159 /* object is considered fully prepared on correct time etc */
1160 /* includes lights */
1161 void RE_AddObject(Render *re, Object *ob)
1162 {
1163         
1164 }
1165
1166 /* *************************************** */
1167
1168 static int render_display_draw_enabled(Render *re)
1169 {
1170         /* don't show preprocess for previewrender sss */
1171         if(re->sss_points)
1172                 return !(re->r.scemode & R_PREVIEWBUTS);
1173         else
1174                 return 1;
1175 }
1176
1177 static void *do_part_thread(void *pa_v)
1178 {
1179         RenderPart *pa= pa_v;
1180         
1181         /* need to return nicely all parts on esc */
1182         if(R.test_break()==0) {
1183                 pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1184
1185                 if(R.sss_points)
1186                         zbufshade_sss_tile(pa);
1187                 else if(R.osa)
1188                         zbufshadeDA_tile(pa);
1189                 else
1190                         zbufshade_tile(pa);
1191                 
1192                 /* merge too on break! */
1193                 if(R.result->exrhandle)
1194                         save_render_result_tile(&R, pa);
1195                 else if(render_display_draw_enabled(&R))
1196                         merge_render_result(R.result, pa->result);
1197         }
1198         
1199         pa->ready= 1;
1200         
1201         return NULL;
1202 }
1203
1204 /* returns with render result filled, not threaded, used for preview now only */
1205 static void render_tile_processor(Render *re, int firsttile)
1206 {
1207         RenderPart *pa;
1208         
1209         if(re->test_break())
1210                 return;
1211
1212         /* hrmf... exception, this is used for preview render, re-entrant, so render result has to be re-used */
1213         if(re->result==NULL || re->result->layers.first==NULL) {
1214                 if(re->result) RE_FreeRenderResult(re->result);
1215                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1216         }
1217         
1218         re->stats_draw(&re->i);
1219  
1220         if(re->result==NULL)
1221                 return;
1222         
1223         initparts(re);
1224         
1225         /* assuming no new data gets added to dbase... */
1226         R= *re;
1227         
1228         for(pa= re->parts.first; pa; pa= pa->next) {
1229                 if(firsttile) {
1230                         re->i.partsdone++;      /* was reset in initparts */
1231                         firsttile--;
1232                 }
1233                 else {
1234                         do_part_thread(pa);
1235                         
1236                         if(pa->result) {
1237                                 if(!re->test_break()) {
1238                                         if(render_display_draw_enabled(re))
1239                                                 re->display_draw(pa->result, NULL);
1240                                         
1241                                         re->i.partsdone++;
1242                                         re->stats_draw(&re->i);
1243                                 }
1244                                 RE_FreeRenderResult(pa->result);
1245                                 pa->result= NULL;
1246                         }               
1247                         if(re->test_break())
1248                                 break;
1249                 }
1250         }
1251         
1252         freeparts(re);
1253 }
1254
1255 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1256 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1257 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1258 float panorama_pixel_rot(Render *re)
1259 {
1260         float psize, phi, xfac;
1261         
1262         /* size of 1 pixel mapped to viewplane coords */
1263         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
1264         /* angle of a pixel */
1265         phi= atan(psize/re->clipsta);
1266         
1267         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1268         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1269         xfac= atan(0.5f*xfac/re->clipsta); 
1270         /* and how much the same viewplane angle is wrapped */
1271         psize= 0.5f*phi*((float)re->partx);
1272         
1273         /* the ratio applied to final per-pixel angle */
1274         phi*= xfac/psize;
1275         
1276         return phi;
1277 }
1278
1279 /* call when all parts stopped rendering, to find the next Y slice */
1280 /* if slice found, it rotates the dbase */
1281 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1282 {
1283         RenderPart *pa, *best= NULL;
1284         
1285         *minx= re->winx;
1286         
1287         /* most left part of the non-rendering parts */
1288         for(pa= re->parts.first; pa; pa= pa->next) {
1289                 if(pa->ready==0 && pa->nr==0) {
1290                         if(pa->disprect.xmin < *minx) {
1291                                 best= pa;
1292                                 *minx= pa->disprect.xmin;
1293                         }
1294                 }
1295         }
1296                         
1297         if(best) {
1298                 float phi= panorama_pixel_rot(re);
1299
1300                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1301                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
1302                 
1303                 /* shift viewplane */
1304                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1305                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1306                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1307                 Mat4CpyMat4(R.winmat, re->winmat);
1308                 
1309                 /* rotate database according to part coordinates */
1310                 project_renderdata(re, projectverto, 1, -R.panodxp*phi);
1311                 R.panosi= sin(R.panodxp*phi);
1312                 R.panoco= cos(R.panodxp*phi);
1313         }
1314         return best;
1315 }
1316
1317 static RenderPart *find_next_part(Render *re, int minx)
1318 {
1319         RenderPart *pa, *best= NULL;
1320         int centx=re->winx/2, centy=re->winy/2, tot=1;
1321         int mindist, distx, disty;
1322         
1323         /* find center of rendered parts, image center counts for 1 too */
1324         for(pa= re->parts.first; pa; pa= pa->next) {
1325                 if(pa->ready) {
1326                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1327                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1328                         tot++;
1329                 }
1330         }
1331         centx/=tot;
1332         centy/=tot;
1333         
1334         /* closest of the non-rendering parts */
1335         mindist= re->winx*re->winy;
1336         for(pa= re->parts.first; pa; pa= pa->next) {
1337                 if(pa->ready==0 && pa->nr==0) {
1338                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1339                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1340                         distx= (int)sqrt(distx*distx + disty*disty);
1341                         if(distx<mindist) {
1342                                 if(re->r.mode & R_PANORAMA) {
1343                                         if(pa->disprect.xmin==minx) {
1344                                                 best= pa;
1345                                                 mindist= distx;
1346                                         }
1347                                 }
1348                                 else {
1349                                         best= pa;
1350                                         mindist= distx;
1351                                 }
1352                         }
1353                 }
1354         }
1355         return best;
1356 }
1357
1358 static void print_part_stats(Render *re, RenderPart *pa)
1359 {
1360         char str[64];
1361         
1362         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1363         re->i.infostr= str;
1364         re->stats_draw(&re->i);
1365         re->i.infostr= NULL;
1366 }
1367
1368 static void threaded_tile_processor(Render *re)
1369 {
1370         ListBase threads;
1371         RenderPart *pa, *nextpa;
1372         RenderResult *rr;
1373         rctf viewplane= re->viewplane;
1374         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1375         
1376         /* first step; the entire render result, or prepare exr buffer saving */
1377         RE_FreeRenderResult(re->result);
1378         rr= re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & R_EXR_TILE_FILE);
1379         
1380         if(rr==NULL)
1381                 return;
1382         /* warning; no return here without closing exr file */
1383 //      if(re->re->test_break())
1384 //              return;
1385         
1386         initparts(re);
1387         
1388         if(rr->exrhandle) {
1389                 char str[FILE_MAX];
1390                 
1391                 render_unique_exr_name(re, str);
1392                 
1393                 printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1394                 IMB_exrtile_begin_write(rr->exrhandle, str, rr->rectx, rr->recty, rr->rectx/re->xparts, rr->recty/re->yparts);
1395         }
1396         
1397         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1398         
1399         /* assuming no new data gets added to dbase... */
1400         R= *re;
1401         
1402         /* set threadsafe break */
1403         R.test_break= thread_break;
1404         
1405         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1406         if(re->r.mode & R_PANORAMA)
1407                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1408         else
1409                 nextpa= find_next_part(re, 0);
1410         
1411         while(rendering) {
1412                 
1413                 if(re->test_break())
1414                         PIL_sleep_ms(50);
1415                 else if(nextpa && BLI_available_threads(&threads)) {
1416                         drawtimer= 0;
1417                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1418                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1419                         BLI_insert_thread(&threads, nextpa);
1420
1421                         nextpa= find_next_part(re, minx);
1422                 }
1423                 else if(re->r.mode & R_PANORAMA) {
1424                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1425                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1426                         else {
1427                                 PIL_sleep_ms(50);
1428                                 drawtimer++;
1429                         }
1430                 }
1431                 else {
1432                         PIL_sleep_ms(50);
1433                         drawtimer++;
1434                 }
1435                 
1436                 /* check for ready ones to display, and if we need to continue */
1437                 rendering= 0;
1438                 hasdrawn= 0;
1439                 for(pa= re->parts.first; pa; pa= pa->next) {
1440                         if(pa->ready) {
1441                                 
1442                                 BLI_remove_thread(&threads, pa);
1443                                 
1444                                 if(pa->result) {
1445                                         if(render_display_draw_enabled(re))
1446                                                 re->display_draw(pa->result, NULL);
1447                                         print_part_stats(re, pa);
1448                                         
1449                                         RE_FreeRenderResult(pa->result);
1450                                         pa->result= NULL;
1451                                         re->i.partsdone++;
1452                                         hasdrawn= 1;
1453                                 }
1454                         }
1455                         else {
1456                                 rendering= 1;
1457                                 if(pa->nr && pa->result && drawtimer>20) {
1458                                         if(render_display_draw_enabled(re))
1459                                                 re->display_draw(pa->result, &pa->result->renrect);
1460                                         hasdrawn= 1;
1461                                 }
1462                         }
1463                 }
1464                 if(hasdrawn)
1465                         drawtimer= 0;
1466
1467                 /* on break, wait for all slots to get freed */
1468                 if( (g_break=re->test_break()) && BLI_available_threads(&threads)==re->r.threads)
1469                         rendering= 0;
1470                 
1471         }
1472         
1473         if(rr->exrhandle) {
1474                 save_empty_result_tiles(re);
1475                 IMB_exr_close(rr->exrhandle);
1476                 rr->exrhandle= NULL;
1477                 read_render_result(re);
1478         }
1479         
1480         /* unset threadsafety */
1481         g_break= 0;
1482         
1483         BLI_end_threads(&threads);
1484         freeparts(re);
1485         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1486
1487 }
1488
1489 /* currently only called by preview renders and envmap */
1490 void RE_TileProcessor(Render *re, int firsttile, int threaded)
1491 {
1492         /* the partsdone variable has to be reset to firsttile, to survive esc before it was set to zero */
1493         
1494         re->i.partsdone= firsttile;
1495
1496         re->i.starttime= PIL_check_seconds_timer();
1497
1498         if(threaded)
1499                 threaded_tile_processor(re);
1500         else
1501                 render_tile_processor(re, firsttile);
1502                 
1503         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1504         re->stats_draw(&re->i);
1505 }
1506
1507
1508 /* ************  This part uses API, for rendering Blender scenes ********** */
1509
1510 static void do_render_3d(Render *re)
1511 {
1512         
1513 //      re->cfra= cfra; /* <- unused! */
1514         
1515         /* make render verts/faces/halos/lamps */
1516         if(render_scene_needs_vector(re))
1517                 RE_Database_FromScene_Vectors(re, re->scene);
1518         else
1519            RE_Database_FromScene(re, re->scene, 1);
1520         
1521         threaded_tile_processor(re);
1522         
1523         /* do left-over 3d post effects (flares) */
1524         if(re->flag & R_HALO)
1525                 if(!re->test_break())
1526                         add_halo_flare(re);
1527
1528         
1529         /* free all render verts etc */
1530         RE_Database_Free(re);
1531 }
1532
1533 /* called by blur loop, accumulate renderlayers */
1534 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1535 {
1536         float mfac= 1.0f - blurfac;
1537         int a, b, stride= channels*rr->rectx;
1538         int len= stride*sizeof(float);
1539         
1540         for(a=0; a<rr->recty; a++) {
1541                 if(blurfac==1.0f) {
1542                         memcpy(rectf, rectf1, len);
1543                 }
1544                 else {
1545                         float *rf= rectf, *rf1= rectf1;
1546                         
1547                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1548                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1549                         }
1550                 }
1551                 rectf+= stride;
1552                 rectf1+= stride;
1553         }
1554 }
1555
1556 /* called by blur loop, accumulate renderlayers */
1557 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac)
1558 {
1559         RenderLayer *rl, *rl1;
1560         RenderPass *rpass, *rpass1;
1561         
1562         rl1= brr->layers.first;
1563         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1564                 
1565                 /* combined */
1566                 if(rl->rectf && rl1->rectf)
1567                         addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1568                 
1569                 /* passes are allocated in sync */
1570                 rpass1= rl1->passes.first;
1571                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1572                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1573                 }
1574         }
1575 }
1576
1577 /* main blur loop, can be called by fields too */
1578 static void do_render_blur_3d(Render *re)
1579 {
1580         RenderResult *rres;
1581         float blurfac;
1582         int blur= re->r.osa;
1583         
1584         /* create accumulation render result */
1585         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1586         
1587         /* do the blur steps */
1588         while(blur--) {
1589                 set_mblur_offs( re->r.blurfac*((float)(re->r.osa-blur))/(float)re->r.osa );
1590                 
1591                 re->i.curblur= re->r.osa-blur;  /* stats */
1592                 
1593                 do_render_3d(re);
1594                 
1595                 blurfac= 1.0f/(float)(re->r.osa-blur);
1596                 
1597                 merge_renderresult_blur(rres, re->result, blurfac);
1598                 if(re->test_break()) break;
1599         }
1600         
1601         /* swap results */
1602         RE_FreeRenderResult(re->result);
1603         re->result= rres;
1604         
1605         set_mblur_offs(0.0f);
1606         re->i.curblur= 0;       /* stats */
1607         
1608         /* weak... the display callback wants an active renderlayer pointer... */
1609         re->result->renlay= render_get_active_layer(re, re->result);
1610         re->display_draw(re->result, NULL);     
1611 }
1612
1613
1614 /* function assumes rectf1 and rectf2 to be half size of rectf */
1615 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1616 {
1617         int a, stride= channels*rr->rectx;
1618         int len= stride*sizeof(float);
1619         
1620         for(a=0; a<rr->recty; a+=2) {
1621                 memcpy(rectf, rectf1, len);
1622                 rectf+= stride;
1623                 rectf1+= stride;
1624                 memcpy(rectf, rectf2, len);
1625                 rectf+= stride;
1626                 rectf2+= stride;
1627         }
1628 }
1629
1630 /* merge render results of 2 fields */
1631 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1632 {
1633         RenderLayer *rl, *rl1, *rl2;
1634         RenderPass *rpass, *rpass1, *rpass2;
1635         
1636         rl1= rr1->layers.first;
1637         rl2= rr2->layers.first;
1638         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1639                 
1640                 /* combined */
1641                 if(rl->rectf && rl1->rectf && rl2->rectf)
1642                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1643                 
1644                 /* passes are allocated in sync */
1645                 rpass1= rl1->passes.first;
1646                 rpass2= rl2->passes.first;
1647                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1648                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1649                 }
1650         }
1651 }
1652
1653
1654 /* interleaves 2 frames */
1655 static void do_render_fields_3d(Render *re)
1656 {
1657         RenderResult *rr1, *rr2= NULL;
1658         
1659         /* no render result was created, we can safely halve render y */
1660         re->winy /= 2;
1661         re->recty /= 2;
1662         re->disprect.ymin /= 2;
1663         re->disprect.ymax /= 2;
1664         
1665         re->i.curfield= 1;      /* stats */
1666         
1667         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1668         RE_SetCamera(re, re->scene->camera);
1669         if(re->r.mode & R_MBLUR)
1670                 do_render_blur_3d(re);
1671         else
1672                 do_render_3d(re);
1673         rr1= re->result;
1674         re->result= NULL;
1675         
1676         /* second field */
1677         if(!re->test_break()) {
1678                 
1679                 re->i.curfield= 2;      /* stats */
1680                 
1681                 re->flag |= R_SEC_FIELD;
1682                 if((re->r.mode & R_FIELDSTILL)==0) 
1683                         set_field_offs(0.5f);
1684                 RE_SetCamera(re, re->scene->camera);
1685                 if(re->r.mode & R_MBLUR)
1686                         do_render_blur_3d(re);
1687                 else
1688                         do_render_3d(re);
1689                 re->flag &= ~R_SEC_FIELD;
1690                 set_field_offs(0.0f);
1691                 
1692                 rr2= re->result;
1693         }
1694         
1695         /* allocate original height new buffers */
1696         re->winy *= 2;
1697         re->recty *= 2;
1698         re->disprect.ymin *= 2;
1699         re->disprect.ymax *= 2;
1700         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1701         
1702         if(rr2) {
1703                 if(re->r.mode & R_ODDFIELD)
1704                         merge_renderresult_fields(re->result, rr2, rr1);
1705                 else
1706                         merge_renderresult_fields(re->result, rr1, rr2);
1707                 
1708                 RE_FreeRenderResult(rr2);
1709         }
1710         RE_FreeRenderResult(rr1);
1711         
1712         re->i.curfield= 0;      /* stats */
1713         
1714         /* weak... the display callback wants an active renderlayer pointer... */
1715         re->result->renlay= render_get_active_layer(re, re->result);
1716         re->display_draw(re->result, NULL);
1717 }
1718
1719 static void load_backbuffer(Render *re)
1720 {
1721         if(re->r.alphamode == R_ADDSKY) {
1722                 ImBuf *ibuf;
1723                 char name[256];
1724                 
1725                 strcpy(name, re->r.backbuf);
1726                 BLI_convertstringcode(name, G.sce, re->r.cfra);
1727                 
1728                 if(re->backbuf) {
1729                         re->backbuf->id.us--;
1730                         if(re->backbuf->id.us<1)
1731                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
1732                 }
1733                 
1734                 re->backbuf= BKE_add_image_file(name);
1735                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
1736                 if(ibuf==NULL) {
1737                         // error() doesnt work with render window open
1738                         //error("No backbuf there!");
1739                         printf("Error: No backbuf %s\n", name);
1740                 }
1741                 else {
1742                         if (re->r.mode & R_FIELDS)
1743                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
1744                 }
1745         }
1746 }
1747
1748 /* main render routine, no compositing */
1749 static void do_render_fields_blur_3d(Render *re)
1750 {
1751         /* also check for camera here */
1752         if(re->scene->camera==NULL) {
1753                 printf("ERROR: Cannot render, no camera\n");
1754                 G.afbreek= 1;
1755                 return;
1756         }
1757         
1758         /* backbuffer initialize */
1759         if(re->r.bufflag & 1)
1760                 load_backbuffer(re);
1761
1762         /* now use renderdata and camera to set viewplane */
1763         RE_SetCamera(re, re->scene->camera);
1764         
1765         if(re->r.mode & R_FIELDS)
1766                 do_render_fields_3d(re);
1767         else if(re->r.mode & R_MBLUR)
1768                 do_render_blur_3d(re);
1769         else
1770                 do_render_3d(re);
1771         
1772         /* when border render, check if we have to insert it in black */
1773         if(re->result) {
1774                 if(re->r.mode & R_BORDER) {
1775                         if((re->r.mode & R_CROP)==0) {
1776                                 RenderResult *rres;
1777                                 
1778                                 /* sub-rect for merge call later on */
1779                                 re->result->tilerect= re->disprect;
1780                                 
1781                                 /* this copying sequence could become function? */
1782                                 re->disprect.xmin= re->disprect.ymin= 0;
1783                                 re->disprect.xmax= re->winx;
1784                                 re->disprect.ymax= re->winy;
1785                                 re->rectx= re->winx;
1786                                 re->recty= re->winy;
1787                                 
1788                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1789                                 
1790                                 merge_render_result(rres, re->result);
1791                                 RE_FreeRenderResult(re->result);
1792                                 re->result= rres;
1793                                 
1794                                 /* weak... the display callback wants an active renderlayer pointer... */
1795                                 re->result->renlay= render_get_active_layer(re, re->result);
1796                                 
1797                                 re->display_init(re->result);
1798                                 re->display_draw(re->result, NULL);
1799                         }
1800                 }
1801         }
1802 }
1803
1804
1805 /* within context of current Render *re, render another scene.
1806    it uses current render image size and disprect, but doesn't execute composite
1807 */
1808 static void render_scene(Render *re, Scene *sce, int cfra)
1809 {
1810         Render *resc= RE_NewRender(sce->id.name);
1811         
1812         sce->r.cfra= cfra;
1813                 
1814         /* initial setup */
1815         RE_InitState(resc, &sce->r, re->winx, re->winy, &re->disprect);
1816         
1817         /* this to enable this scene to create speed vectors */
1818         resc->r.scemode |= R_DOCOMP;
1819         
1820         /* still unsure entity this... */
1821         resc->scene= sce;
1822         
1823         /* ensure scene has depsgraph, base flags etc OK. Warning... also sets G.scene */
1824         set_scene_bg(sce);
1825
1826         /* copy callbacks */
1827         resc->display_draw= re->display_draw;
1828         resc->test_break= re->test_break;
1829         resc->stats_draw= re->stats_draw;
1830         
1831         do_render_fields_blur_3d(resc);
1832 }
1833
1834 static void ntree_render_scenes(Render *re)
1835 {
1836         bNode *node;
1837         int cfra= re->scene->r.cfra;
1838         
1839         if(re->scene->nodetree==NULL) return;
1840         
1841         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
1842         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1843                 if(node->type==CMP_NODE_R_LAYERS) {
1844                         if(node->id) {
1845                                 if(node->id != (ID *)re->scene)
1846                                         node->id->flag |= LIB_DOIT;
1847                                 else
1848                                         node->id->flag &= ~LIB_DOIT;
1849                         }
1850                 }
1851         }
1852         
1853         /* now foreach render-result node tagged we do a full render */
1854         /* results are stored in a way compisitor will find it */
1855         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1856                 if(node->type==CMP_NODE_R_LAYERS) {
1857                         if(node->id && node->id != (ID *)re->scene) {
1858                                 if(node->id->flag & LIB_DOIT) {
1859                                         render_scene(re, (Scene *)node->id, cfra);
1860                                         node->id->flag &= ~LIB_DOIT;
1861                                 }
1862                         }
1863                 }
1864         }
1865         
1866         /* still the global... */
1867         if(G.scene!=re->scene)
1868                 set_scene_bg(re->scene);
1869         
1870 }
1871
1872 /* helper call to detect if theres a composite with render-result node */
1873 static int composite_needs_render(Scene *sce)
1874 {
1875         bNodeTree *ntree= sce->nodetree;
1876         bNode *node;
1877         
1878         if(ntree==NULL) return 1;
1879         if(sce->use_nodes==0) return 1;
1880         if((sce->r.scemode & R_DOCOMP)==0) return 1;
1881                 
1882         for(node= ntree->nodes.first; node; node= node->next) {
1883                 if(node->type==CMP_NODE_R_LAYERS)
1884                         if(node->id==NULL || node->id==&sce->id)
1885                                 return 1;
1886         }
1887         return 0;
1888 }
1889
1890 /* bad call... need to think over proper method still */
1891 static void render_composit_stats(char *str)
1892 {
1893         R.i.infostr= str;
1894         R.stats_draw(&R.i);
1895         R.i.infostr= NULL;
1896 }
1897
1898 /* returns fully composited render-result on given time step (in RenderData) */
1899 static void do_render_composite_fields_blur_3d(Render *re)
1900 {
1901         bNodeTree *ntree= re->scene->nodetree;
1902         
1903         /* INIT seeding, compositor can use random texture */
1904         BLI_srandom(re->r.cfra);
1905         
1906         if(composite_needs_render(re->scene)) {
1907                 /* save memory... free all cached images */
1908                 ntreeFreeCache(ntree);
1909                 
1910                 do_render_fields_blur_3d(re);
1911         }
1912         
1913         /* swap render result */
1914         if(re->r.scemode & R_SINGLE_LAYER)
1915                 pop_render_result(re);
1916         
1917         if(!re->test_break() && ntree) {
1918                 ntreeCompositTagRender(re->scene);
1919                 ntreeCompositTagAnimated(ntree);
1920                 
1921                 if(re->r.scemode & R_DOCOMP) {
1922                         /* checks if there are render-result nodes that need scene */
1923                         if((re->r.scemode & R_SINGLE_LAYER)==0)
1924                                 ntree_render_scenes(re);
1925                         
1926                         if(!re->test_break()) {
1927                                 ntree->stats_draw= render_composit_stats;
1928                                 ntree->test_break= re->test_break;
1929                                 /* in case it was never initialized */
1930                                 R.stats_draw= re->stats_draw;
1931                                 
1932                                 ntreeCompositExecTree(ntree, &re->r, G.background==0);
1933                                 ntree->stats_draw= NULL;
1934                                 ntree->test_break= NULL;
1935                         }
1936                 }
1937         }
1938
1939         re->display_draw(re->result, NULL);
1940 }
1941
1942 #ifndef DISABLE_YAFRAY
1943 /* yafray: main yafray render/export call */
1944 static void yafrayRender(Render *re)
1945 {
1946         RE_FreeRenderResult(re->result);
1947         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1948         
1949         // need this too, for aspect/ortho/etc info
1950         RE_SetCamera(re, re->scene->camera);
1951
1952         // switch must be done before prepareScene()
1953         if (!re->r.YFexportxml)
1954                 YAF_switchFile();
1955         else
1956                 YAF_switchPlugin();
1957         
1958         printf("Starting scene conversion.\n");
1959         RE_Database_FromScene(re, re->scene, 1);
1960         printf("Scene conversion done.\n");
1961         
1962         re->i.starttime = PIL_check_seconds_timer();
1963         
1964         YAF_exportScene(re);
1965
1966         /* also needed for yafray border render, straight copy from do_render_fields_blur_3d() */
1967         /* when border render, check if we have to insert it in black */
1968         if(re->result) {
1969                 if(re->r.mode & R_BORDER) {
1970                         if((re->r.mode & R_CROP)==0) {
1971                                 RenderResult *rres;
1972                                 
1973                                 /* sub-rect for merge call later on */
1974                                 re->result->tilerect= re->disprect;
1975                                 
1976                                 /* this copying sequence could become function? */
1977                                 re->disprect.xmin= re->disprect.ymin= 0;
1978                                 re->disprect.xmax= re->winx;
1979                                 re->disprect.ymax= re->winy;
1980                                 re->rectx= re->winx;
1981                                 re->recty= re->winy;
1982                                 
1983                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1984                                 
1985                                 merge_render_result(rres, re->result);
1986                                 RE_FreeRenderResult(re->result);
1987                                 re->result= rres;
1988                                 
1989                                 re->display_init(re->result);
1990                                 re->display_draw(re->result, NULL);
1991                         }
1992                 }
1993         }
1994
1995         re->i.lastframetime = PIL_check_seconds_timer()- re->i.starttime;
1996         re->stats_draw(&re->i);
1997         
1998         RE_Database_Free(re);
1999 }
2000
2001
2002
2003 #endif /* disable yafray */
2004
2005 static void renderresult_stampinfo()
2006 {
2007         RenderResult rres;
2008         /* this is the basic trick to get the displayed float or char rect from render result */
2009         RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
2010         BKE_stamp_buf((unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty);
2011 }
2012
2013 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2014
2015 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2016 static void do_render_all_options(Render *re)
2017 {
2018         re->i.starttime= PIL_check_seconds_timer();
2019
2020         /* ensure no images are in memory from previous animated sequences */
2021         BKE_image_all_free_anim_ibufs(re->r.cfra);
2022         
2023         if(re->r.scemode & R_DOSEQ) {
2024                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2025                 if(!re->test_break()) 
2026                         do_render_seq(re->result, re->r.cfra);
2027                 
2028                 re->stats_draw(&re->i);
2029                 re->display_draw(re->result, NULL);
2030                 
2031         }
2032         else {
2033 #ifndef DISABLE_YAFRAY
2034                 if(re->r.renderer==R_YAFRAY)
2035                         yafrayRender(re);
2036                 else
2037                         do_render_composite_fields_blur_3d(re);
2038 #else
2039                 do_render_composite_fields_blur_3d(re);
2040 #endif
2041         }
2042         
2043         /* for UI only */
2044         renderresult_add_names(re->result);
2045         
2046         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2047         
2048         /* stamp image info here */
2049         if(G.scene->r.scemode & R_STAMP_INFO && G.scene->r.stamp & R_STAMP_DRAW)
2050                 renderresult_stampinfo();
2051         
2052         re->stats_draw(&re->i);
2053 }
2054
2055 static int is_rendering_allowed(Render *re)
2056 {
2057         SceneRenderLayer *srl;
2058         
2059         /* forbidden combinations */
2060         if(re->r.mode & R_PANORAMA) {
2061                 if(re->r.mode & R_BORDER) {
2062                         re->error("No border supported for Panorama");
2063                         return 0;
2064                 }
2065                 if(re->r.mode & R_ORTHO) {
2066                         re->error("No Ortho render possible for Panorama");
2067                         return 0;
2068                 }
2069         }
2070         
2071         if(re->r.mode & R_BORDER) {
2072                 if(re->r.border.xmax <= re->r.border.xmin || 
2073                    re->r.border.ymax <= re->r.border.ymin) {
2074                         re->error("No border area selected.");
2075                         return 0;
2076                 }
2077                 if(re->r.scemode & R_EXR_TILE_FILE) {
2078                         re->error("Border render and Buffer-save not supported yet");
2079                         return 0;
2080                 }
2081         }
2082         
2083         if(re->r.scemode & R_EXR_TILE_FILE) {
2084                 char str[FILE_MAX];
2085                 
2086                 render_unique_exr_name(re, str);
2087                 
2088                 if (BLI_is_writable(str)==0) {
2089                         re->error("Can not save render buffers, check the temp default path");
2090                         return 0;
2091                 }
2092                 
2093         }
2094         
2095         if(re->r.scemode & R_DOCOMP) {
2096                 if(re->scene->use_nodes) {
2097                         bNodeTree *ntree= re->scene->nodetree;
2098                         bNode *node;
2099                 
2100                         if(ntree==NULL) {
2101                                 re->error("No Nodetree in Scene");
2102                                 return 0;
2103                         }
2104                         
2105                         for(node= ntree->nodes.first; node; node= node->next)
2106                                 if(node->type==CMP_NODE_COMPOSITE)
2107                                         break;
2108                         
2109                         
2110                         if(node==NULL) {
2111                                 re->error("No Render Output Node in Scene");
2112                                 return 0;
2113                         }
2114                 }
2115         }
2116         
2117         /* check valid camera, without camera render is OK (compo, seq) */
2118         if(re->scene->camera==NULL)
2119                 re->scene->camera= scene_find_camera(re->scene);
2120         
2121         if(!(re->r.scemode & (R_DOSEQ|R_DOCOMP))) {
2122                 if(re->scene->camera==NULL) {
2123                         re->error("No camera");
2124                         return 0;
2125                 }
2126         }
2127         
2128         /* layer flag tests */
2129         if(re->r.scemode & R_SINGLE_LAYER) {
2130                 srl= BLI_findlink(&re->scene->r.layers, re->r.actlay);
2131                 /* force layer to be enabled */
2132                 srl->layflag &= ~SCE_LAY_DISABLE;
2133         }
2134         
2135         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
2136                 if(!(srl->layflag & SCE_LAY_DISABLE))
2137                         break;
2138         if(srl==NULL) {
2139                 re->error("All RenderLayers are disabled");
2140                 return 0;
2141         }
2142         
2143         /* renderer */
2144         if(!ELEM(re->r.renderer, R_INTERN, R_YAFRAY)) {
2145                 re->error("Unknown render engine set");
2146                 return 0;
2147         }
2148         return 1;
2149 }
2150
2151 /* evaluating scene options for general Blender render */
2152 static int render_initialize_from_scene(Render *re, Scene *scene)
2153 {
2154         int winx, winy;
2155         rcti disprect;
2156         
2157         /* r.xsch and r.ysch has the actual view window size
2158                 r.border is the clipping rect */
2159         
2160         /* calculate actual render result and display size */
2161         winx= (scene->r.size*scene->r.xsch)/100;
2162         winy= (scene->r.size*scene->r.ysch)/100;
2163         
2164         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2165         if(scene->r.mode & R_BORDER) {
2166                 disprect.xmin= scene->r.border.xmin*winx;
2167                 disprect.xmax= scene->r.border.xmax*winx;
2168                 
2169                 disprect.ymin= scene->r.border.ymin*winy;
2170                 disprect.ymax= scene->r.border.ymax*winy;
2171         }
2172         else {
2173                 disprect.xmin= disprect.ymin= 0;
2174                 disprect.xmax= winx;
2175                 disprect.ymax= winy;
2176         }
2177         
2178         if(scene->r.scemode & R_EXR_TILE_FILE) {
2179                 int partx= winx/scene->r.xparts, party= winy/scene->r.yparts;
2180                 
2181                 /* stupid exr tiles dont like different sizes */
2182                 if(winx != partx*scene->r.xparts || winy != party*scene->r.yparts) {
2183                         re->error("Sorry... exr tile saving only allowed with equally sized parts");
2184                         return 0;
2185                 }
2186                 if((scene->r.mode & R_FIELDS) && (party & 1)) {
2187                         re->error("Sorry... exr tile saving only allowed with equally sized parts");
2188                         return 0;
2189                 }
2190         }
2191         
2192         if(scene->r.scemode & R_SINGLE_LAYER)
2193                 push_render_result(re);
2194         
2195         RE_InitState(re, &scene->r, winx, winy, &disprect);
2196         
2197         /* initstate makes new result, have to send changed tags around */
2198         ntreeCompositTagRender(re->scene);
2199         
2200         re->scene= scene;
2201         if(!is_rendering_allowed(re))
2202                 return 0;
2203         
2204         re->display_init(re->result);
2205         re->display_clear(re->result);
2206         
2207         return 1;
2208 }
2209
2210 /* general Blender frame render call */
2211 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
2212 {
2213         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2214         /* is also set by caller renderwin.c */
2215         G.rendering= 1;
2216         
2217         scene->r.cfra= frame;
2218         
2219         if(render_initialize_from_scene(re, scene)) {
2220                 do_render_all_options(re);
2221         }
2222         
2223         /* UGLY WARNING */
2224         G.rendering= 0;
2225 }
2226
2227 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
2228 {
2229         char name[FILE_MAX];
2230         RenderResult rres;
2231         
2232         RE_GetResultImage(re, &rres);
2233
2234         /* write movie or image */
2235         if(BKE_imtype_is_movie(scene->r.imtype)) {
2236                 int dofree = 0;
2237                 /* note; the way it gets 32 bits rects is weak... */
2238                 if(rres.rect32==NULL) {
2239                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2240                         dofree = 1;
2241                 }
2242                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
2243                 mh->append_movie(scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
2244                 if(dofree) {
2245                         MEM_freeN(rres.rect32);
2246                 }
2247                 printf("Append frame %d", scene->r.cfra);
2248         } 
2249         else {
2250                 BKE_makepicstring(name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2251                 
2252                 if(re->r.imtype==R_MULTILAYER) {
2253                         if(re->result) {
2254                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2255                                 printf("Saved: %s", name);
2256                         }
2257                 }
2258                 else {
2259                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
2260                         int ok;
2261                         
2262                                         /* if not exists, BKE_write_ibuf makes one */
2263                         ibuf->rect= (unsigned int *)rres.rect32;    
2264                         ibuf->rect_float= rres.rectf;
2265                         ibuf->zbuf_float= rres.rectz;
2266                         
2267                         /* float factor for random dither, imbuf takes care of it */
2268                         ibuf->dither= scene->r.dither_intensity;
2269
2270                         ok= BKE_write_ibuf(ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2271                         
2272                         if(ok==0) {
2273                                 printf("Render error: cannot save %s\n", name);
2274                                 G.afbreek=1;
2275                         }
2276                         else printf("Saved: %s", name);
2277                         
2278                         /* optional preview images for exr */
2279                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
2280                                 if(BLI_testextensie(name, ".exr")) 
2281                                         name[strlen(name)-4]= 0;
2282                                 BKE_add_image_extension(name, R_JPEG90);
2283                                 ibuf->depth= 24; 
2284                                 BKE_write_ibuf(ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
2285                                 printf("\nSaved: %s", name);
2286                         }
2287                         
2288                                         /* imbuf knows which rects are not part of ibuf */
2289                         IMB_freeImBuf(ibuf);
2290                 }
2291         }
2292         
2293         BLI_timestr(re->i.lastframetime, name);
2294         printf(" Time: %s\n", name);
2295         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2296 }
2297
2298 /* saves images to disk */
2299 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
2300 {
2301         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
2302         int cfrao= scene->r.cfra;
2303         
2304         /* do not call for each frame, it initializes & pops output window */
2305         if(!render_initialize_from_scene(re, scene))
2306                 return;
2307         
2308         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2309         /* is also set by caller renderwin.c */
2310         G.rendering= 1;
2311         
2312         if(BKE_imtype_is_movie(scene->r.imtype))
2313                 mh->start_movie(&re->r, re->rectx, re->recty);
2314         
2315         if (mh->get_next_frame) {
2316                 while (!(G.afbreek == 1)) {
2317                         int nf = mh->get_next_frame();
2318                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2319                                 scene->r.cfra = re->r.cfra = nf;
2320                                 
2321                                 do_render_all_options(re);
2322
2323                                 if(re->test_break() == 0) {
2324                                         do_write_image_or_movie(re, scene, mh);
2325                                 }
2326                         } else {
2327                                 re->test_break();
2328                         }
2329                 }
2330         } else {
2331                 for(scene->r.cfra= sfra; 
2332                     scene->r.cfra<=efra; scene->r.cfra++) {
2333                         re->r.cfra= scene->r.cfra;         /* weak.... */
2334                 
2335                         do_render_all_options(re);
2336
2337                         if(re->test_break() == 0) {
2338                                 do_write_image_or_movie(re, scene, mh);
2339                         }
2340                 
2341                         if(G.afbreek==1) break;
2342                 }
2343         }
2344         
2345         /* end movie */
2346         if(BKE_imtype_is_movie(scene->r.imtype))
2347                 mh->end_movie();
2348
2349         scene->r.cfra= cfrao;
2350         
2351         /* UGLY WARNING */
2352         G.rendering= 0;
2353 }
2354
2355 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2356
2357 /* only temp file! */
2358 void RE_ReadRenderResult(Scene *scene, Scene *scenode)
2359 {
2360         Render *re;
2361         int winx, winy;
2362         rcti disprect;
2363         
2364         /* calculate actual render result and display size */
2365         winx= (scene->r.size*scene->r.xsch)/100;
2366         winy= (scene->r.size*scene->r.ysch)/100;
2367         
2368         /* only in movie case we render smaller part */
2369         if(scene->r.mode & R_BORDER) {
2370                 disprect.xmin= scene->r.border.xmin*winx;
2371                 disprect.xmax= scene->r.border.xmax*winx;
2372                 
2373                 disprect.ymin= scene->r.border.ymin*winy;
2374                 disprect.ymax= scene->r.border.ymax*winy;
2375         }
2376         else {
2377                 disprect.xmin= disprect.ymin= 0;
2378                 disprect.xmax= winx;
2379                 disprect.ymax= winy;
2380         }
2381         
2382         if(scenode)
2383                 scene= scenode;
2384         
2385         re= RE_NewRender(scene->id.name);
2386         RE_InitState(re, &scene->r, winx, winy, &disprect);
2387         re->scene= scene;
2388         
2389         read_render_result(re);
2390 }
2391
2392 void RE_set_max_threads(int threads)
2393 {
2394         if(threads>0 && threads<=BLENDER_MAX_THREADS)
2395                 commandline_threads= threads;
2396         else
2397                 printf("Error, threads has to be in range 1-%d\n", BLENDER_MAX_THREADS);
2398 }