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