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