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