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