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