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