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