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