2.5: Render Api
[blender.git] / source / blender / render / intern / source / pipeline.c
1 /**  
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. 
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2006 Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <math.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "DNA_group_types.h"
35 #include "DNA_image_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_sequence_types.h"
40 #include "DNA_userdef_types.h"
41
42 #include "BKE_utildefines.h"
43 #include "BKE_global.h"
44 #include "BKE_image.h"
45 #include "BKE_main.h"
46 #include "BKE_node.h"
47 #include "BKE_object.h"
48 #include "BKE_report.h"
49 #include "BKE_scene.h"
50 #include "BKE_writeavi.h"       /* <------ should be replaced once with generic movie module */
51 #include "BKE_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 /* called for reading temp files, and for external engines */
872 static int read_render_result_from_file(char *filename, RenderResult *rr)
873 {
874         RenderLayer *rl;
875         RenderPass *rpass;
876         void *exrhandle= IMB_exr_get_handle();
877         int rectx, recty;
878
879         if(IMB_exr_begin_read(exrhandle, filename, &rectx, &recty)==0) {
880                 IMB_exr_close(exrhandle);
881                 return 0;
882         }
883         
884         if(rr == NULL || rectx!=rr->rectx || recty!=rr->recty) {
885                 printf("error in reading render result\n");
886                 IMB_exr_close(exrhandle);
887                 return 0;
888         }
889         else {
890                 for(rl= rr->layers.first; rl; rl= rl->next) {
891                         
892                         /* combined */
893                         if(rl->rectf) {
894                                 int a, xstride= 4;
895                                 for(a=0; a<xstride; a++)
896                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
897                                                                                 xstride, xstride*rectx, rl->rectf+a);
898                         }
899                         
900                         /* passes are allocated in sync */
901                         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
902                                 int a, xstride= rpass->channels;
903                                 for(a=0; a<xstride; a++)
904                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
905                                                                                 xstride, xstride*rectx, rpass->rect+a);
906                         }
907                         
908                 }
909                 IMB_exr_read_channels(exrhandle);
910                 renderresult_add_names(rr);
911         }
912         
913         IMB_exr_close(exrhandle);
914
915         return 1;
916 }
917
918 /* only for temp buffer files, makes exact copy of render result */
919 static void read_render_result(Render *re, int sample)
920 {
921         char str[FILE_MAX];
922
923         RE_FreeRenderResult(re->result);
924         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
925
926         render_unique_exr_name(re, str, sample);
927         printf("read exr tmp file: %s\n", str);
928
929         if(!read_render_result_from_file(str, re->result))
930                 printf("cannot read: %s\n", str);
931 }
932
933 /* *************************************************** */
934
935 Render *RE_GetRender(const char *name)
936 {
937         Render *re;
938         
939         /* search for existing renders */
940         for(re= RenderList.first; re; re= re->next) {
941                 if(strncmp(re->name, name, RE_MAXNAME)==0) {
942                         break;
943                 }
944         }
945         return re;
946 }
947
948 /* if you want to know exactly what has been done */
949 RenderResult *RE_GetResult(Render *re)
950 {
951         if(re)
952                 return re->result;
953         return NULL;
954 }
955
956 /* displist.c util.... */
957 Scene *RE_GetScene(Render *re)
958 {
959         if(re)
960                 return re->scene;
961         return NULL;
962 }
963
964 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
965 {
966         RenderLayer *rl= BLI_findlink(&rr->layers, re->r.actlay);
967         
968         if(rl) 
969                 return rl;
970         else 
971                 return rr->layers.first;
972 }
973
974
975 /* fill provided result struct with what's currently active or done */
976 void RE_GetResultImage(Render *re, RenderResult *rr)
977 {
978         memset(rr, 0, sizeof(RenderResult));
979
980         if(re && re->result) {
981                 RenderLayer *rl;
982                 
983                 rr->rectx= re->result->rectx;
984                 rr->recty= re->result->recty;
985                 
986                 rr->rectf= re->result->rectf;
987                 rr->rectz= re->result->rectz;
988                 rr->rect32= re->result->rect32;
989                 
990                 /* active layer */
991                 rl= render_get_active_layer(re, re->result);
992
993                 if(rl) {
994                         if(rr->rectf==NULL)
995                                 rr->rectf= rl->rectf;
996                         if(rr->rectz==NULL)
997                                 rr->rectz= RE_RenderLayerGetPass(rl, SCE_PASS_Z);       
998                 }
999         }
1000 }
1001
1002 /* caller is responsible for allocating rect in correct size! */
1003 void RE_ResultGet32(Render *re, unsigned int *rect)
1004 {
1005         RenderResult rres;
1006         
1007         RE_GetResultImage(re, &rres);
1008         if(rres.rect32) 
1009                 memcpy(rect, rres.rect32, sizeof(int)*rres.rectx*rres.recty);
1010         else if(rres.rectf) {
1011                 float *fp= rres.rectf;
1012                 int tot= rres.rectx*rres.recty;
1013                 char *cp= (char *)rect;
1014                 
1015                 for(;tot>0; tot--, cp+=4, fp+=4) {
1016                         cp[0] = FTOCHAR(fp[0]);
1017                         cp[1] = FTOCHAR(fp[1]);
1018                         cp[2] = FTOCHAR(fp[2]);
1019                         cp[3] = FTOCHAR(fp[3]);
1020                 }
1021         }
1022         else
1023                 /* else fill with black */
1024                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
1025 }
1026
1027
1028 RenderStats *RE_GetStats(Render *re)
1029 {
1030         return &re->i;
1031 }
1032
1033 Render *RE_NewRender(const char *name)
1034 {
1035         Render *re;
1036         
1037         /* only one render per name exists */
1038         re= RE_GetRender(name);
1039         if(re==NULL) {
1040                 
1041                 /* new render data struct */
1042                 re= MEM_callocN(sizeof(Render), "new render");
1043                 BLI_addtail(&RenderList, re);
1044                 strncpy(re->name, name, RE_MAXNAME);
1045         }
1046         
1047         /* prevent UI to draw old results */
1048         RE_FreeRenderResult(re->result);
1049         re->result= NULL;
1050         re->result_ok= 0;
1051         
1052         /* set default empty callbacks */
1053         re->display_init= result_nothing;
1054         re->display_clear= result_nothing;
1055         re->display_draw= result_rcti_nothing;
1056         re->timecursor= int_nothing;
1057         re->test_break= void_nothing;
1058         re->error= print_error;
1059         if(G.background)
1060                 re->stats_draw= stats_background;
1061         else
1062                 re->stats_draw= stats_nothing;
1063         /* clear callback handles */
1064         re->dih= re->dch= re->ddh= re->sdh= re->tch= re->tbh= re->erh= NULL;
1065         
1066         /* init some variables */
1067         re->ycor= 1.0f;
1068         
1069         return re;
1070 }
1071
1072 /* only call this while you know it will remove the link too */
1073 void RE_FreeRender(Render *re)
1074 {
1075         
1076         free_renderdata_tables(re);
1077         free_sample_tables(re);
1078         
1079         RE_FreeRenderResult(re->result);
1080         RE_FreeRenderResult(re->pushedresult);
1081         
1082         BLI_remlink(&RenderList, re);
1083         MEM_freeN(re);
1084 }
1085
1086 /* exit blender */
1087 void RE_FreeAllRender(void)
1088 {
1089         while(RenderList.first) {
1090                 RE_FreeRender(RenderList.first);
1091         }
1092 }
1093
1094 /* ********* initialize state ******** */
1095
1096
1097 /* what doesn't change during entire render sequence */
1098 /* disprect is optional, if NULL it assumes full window render */
1099 void RE_InitState(Render *re, Render *source, RenderData *rd, int winx, int winy, rcti *disprect)
1100 {
1101         re->ok= TRUE;   /* maybe flag */
1102         
1103         re->i.starttime= PIL_check_seconds_timer();
1104         re->r= *rd;             /* hardcopy */
1105         
1106         re->winx= winx;
1107         re->winy= winy;
1108         if(disprect) {
1109                 re->disprect= *disprect;
1110                 re->rectx= disprect->xmax-disprect->xmin;
1111                 re->recty= disprect->ymax-disprect->ymin;
1112         }
1113         else {
1114                 re->disprect.xmin= re->disprect.ymin= 0;
1115                 re->disprect.xmax= winx;
1116                 re->disprect.ymax= winy;
1117                 re->rectx= winx;
1118                 re->recty= winy;
1119         }
1120         
1121         if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
1122                                                                                   (re->rectx < 16 || re->recty < 16) )) {
1123                 re->error(re->erh, "Image too small");
1124                 re->ok= 0;
1125         }
1126         else {
1127 #ifdef WITH_OPENEXR
1128                 if(re->r.scemode & R_FULL_SAMPLE)
1129                         re->r.scemode |= R_EXR_TILE_FILE;       /* enable automatic */
1130 #else
1131                 /* can't do this without openexr support */
1132                 re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1133 #endif
1134                 
1135                 /* fullsample wants uniform osa levels */
1136                 if(source && (re->r.scemode & R_FULL_SAMPLE)) {
1137                         /* but, if source has no full sample we disable it */
1138                         if((source->r.scemode & R_FULL_SAMPLE)==0)
1139                                 re->r.scemode &= ~R_FULL_SAMPLE;
1140                         else
1141                                 re->r.osa= re->osa= source->osa;
1142                 }
1143                 else {
1144                         /* check state variables, osa? */
1145                         if(re->r.mode & (R_OSA)) {
1146                                 re->osa= re->r.osa;
1147                                 if(re->osa>16) re->osa= 16;
1148                         }
1149                         else re->osa= 0;
1150                 }
1151
1152                 /* always call, checks for gamma, gamma tables and jitter too */
1153                 make_sample_tables(re); 
1154                 
1155                 /* if preview render, we try to keep old result */
1156                 if(re->r.scemode & R_PREVIEWBUTS) {
1157                         if(re->result && re->result->rectx==re->rectx && re->result->recty==re->recty);
1158                         else {
1159                                 RE_FreeRenderResult(re->result);
1160                                 re->result= NULL;
1161                         }
1162                 }
1163                 else {
1164                         
1165                         /* make empty render result, so display callbacks can initialize */
1166                         RE_FreeRenderResult(re->result);
1167                         re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1168                         re->result->rectx= re->rectx;
1169                         re->result->recty= re->recty;
1170                 }
1171                 
1172                 /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1173                 re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1174                 
1175                 RE_init_threadcount(re);
1176         }
1177 }
1178
1179 /* part of external api, not called for regular render pipeline */
1180 void RE_SetDispRect (struct Render *re, rcti *disprect)
1181 {
1182         re->disprect= *disprect;
1183         re->rectx= disprect->xmax-disprect->xmin;
1184         re->recty= disprect->ymax-disprect->ymin;
1185         
1186         /* initialize render result */
1187         RE_FreeRenderResult(re->result);
1188         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1189 }
1190
1191 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
1192 {
1193         /* re->ok flag? */
1194         
1195         re->viewplane= *viewplane;
1196         re->clipsta= clipsta;
1197         re->clipend= clipend;
1198         re->r.mode &= ~R_ORTHO;
1199
1200         i_window(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1201         
1202 }
1203
1204 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1205 {
1206         /* re->ok flag? */
1207         
1208         re->viewplane= *viewplane;
1209         re->clipsta= clipsta;
1210         re->clipend= clipend;
1211         re->r.mode |= R_ORTHO;
1212
1213         i_ortho(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
1214 }
1215
1216 void RE_SetView(Render *re, float mat[][4])
1217 {
1218         /* re->ok flag? */
1219         Mat4CpyMat4(re->viewmat, mat);
1220         Mat4Invert(re->viewinv, re->viewmat);
1221 }
1222
1223 /* image and movie output has to move to either imbuf or kernel */
1224 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1225 {
1226         re->display_init= f;
1227         re->dih= handle;
1228 }
1229 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1230 {
1231         re->display_clear= f;
1232         re->dch= handle;
1233 }
1234 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
1235 {
1236         re->display_draw= f;
1237         re->ddh= handle;
1238 }
1239 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
1240 {
1241         re->stats_draw= f;
1242         re->sdh= handle;
1243 }
1244 void RE_timecursor_cb(Render *re, void *handle, void (*f)(void *handle, int))
1245 {
1246         re->timecursor= f;
1247         re->tch= handle;
1248 }
1249
1250 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
1251 {
1252         re->test_break= f;
1253         re->tbh= handle;
1254 }
1255 void RE_error_cb(Render *re, void *handle, void (*f)(void *handle, char *str))
1256 {
1257         re->error= f;
1258         re->erh= handle;
1259 }
1260
1261
1262 /* ********* add object data (later) ******** */
1263
1264 /* object is considered fully prepared on correct time etc */
1265 /* includes lights */
1266 void RE_AddObject(Render *re, Object *ob)
1267 {
1268         
1269 }
1270
1271 /* *************************************** */
1272
1273 static int render_display_draw_enabled(Render *re)
1274 {
1275         /* don't show preprocess for previewrender sss */
1276         if(re->sss_points)
1277                 return !(re->r.scemode & R_PREVIEWBUTS);
1278         else
1279                 return 1;
1280 }
1281
1282 /* allocate osa new results for samples */
1283 static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
1284 {
1285         int a;
1286         
1287         if(re->osa==0)
1288                 return new_render_result(re, partrct, crop, RR_USEMEM);
1289         
1290         for(a=0; a<re->osa; a++) {
1291                 RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
1292                 BLI_addtail(lb, rr);
1293                 rr->sample_nr= a;
1294         }
1295         
1296         return lb->first;
1297 }
1298
1299
1300 /* the main thread call, renders an entire part */
1301 static void *do_part_thread(void *pa_v)
1302 {
1303         RenderPart *pa= pa_v;
1304         
1305         /* need to return nicely all parts on esc */
1306         if(R.test_break(R.tbh)==0) {
1307                 
1308                 if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
1309                         pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
1310                 else
1311                         pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1312
1313                 if(R.sss_points)
1314                         zbufshade_sss_tile(pa);
1315                 else if(R.osa)
1316                         zbufshadeDA_tile(pa);
1317                 else
1318                         zbufshade_tile(pa);
1319                 
1320                 /* merge too on break! */
1321                 if(R.result->exrhandle) {
1322                         RenderResult *rr, *rrpart;
1323                         
1324                         for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
1325                                 save_render_result_tile(rr, rrpart);
1326                         
1327                 }
1328                 else if(render_display_draw_enabled(&R)) {
1329                         /* on break, don't merge in result for preview renders, looks nicer */
1330                         if(R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS));
1331                         else merge_render_result(R.result, pa->result);
1332                 }
1333         }
1334         
1335         pa->ready= 1;
1336         
1337         return NULL;
1338 }
1339
1340 /* returns with render result filled, not threaded, used for preview now only */
1341 static void render_tile_processor(Render *re, int firsttile)
1342 {
1343         RenderPart *pa;
1344         
1345         if(re->test_break(re->tbh))
1346                 return;
1347
1348         /* hrmf... exception, this is used for preview render, re-entrant, so render result has to be re-used */
1349         if(re->result==NULL || re->result->layers.first==NULL) {
1350                 if(re->result) RE_FreeRenderResult(re->result);
1351                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1352         }
1353         
1354         re->stats_draw(re->sdh, &re->i);
1355  
1356         if(re->result==NULL)
1357                 return;
1358         
1359         initparts(re);
1360         
1361         /* assuming no new data gets added to dbase... */
1362         R= *re;
1363         
1364         for(pa= re->parts.first; pa; pa= pa->next) {
1365                 if(firsttile) {
1366                         re->i.partsdone++;      /* was reset in initparts */
1367                         firsttile--;
1368                 }
1369                 else {
1370                         do_part_thread(pa);
1371                         
1372                         if(pa->result) {
1373                                 if(!re->test_break(re->tbh)) {
1374                                         if(render_display_draw_enabled(re))
1375                                                 re->display_draw(re->ddh, pa->result, NULL);
1376                                         
1377                                         re->i.partsdone++;
1378                                         re->stats_draw(re->sdh, &re->i);
1379                                 }
1380                                 RE_FreeRenderResult(pa->result);
1381                                 pa->result= NULL;
1382                         }               
1383                         if(re->test_break(re->tbh))
1384                                 break;
1385                 }
1386         }
1387         
1388         freeparts(re);
1389 }
1390
1391 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1392 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1393 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1394 float panorama_pixel_rot(Render *re)
1395 {
1396         float psize, phi, xfac;
1397         
1398         /* size of 1 pixel mapped to viewplane coords */
1399         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
1400         /* angle of a pixel */
1401         phi= atan(psize/re->clipsta);
1402         
1403         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1404         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1405         xfac= atan(0.5f*xfac/re->clipsta); 
1406         /* and how much the same viewplane angle is wrapped */
1407         psize= 0.5f*phi*((float)re->partx);
1408         
1409         /* the ratio applied to final per-pixel angle */
1410         phi*= xfac/psize;
1411         
1412         return phi;
1413 }
1414
1415 /* call when all parts stopped rendering, to find the next Y slice */
1416 /* if slice found, it rotates the dbase */
1417 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1418 {
1419         RenderPart *pa, *best= NULL;
1420         
1421         *minx= re->winx;
1422         
1423         /* most left part of the non-rendering parts */
1424         for(pa= re->parts.first; pa; pa= pa->next) {
1425                 if(pa->ready==0 && pa->nr==0) {
1426                         if(pa->disprect.xmin < *minx) {
1427                                 best= pa;
1428                                 *minx= pa->disprect.xmin;
1429                         }
1430                 }
1431         }
1432                         
1433         if(best) {
1434                 float phi= panorama_pixel_rot(re);
1435
1436                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1437                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
1438                 
1439                 /* shift viewplane */
1440                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1441                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1442                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1443                 Mat4CpyMat4(R.winmat, re->winmat);
1444                 
1445                 /* rotate database according to part coordinates */
1446                 project_renderdata(re, projectverto, 1, -R.panodxp*phi, 1);
1447                 R.panosi= sin(R.panodxp*phi);
1448                 R.panoco= cos(R.panodxp*phi);
1449         }
1450         return best;
1451 }
1452
1453 static RenderPart *find_next_part(Render *re, int minx)
1454 {
1455         RenderPart *pa, *best= NULL;
1456         int centx=re->winx/2, centy=re->winy/2, tot=1;
1457         int mindist, distx, disty;
1458         
1459         /* find center of rendered parts, image center counts for 1 too */
1460         for(pa= re->parts.first; pa; pa= pa->next) {
1461                 if(pa->ready) {
1462                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1463                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1464                         tot++;
1465                 }
1466         }
1467         centx/=tot;
1468         centy/=tot;
1469         
1470         /* closest of the non-rendering parts */
1471         mindist= re->winx*re->winy;
1472         for(pa= re->parts.first; pa; pa= pa->next) {
1473                 if(pa->ready==0 && pa->nr==0) {
1474                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1475                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1476                         distx= (int)sqrt(distx*distx + disty*disty);
1477                         if(distx<mindist) {
1478                                 if(re->r.mode & R_PANORAMA) {
1479                                         if(pa->disprect.xmin==minx) {
1480                                                 best= pa;
1481                                                 mindist= distx;
1482                                         }
1483                                 }
1484                                 else {
1485                                         best= pa;
1486                                         mindist= distx;
1487                                 }
1488                         }
1489                 }
1490         }
1491         return best;
1492 }
1493
1494 static void print_part_stats(Render *re, RenderPart *pa)
1495 {
1496         char str[64];
1497         
1498         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1499         re->i.infostr= str;
1500         re->stats_draw(re->sdh, &re->i);
1501         re->i.infostr= NULL;
1502 }
1503
1504 /* make osa new results for samples */
1505 static RenderResult *new_full_sample_buffers_exr(Render *re)
1506 {
1507         int a;
1508         
1509         for(a=0; a<re->osa; a++) {
1510                 RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
1511                 BLI_addtail(&re->fullresult, rr);
1512                 rr->sample_nr= a;
1513         }
1514         
1515         return re->fullresult.first;
1516 }
1517
1518 static void threaded_tile_processor(Render *re)
1519 {
1520         ListBase threads;
1521         RenderPart *pa, *nextpa;
1522         rctf viewplane= re->viewplane;
1523         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1524         
1525         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
1526         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
1527                 RE_FreeRenderResult(re->result);
1528         
1529                 if(re->sss_points)
1530                         re->result= new_render_result(re, &re->disprect, 0, 0);
1531                 else if(re->r.scemode & R_FULL_SAMPLE)
1532                         re->result= new_full_sample_buffers_exr(re);
1533                 else
1534                         re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
1535         }
1536         
1537         if(re->result==NULL)
1538                 return;
1539         
1540         /* warning; no return here without closing exr file */
1541         
1542         initparts(re);
1543         
1544         if(re->result->exrhandle) {
1545                 RenderResult *rr;
1546                 char str[FILE_MAX];
1547                 
1548                 for(rr= re->result; rr; rr= rr->next) {
1549                         render_unique_exr_name(re, str, rr->sample_nr);
1550                 
1551                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1552                         IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1553                 }
1554         }
1555         
1556         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1557         
1558         /* assuming no new data gets added to dbase... */
1559         R= *re;
1560         
1561         /* set threadsafe break */
1562         R.test_break= thread_break;
1563         
1564         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1565         if(re->r.mode & R_PANORAMA)
1566                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1567         else
1568                 nextpa= find_next_part(re, 0);
1569         
1570         while(rendering) {
1571                 
1572                 if(re->test_break(re->tbh))
1573                         PIL_sleep_ms(50);
1574                 else if(nextpa && BLI_available_threads(&threads)) {
1575                         drawtimer= 0;
1576                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1577                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1578                         BLI_insert_thread(&threads, nextpa);
1579
1580                         nextpa= find_next_part(re, minx);
1581                 }
1582                 else if(re->r.mode & R_PANORAMA) {
1583                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1584                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1585                         else {
1586                                 PIL_sleep_ms(50);
1587                                 drawtimer++;
1588                         }
1589                 }
1590                 else {
1591                         PIL_sleep_ms(50);
1592                         drawtimer++;
1593                 }
1594                 
1595                 /* check for ready ones to display, and if we need to continue */
1596                 rendering= 0;
1597                 hasdrawn= 0;
1598                 for(pa= re->parts.first; pa; pa= pa->next) {
1599                         if(pa->ready) {
1600                                 
1601                                 BLI_remove_thread(&threads, pa);
1602                                 
1603                                 if(pa->result) {
1604                                         if(render_display_draw_enabled(re))
1605                                                 re->display_draw(re->ddh, pa->result, NULL);
1606                                         print_part_stats(re, pa);
1607                                         
1608                                         free_render_result(&pa->fullresult, pa->result);
1609                                         pa->result= NULL;
1610                                         re->i.partsdone++;
1611                                         hasdrawn= 1;
1612                                 }
1613                         }
1614                         else {
1615                                 rendering= 1;
1616                                 if(pa->nr && pa->result && drawtimer>20) {
1617                                         if(render_display_draw_enabled(re))
1618                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
1619                                         hasdrawn= 1;
1620                                 }
1621                         }
1622                 }
1623                 if(hasdrawn)
1624                         drawtimer= 0;
1625
1626                 /* on break, wait for all slots to get freed */
1627                 if( (g_break=re->test_break(re->tbh)) && BLI_available_threads(&threads)==re->r.threads)
1628                         rendering= 0;
1629                 
1630         }
1631         
1632         if(re->result->exrhandle) {
1633                 RenderResult *rr;
1634
1635                 save_empty_result_tiles(re);
1636                 
1637                 for(rr= re->result; rr; rr= rr->next) {
1638                         IMB_exr_close(rr->exrhandle);
1639                         rr->exrhandle= NULL;
1640                 }
1641                 
1642                 free_render_result(&re->fullresult, re->result);
1643                 re->result= NULL;
1644                 
1645                 read_render_result(re, 0);
1646         }
1647         
1648         /* unset threadsafety */
1649         g_break= 0;
1650         
1651         BLI_end_threads(&threads);
1652         freeparts(re);
1653         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1654 }
1655
1656 /* currently only called by preview renders and envmap */
1657 void RE_TileProcessor(Render *re, int firsttile, int threaded)
1658 {
1659         /* the partsdone variable has to be reset to firsttile, to survive esc before it was set to zero */
1660         
1661         re->i.partsdone= firsttile;
1662
1663         if(!re->sss_points)
1664                 re->i.starttime= PIL_check_seconds_timer();
1665
1666         if(threaded)
1667                 threaded_tile_processor(re);
1668         else
1669                 render_tile_processor(re, firsttile);
1670                 
1671         if(!re->sss_points)
1672                 re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1673         re->stats_draw(re->sdh, &re->i);
1674 }
1675
1676
1677 /* ************  This part uses API, for rendering Blender scenes ********** */
1678
1679 static void external_render_3d(Render *re, RenderEngineType *type);
1680
1681 static void do_render_3d(Render *re)
1682 {
1683         RenderEngineType *type;
1684
1685         /* try external */
1686         for(type=R_engines.first; type; type=type->next)
1687                 if(strcmp(type->idname, re->r.engine) == 0)
1688                         break;
1689
1690         if(type && type->render) {
1691                 external_render_3d(re, type);
1692                 return;
1693         }
1694
1695         /* internal */
1696         
1697 //      re->cfra= cfra; /* <- unused! */
1698         
1699         /* make render verts/faces/halos/lamps */
1700         if(render_scene_needs_vector(re))
1701                 RE_Database_FromScene_Vectors(re, re->scene);
1702         else
1703            RE_Database_FromScene(re, re->scene, 1);
1704         
1705         threaded_tile_processor(re);
1706         
1707         /* do left-over 3d post effects (flares) */
1708         if(re->flag & R_HALO)
1709                 if(!re->test_break(re->tbh))
1710                         add_halo_flare(re);
1711         
1712         /* free all render verts etc */
1713         RE_Database_Free(re);
1714 }
1715
1716 /* called by blur loop, accumulate RGBA key alpha */
1717 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
1718 {
1719         float mfac= 1.0f - blurfac;
1720         int a, b, stride= 4*rr->rectx;
1721         int len= stride*sizeof(float);
1722         
1723         for(a=0; a<rr->recty; a++) {
1724                 if(blurfac==1.0f) {
1725                         memcpy(rectf, rectf1, len);
1726                 }
1727                 else {
1728                         float *rf= rectf, *rf1= rectf1;
1729                         
1730                         for( b= rr->rectx; b>0; b--, rf+=4, rf1+=4) {
1731                                 if(rf1[3]<0.01f)
1732                                         rf[3]= mfac*rf[3];
1733                                 else if(rf[3]<0.01f) {
1734                                         rf[0]= rf1[0];
1735                                         rf[1]= rf1[1];
1736                                         rf[2]= rf1[2];
1737                                         rf[3]= blurfac*rf1[3];
1738                                 }
1739                                 else {
1740                                         rf[0]= mfac*rf[0] + blurfac*rf1[0];
1741                                         rf[1]= mfac*rf[1] + blurfac*rf1[1];
1742                                         rf[2]= mfac*rf[2] + blurfac*rf1[2];
1743                                         rf[3]= mfac*rf[3] + blurfac*rf1[3];
1744                                 }                               
1745                         }
1746                 }
1747                 rectf+= stride;
1748                 rectf1+= stride;
1749         }
1750 }
1751
1752 /* called by blur loop, accumulate renderlayers */
1753 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1754 {
1755         float mfac= 1.0f - blurfac;
1756         int a, b, stride= channels*rr->rectx;
1757         int len= stride*sizeof(float);
1758         
1759         for(a=0; a<rr->recty; a++) {
1760                 if(blurfac==1.0f) {
1761                         memcpy(rectf, rectf1, len);
1762                 }
1763                 else {
1764                         float *rf= rectf, *rf1= rectf1;
1765                         
1766                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1767                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1768                         }
1769                 }
1770                 rectf+= stride;
1771                 rectf1+= stride;
1772         }
1773 }
1774
1775
1776 /* called by blur loop, accumulate renderlayers */
1777 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1778 {
1779         RenderLayer *rl, *rl1;
1780         RenderPass *rpass, *rpass1;
1781         
1782         rl1= brr->layers.first;
1783         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1784                 
1785                 /* combined */
1786                 if(rl->rectf && rl1->rectf) {
1787                         if(key_alpha)
1788                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1789                         else
1790                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1791                 }
1792                 
1793                 /* passes are allocated in sync */
1794                 rpass1= rl1->passes.first;
1795                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1796                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1797                 }
1798         }
1799 }
1800
1801 /* main blur loop, can be called by fields too */
1802 static void do_render_blur_3d(Render *re)
1803 {
1804         RenderResult *rres;
1805         float blurfac;
1806         int blur= re->r.osa;
1807         
1808         /* create accumulation render result */
1809         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1810         
1811         /* do the blur steps */
1812         while(blur--) {
1813                 set_mblur_offs( re->r.blurfac*((float)(re->r.osa-blur))/(float)re->r.osa );
1814                 
1815                 re->i.curblur= re->r.osa-blur;  /* stats */
1816                 
1817                 do_render_3d(re);
1818                 
1819                 blurfac= 1.0f/(float)(re->r.osa-blur);
1820                 
1821                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1822                 if(re->test_break(re->tbh)) break;
1823         }
1824         
1825         /* swap results */
1826         RE_FreeRenderResult(re->result);
1827         re->result= rres;
1828         
1829         set_mblur_offs(0.0f);
1830         re->i.curblur= 0;       /* stats */
1831         
1832         /* weak... the display callback wants an active renderlayer pointer... */
1833         re->result->renlay= render_get_active_layer(re, re->result);
1834         re->display_draw(re->ddh, re->result, NULL);    
1835 }
1836
1837
1838 /* function assumes rectf1 and rectf2 to be half size of rectf */
1839 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1840 {
1841         int a, stride= channels*rr->rectx;
1842         int len= stride*sizeof(float);
1843         
1844         for(a=0; a<rr->recty; a+=2) {
1845                 memcpy(rectf, rectf1, len);
1846                 rectf+= stride;
1847                 rectf1+= stride;
1848                 memcpy(rectf, rectf2, len);
1849                 rectf+= stride;
1850                 rectf2+= stride;
1851         }
1852 }
1853
1854 /* merge render results of 2 fields */
1855 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1856 {
1857         RenderLayer *rl, *rl1, *rl2;
1858         RenderPass *rpass, *rpass1, *rpass2;
1859         
1860         rl1= rr1->layers.first;
1861         rl2= rr2->layers.first;
1862         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1863                 
1864                 /* combined */
1865                 if(rl->rectf && rl1->rectf && rl2->rectf)
1866                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1867                 
1868                 /* passes are allocated in sync */
1869                 rpass1= rl1->passes.first;
1870                 rpass2= rl2->passes.first;
1871                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1872                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1873                 }
1874         }
1875 }
1876
1877
1878 /* interleaves 2 frames */
1879 static void do_render_fields_3d(Render *re)
1880 {
1881         RenderResult *rr1, *rr2= NULL;
1882         
1883         /* no render result was created, we can safely halve render y */
1884         re->winy /= 2;
1885         re->recty /= 2;
1886         re->disprect.ymin /= 2;
1887         re->disprect.ymax /= 2;
1888         
1889         re->i.curfield= 1;      /* stats */
1890         
1891         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1892         RE_SetCamera(re, re->scene->camera);
1893         if(re->r.mode & R_MBLUR)
1894                 do_render_blur_3d(re);
1895         else
1896                 do_render_3d(re);
1897         rr1= re->result;
1898         re->result= NULL;
1899         
1900         /* second field */
1901         if(!re->test_break(re->tbh)) {
1902                 
1903                 re->i.curfield= 2;      /* stats */
1904                 
1905                 re->flag |= R_SEC_FIELD;
1906                 if((re->r.mode & R_FIELDSTILL)==0) 
1907                         set_field_offs(0.5f);
1908                 RE_SetCamera(re, re->scene->camera);
1909                 if(re->r.mode & R_MBLUR)
1910                         do_render_blur_3d(re);
1911                 else
1912                         do_render_3d(re);
1913                 re->flag &= ~R_SEC_FIELD;
1914                 set_field_offs(0.0f);
1915                 
1916                 rr2= re->result;
1917         }
1918         
1919         /* allocate original height new buffers */
1920         re->winy *= 2;
1921         re->recty *= 2;
1922         re->disprect.ymin *= 2;
1923         re->disprect.ymax *= 2;
1924         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1925         
1926         if(rr2) {
1927                 if(re->r.mode & R_ODDFIELD)
1928                         merge_renderresult_fields(re->result, rr2, rr1);
1929                 else
1930                         merge_renderresult_fields(re->result, rr1, rr2);
1931                 
1932                 RE_FreeRenderResult(rr2);
1933         }
1934         RE_FreeRenderResult(rr1);
1935         
1936         re->i.curfield= 0;      /* stats */
1937         
1938         /* weak... the display callback wants an active renderlayer pointer... */
1939         re->result->renlay= render_get_active_layer(re, re->result);
1940         re->display_draw(re->ddh, re->result, NULL);
1941 }
1942
1943 static void load_backbuffer(Render *re)
1944 {
1945         if(re->r.alphamode == R_ADDSKY) {
1946                 ImBuf *ibuf;
1947                 char name[256];
1948                 
1949                 strcpy(name, re->r.backbuf);
1950                 BLI_convertstringcode(name, G.sce);
1951                 BLI_convertstringframe(name, re->r.cfra);
1952                 
1953                 if(re->backbuf) {
1954                         re->backbuf->id.us--;
1955                         if(re->backbuf->id.us<1)
1956                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
1957                 }
1958                 
1959                 re->backbuf= BKE_add_image_file(name, re->r.cfra);
1960                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
1961                 if(ibuf==NULL) {
1962                         // error() doesnt work with render window open
1963                         //error("No backbuf there!");
1964                         printf("Error: No backbuf %s\n", name);
1965                 }
1966                 else {
1967                         if (re->r.mode & R_FIELDS)
1968                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
1969                 }
1970         }
1971 }
1972
1973 /* main render routine, no compositing */
1974 static void do_render_fields_blur_3d(Render *re)
1975 {
1976         /* also check for camera here */
1977         if(re->scene->camera==NULL) {
1978                 printf("ERROR: Cannot render, no camera\n");
1979                 G.afbreek= 1;
1980                 return;
1981         }
1982         
1983         /* backbuffer initialize */
1984         if(re->r.bufflag & 1)
1985                 load_backbuffer(re);
1986
1987         /* now use renderdata and camera to set viewplane */
1988         RE_SetCamera(re, re->scene->camera);
1989         
1990         if(re->r.mode & R_FIELDS)
1991                 do_render_fields_3d(re);
1992         else if(re->r.mode & R_MBLUR)
1993                 do_render_blur_3d(re);
1994         else
1995                 do_render_3d(re);
1996         
1997         /* when border render, check if we have to insert it in black */
1998         if(re->result) {
1999                 if(re->r.mode & R_BORDER) {
2000                         if((re->r.mode & R_CROP)==0) {
2001                                 RenderResult *rres;
2002                                 
2003                                 /* sub-rect for merge call later on */
2004                                 re->result->tilerect= re->disprect;
2005                                 
2006                                 /* this copying sequence could become function? */
2007                                 /* weak is: it chances disprect from border */
2008                                 re->disprect.xmin= re->disprect.ymin= 0;
2009                                 re->disprect.xmax= re->winx;
2010                                 re->disprect.ymax= re->winy;
2011                                 re->rectx= re->winx;
2012                                 re->recty= re->winy;
2013                                 
2014                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2015                                 
2016                                 merge_render_result(rres, re->result);
2017                                 RE_FreeRenderResult(re->result);
2018                                 re->result= rres;
2019                                 
2020                                 /* weak... the display callback wants an active renderlayer pointer... */
2021                                 re->result->renlay= render_get_active_layer(re, re->result);
2022                                 
2023                                 re->display_init(re->dih, re->result);
2024                                 re->display_draw(re->ddh, re->result, NULL);
2025                         }
2026                 }
2027         }
2028 }
2029
2030
2031 /* within context of current Render *re, render another scene.
2032    it uses current render image size and disprect, but doesn't execute composite
2033 */
2034 static void render_scene(Render *re, Scene *sce, int cfra)
2035 {
2036         Render *resc= RE_NewRender(sce->id.name);
2037         int winx= re->winx, winy= re->winy;
2038         
2039         sce->r.cfra= cfra;
2040                 
2041         /* exception: scene uses own size (unfinished code) */
2042         if(0) {
2043                 winx= (sce->r.size*sce->r.xsch)/100;
2044                 winy= (sce->r.size*sce->r.ysch)/100;
2045         }
2046         
2047         /* initial setup */
2048         RE_InitState(resc, re, &sce->r, winx, winy, &re->disprect);
2049         
2050         /* still unsure entity this... */
2051         resc->scene= sce;
2052         
2053         /* ensure scene has depsgraph, base flags etc OK */
2054         set_scene_bg(sce);
2055
2056         /* copy callbacks */
2057         resc->display_draw= re->display_draw;
2058         resc->ddh= re->ddh;
2059         resc->test_break= re->test_break;
2060         resc->tbh= re->tbh;
2061         resc->stats_draw= re->stats_draw;
2062         resc->sdh= re->sdh;
2063         
2064         do_render_fields_blur_3d(resc);
2065 }
2066
2067 static void tag_scenes_for_render(Render *re)
2068 {
2069         bNode *node;
2070         Scene *sce;
2071         
2072         for(sce= G.main->scene.first; sce; sce= sce->id.next)
2073                 sce->id.flag &= ~LIB_DOIT;
2074         
2075         re->scene->id.flag |= LIB_DOIT;
2076         
2077         if(re->scene->nodetree==NULL) return;
2078         
2079         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
2080         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2081                 if(node->type==CMP_NODE_R_LAYERS) {
2082                         if(node->id) {
2083                                 if(node->id != (ID *)re->scene)
2084                                         node->id->flag |= LIB_DOIT;
2085                         }
2086                 }
2087         }
2088         
2089 }
2090
2091 static void ntree_render_scenes(Render *re)
2092 {
2093         bNode *node;
2094         int cfra= re->scene->r.cfra;
2095         
2096         if(re->scene->nodetree==NULL) return;
2097         
2098         tag_scenes_for_render(re);
2099         
2100         /* now foreach render-result node tagged we do a full render */
2101         /* results are stored in a way compisitor will find it */
2102         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2103                 if(node->type==CMP_NODE_R_LAYERS) {
2104                         if(node->id && node->id != (ID *)re->scene) {
2105                                 if(node->id->flag & LIB_DOIT) {
2106                                         render_scene(re, (Scene *)node->id, cfra);
2107                                         node->id->flag &= ~LIB_DOIT;
2108                                 }
2109                         }
2110                 }
2111         }
2112 }
2113
2114 /* helper call to detect if theres a composite with render-result node */
2115 static int composite_needs_render(Scene *sce)
2116 {
2117         bNodeTree *ntree= sce->nodetree;
2118         bNode *node;
2119         
2120         if(ntree==NULL) return 1;
2121         if(sce->use_nodes==0) return 1;
2122         if((sce->r.scemode & R_DOCOMP)==0) return 1;
2123                 
2124         for(node= ntree->nodes.first; node; node= node->next) {
2125                 if(node->type==CMP_NODE_R_LAYERS)
2126                         if(node->id==NULL || node->id==&sce->id)
2127                                 return 1;
2128         }
2129         return 0;
2130 }
2131
2132 /* bad call... need to think over proper method still */
2133 static void render_composit_stats(void *unused, char *str)
2134 {
2135         R.i.infostr= str;
2136         R.stats_draw(R.sdh, &R.i);
2137         R.i.infostr= NULL;
2138 }
2139
2140
2141 /* reads all buffers, calls optional composite, merges in first result->rectf */
2142 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
2143 {
2144         float *rectf, filt[3][3];
2145         int sample;
2146         
2147         /* filtmask needs it */
2148         R= *re;
2149         
2150         /* we accumulate in here */
2151         rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
2152         
2153         for(sample=0; sample<re->r.osa; sample++) {
2154                 RenderResult rres;
2155                 int x, y, mask;
2156                 
2157                 /* set all involved renders on the samplebuffers (first was done by render itself) */
2158                 /* also function below assumes this */
2159                 if(sample) {
2160                         Render *re1;
2161                         
2162                         tag_scenes_for_render(re);
2163                         for(re1= RenderList.first; re1; re1= re1->next) {
2164                                 if(re1->scene->id.flag & LIB_DOIT)
2165                                         if(re1->r.scemode & R_FULL_SAMPLE)
2166                                                 read_render_result(re1, sample);
2167                         }
2168                 }
2169
2170                 /* composite */
2171                 if(ntree) {
2172                         ntreeCompositTagRender(re->scene);
2173                         ntreeCompositTagAnimated(ntree);
2174                         
2175                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2176                 }
2177                 
2178                 /* ensure we get either composited result or the active layer */
2179                 RE_GetResultImage(re, &rres);
2180                 
2181                 /* accumulate with filter, and clip */
2182                 mask= (1<<sample);
2183                 mask_array(mask, filt);
2184
2185                 for(y=0; y<re->recty; y++) {
2186                         float *rf= rectf + 4*y*re->rectx;
2187                         float *col= rres.rectf + 4*y*re->rectx;
2188                                 
2189                         for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
2190                                 if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
2191                                 if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
2192                                 if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
2193                                 
2194                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
2195                         }
2196                 }
2197                 
2198                 /* show stuff */
2199                 if(sample!=re->osa-1) {
2200                         /* weak... the display callback wants an active renderlayer pointer... */
2201                         re->result->renlay= render_get_active_layer(re, re->result);
2202                         re->display_draw(re->ddh, re->result, NULL);
2203                 }
2204                 
2205                 if(re->test_break(re->tbh))
2206                         break;
2207         }
2208         
2209         if(re->result->rectf) 
2210                 MEM_freeN(re->result->rectf);
2211         re->result->rectf= rectf;
2212 }
2213
2214 void RE_MergeFullSample(Render *re, Scene *sce, bNodeTree *ntree)
2215 {
2216         Scene *scene;
2217         bNode *node;
2218         
2219         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
2220         
2221         /* tag scenes unread */
2222         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2223                 scene->id.flag |= LIB_DOIT;
2224         
2225         for(node= ntree->nodes.first; node; node= node->next) {
2226                 if(node->type==CMP_NODE_R_LAYERS) {
2227                         Scene *nodescene= (Scene *)node->id;
2228                         
2229                         if(nodescene==NULL) nodescene= sce;
2230                         if(nodescene->id.flag & LIB_DOIT) {
2231                                 nodescene->r.mode |= R_OSA;     /* render struct needs tables */
2232                                 RE_ReadRenderResult(sce, nodescene);
2233                                 nodescene->id.flag &= ~LIB_DOIT;
2234                         }
2235                 }
2236         }
2237         
2238         /* own render result should be read/allocated */
2239         if(re->scene->id.flag & LIB_DOIT)
2240                 RE_ReadRenderResult(re->scene, re->scene);
2241         
2242         /* and now we can draw (result is there) */
2243         re->display_init(re->dih, re->result);
2244         re->display_clear(re->dch, re->result);
2245         
2246         do_merge_fullsample(re, ntree);
2247 }
2248
2249 /* returns fully composited render-result on given time step (in RenderData) */
2250 static void do_render_composite_fields_blur_3d(Render *re)
2251 {
2252         bNodeTree *ntree= re->scene->nodetree;
2253         
2254         /* INIT seeding, compositor can use random texture */
2255         BLI_srandom(re->r.cfra);
2256         
2257         if(composite_needs_render(re->scene)) {
2258                 /* save memory... free all cached images */
2259                 ntreeFreeCache(ntree);
2260                 
2261                 do_render_fields_blur_3d(re);
2262         }
2263         
2264         /* swap render result */
2265         if(re->r.scemode & R_SINGLE_LAYER)
2266                 pop_render_result(re);
2267         
2268         if(!re->test_break(re->tbh)) {
2269                 
2270                 if(ntree) {
2271                         ntreeCompositTagRender(re->scene);
2272                         ntreeCompositTagAnimated(ntree);
2273                 }
2274                 
2275                 if(1 || !(re->r.scemode & R_COMP_RERENDER)) {
2276                         if(ntree && re->r.scemode & R_DOCOMP) {
2277                                 /* checks if there are render-result nodes that need scene */
2278                                 if((re->r.scemode & R_SINGLE_LAYER)==0)
2279                                         ntree_render_scenes(re);
2280                                 
2281                                 if(!re->test_break(re->tbh)) {
2282                                         ntree->stats_draw= render_composit_stats;
2283                                         ntree->test_break= re->test_break;
2284                                         ntree->sdh= re->sdh;
2285                                         ntree->tbh= re->tbh;
2286                                         /* in case it was never initialized */
2287                                         R.stats_draw= re->stats_draw;
2288                                         
2289                                         if(re->r.scemode & R_FULL_SAMPLE) 
2290                                                 do_merge_fullsample(re, ntree);
2291                                         else
2292                                                 ntreeCompositExecTree(ntree, &re->r, G.background==0);
2293                                         
2294                                         ntree->stats_draw= NULL;
2295                                         ntree->test_break= NULL;
2296                                         ntree->tbh= ntree->sdh= NULL;
2297                                 }
2298                         }
2299                         else if(re->r.scemode & R_FULL_SAMPLE)
2300                                 do_merge_fullsample(re, NULL);
2301                 }
2302         }
2303
2304         /* weak... the display callback wants an active renderlayer pointer... */
2305         re->result->renlay= render_get_active_layer(re, re->result);
2306         re->display_draw(re->ddh, re->result, NULL);
2307 }
2308
2309 static void renderresult_stampinfo(Scene *scene)
2310 {
2311         RenderResult rres;
2312         /* this is the basic trick to get the displayed float or char rect from render result */
2313         RE_GetResultImage(RE_GetRender(scene->id.name), &rres);
2314         BKE_stamp_buf(scene, (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
2315 }
2316
2317 static void do_render_seq(Render * re)
2318 {
2319         static int recurs_depth = 0;
2320         struct ImBuf *ibuf;
2321         RenderResult *rr = re->result;
2322         int cfra = re->r.cfra;
2323
2324         recurs_depth++;
2325
2326         ibuf= give_ibuf_seq(re->scene, rr->rectx, rr->recty, cfra, 0, 100.0);
2327
2328         recurs_depth--;
2329         
2330         if(ibuf) {
2331                 if(ibuf->rect_float) {
2332                         if (!rr->rectf)
2333                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
2334                         
2335                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2336                         
2337                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
2338                            can hang around when sequence render has rendered a 32 bits one before */
2339                         if(rr->rect32) {
2340                                 MEM_freeN(rr->rect32);
2341                                 rr->rect32= NULL;
2342                         }
2343                 }
2344                 else if(ibuf->rect) {
2345                         if (!rr->rect32)
2346                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2347
2348                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
2349
2350                         /* if (ibuf->zbuf) { */
2351                         /*      if (R.rectz) freeN(R.rectz); */
2352                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
2353                         /* } */
2354                 }
2355                 
2356                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
2357                         Editing * ed = re->scene->ed;
2358                         if (ed) {
2359                                 free_imbuf_seq(&ed->seqbase, TRUE);
2360                         }
2361                 }
2362         }
2363         else {
2364                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
2365                 if (rr->rectf)
2366                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
2367                 else if (rr->rect32)
2368                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
2369                 else
2370                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2371         }
2372 }
2373
2374 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2375
2376 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2377 static void do_render_all_options(Render *re)
2378 {
2379         re->i.starttime= PIL_check_seconds_timer();
2380
2381         /* ensure no images are in memory from previous animated sequences */
2382         BKE_image_all_free_anim_ibufs(re->r.cfra);
2383         
2384         if((re->r.scemode & R_DOSEQ) && re->scene->ed && re->scene->ed->seqbase.first) {
2385                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2386                 if(!re->test_break(re->tbh)) 
2387                         do_render_seq(re);
2388                 
2389                 re->stats_draw(re->sdh, &re->i);
2390                 re->display_draw(re->ddh, re->result, NULL);
2391                 
2392         }
2393         else {
2394                 do_render_composite_fields_blur_3d(re);
2395         }
2396         
2397         /* for UI only */
2398         renderresult_add_names(re->result);
2399         
2400         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2401         
2402         re->stats_draw(re->sdh, &re->i);
2403         
2404         /* stamp image info here */
2405         if((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
2406                 renderresult_stampinfo(re->scene);
2407                 re->display_draw(re->ddh, re->result, NULL);
2408         }
2409 }
2410
2411 static int is_rendering_allowed(Render *re)
2412 {
2413         SceneRenderLayer *srl;
2414         
2415         /* forbidden combinations */
2416         if(re->r.mode & R_PANORAMA) {
2417                 if(re->r.mode & R_BORDER) {
2418                         re->error(re->erh, "No border supported for Panorama");
2419                         return 0;
2420                 }
2421                 if(re->r.mode & R_ORTHO) {
2422                         re->error(re->erh, "No Ortho render possible for Panorama");
2423                         return 0;
2424                 }
2425         }
2426         
2427         if(re->r.mode & R_BORDER) {
2428                 if(re->r.border.xmax <= re->r.border.xmin || 
2429                    re->r.border.ymax <= re->r.border.ymin) {
2430                         re->error(re->erh, "No border area selected.");
2431                         return 0;
2432                 }
2433                 if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2434                         re->error(re->erh, "Border render and Buffer-save not supported yet");
2435                         return 0;
2436                 }
2437         }
2438         
2439         if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2440                 char str[FILE_MAX];
2441                 
2442                 render_unique_exr_name(re, str, 0);
2443                 
2444                 if (BLI_is_writable(str)==0) {
2445                         re->error(re->erh, "Can not save render buffers, check the temp default path");
2446                         return 0;
2447                 }
2448                 
2449                 /* no osa + fullsample won't work... */
2450                 if(re->osa==0)
2451                         re->r.scemode &= ~R_FULL_SAMPLE;
2452                 
2453                 /* no fullsample and edge */
2454                 if((re->r.scemode & R_FULL_SAMPLE) && (re->r.mode & R_EDGE)) {
2455                         re->error(re->erh, "Full Sample doesn't support Edge Enhance");
2456                         return 0;
2457                 }
2458                 
2459         }
2460         else
2461                 re->r.scemode &= ~R_FULL_SAMPLE;        /* clear to be sure */
2462         
2463         if(re->r.scemode & R_DOCOMP) {
2464                 if(re->scene->use_nodes) {
2465                         bNodeTree *ntree= re->scene->nodetree;
2466                         bNode *node;
2467                 
2468                         if(ntree==NULL) {
2469                                 re->error(re->erh, "No Nodetree in Scene");
2470                                 return 0;
2471                         }
2472                         
2473                         for(node= ntree->nodes.first; node; node= node->next)
2474                                 if(node->type==CMP_NODE_COMPOSITE)
2475                                         break;
2476                         
2477                         
2478                         if(node==NULL) {
2479                                 re->error(re->erh, "No Render Output Node in Scene");
2480                                 return 0;
2481                         }
2482                 }
2483         }
2484         
2485         /* check valid camera, without camera render is OK (compo, seq) */
2486         if(re->scene->camera==NULL)
2487                 re->scene->camera= scene_find_camera(re->scene);
2488         
2489         if(!(re->r.scemode & (R_DOSEQ|R_DOCOMP))) {
2490                 if(re->scene->camera==NULL) {
2491                         re->error(re->erh, "No camera");
2492                         return 0;
2493                 }
2494         }
2495         
2496         /* layer flag tests */
2497         if(re->r.scemode & R_SINGLE_LAYER) {
2498                 srl= BLI_findlink(&re->scene->r.layers, re->r.actlay);
2499                 /* force layer to be enabled */
2500                 srl->layflag &= ~SCE_LAY_DISABLE;
2501         }
2502         
2503         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
2504                 if(!(srl->layflag & SCE_LAY_DISABLE))
2505                         break;
2506         if(srl==NULL) {
2507                 re->error(re->erh, "All RenderLayers are disabled");
2508                 return 0;
2509         }
2510         
2511         /* renderer */
2512         if(!ELEM(re->r.renderer, R_INTERN, R_YAFRAY)) {
2513                 re->error(re->erh, "Unknown render engine set");
2514                 return 0;
2515         }
2516         return 1;
2517 }
2518
2519 static void update_physics_cache(Render *re, Scene *scene, int anim_init)
2520 {
2521         PTCacheBaker baker;
2522
2523         baker.scene = scene;
2524         baker.pid = NULL;
2525         baker.bake = 0;
2526         baker.render = 1;
2527         baker.anim_init = 1;
2528         baker.quick_step = 1;
2529         baker.break_test = re->test_break;
2530         baker.break_data = re->tbh;
2531         baker.progressbar = NULL;
2532
2533         BKE_ptcache_make_cache(&baker);
2534 }
2535 /* evaluating scene options for general Blender render */
2536 static int render_initialize_from_scene(Render *re, Scene *scene, int anim, int anim_init)
2537 {
2538         int winx, winy;
2539         rcti disprect;
2540         
2541         /* r.xsch and r.ysch has the actual view window size
2542                 r.border is the clipping rect */
2543         
2544         /* calculate actual render result and display size */
2545         winx= (scene->r.size*scene->r.xsch)/100;
2546         winy= (scene->r.size*scene->r.ysch)/100;
2547         
2548         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2549         if(scene->r.mode & R_BORDER) {
2550                 disprect.xmin= scene->r.border.xmin*winx;
2551                 disprect.xmax= scene->r.border.xmax*winx;
2552                 
2553                 disprect.ymin= scene->r.border.ymin*winy;
2554                 disprect.ymax= scene->r.border.ymax*winy;
2555         }
2556         else {
2557                 disprect.xmin= disprect.ymin= 0;
2558                 disprect.xmax= winx;
2559                 disprect.ymax= winy;
2560         }
2561         
2562         re->scene= scene;
2563         
2564         /* not too nice, but it survives anim-border render */
2565         if(anim) {
2566                 re->disprect= disprect;
2567                 return 1;
2568         }
2569         
2570         /* check all scenes involved */
2571         tag_scenes_for_render(re);
2572
2573         /*
2574          * Disabled completely for now,
2575          * can be later set as render profile option
2576          * and default for background render.
2577         */
2578         if(0) {
2579                 /* make sure dynamics are up to date */
2580                 update_physics_cache(re, scene, anim_init);
2581         }
2582         
2583         if(scene->r.scemode & R_SINGLE_LAYER)
2584                 push_render_result(re);
2585         
2586         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2587         if(!re->ok)  /* if an error was printed, abort */
2588                 return 0;
2589         
2590         /* initstate makes new result, have to send changed tags around */
2591         ntreeCompositTagRender(re->scene);
2592         
2593         if(!is_rendering_allowed(re))
2594                 return 0;
2595         
2596         re->display_init(re->dih, re->result);
2597         re->display_clear(re->dch, re->result);
2598         
2599         return 1;
2600 }
2601
2602 /* general Blender frame render call */
2603 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
2604 {
2605         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2606         G.rendering= 1;
2607         re->result_ok= 0;
2608         
2609         scene->r.cfra= frame;
2610         
2611         if(render_initialize_from_scene(re, scene, 0, 0)) {
2612                 do_render_all_options(re);
2613         }
2614         
2615         /* UGLY WARNING */
2616         G.rendering= 0;
2617         re->result_ok= 1;
2618 }
2619
2620 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
2621 {
2622         char name[FILE_MAX];
2623         RenderResult rres;
2624         
2625         RE_GetResultImage(re, &rres);
2626
2627         /* write movie or image */
2628         if(BKE_imtype_is_movie(scene->r.imtype)) {
2629                 int dofree = 0;
2630                 /* note; the way it gets 32 bits rects is weak... */
2631                 if(rres.rect32==NULL) {
2632                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2633                         dofree = 1;
2634                 }
2635                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
2636                 mh->append_movie(&re->r, scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
2637                 if(dofree) {
2638                         MEM_freeN(rres.rect32);
2639                 }
2640                 printf("Append frame %d", scene->r.cfra);
2641         } 
2642         else {
2643                 BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2644                 
2645                 if(re->r.imtype==R_MULTILAYER) {
2646                         if(re->result) {
2647                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2648                                 printf("Saved: %s", name);
2649                         }
2650                 }
2651                 else {
2652                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
2653                         int ok;
2654                         
2655                         /* if not exists, BKE_write_ibuf makes one */
2656                         ibuf->rect= (unsigned int *)rres.rect32;    
2657                         ibuf->rect_float= rres.rectf;
2658                         ibuf->zbuf_float= rres.rectz;
2659                         
2660                         /* float factor for random dither, imbuf takes care of it */
2661                         ibuf->dither= scene->r.dither_intensity;
2662                         /* gamma correct to sRGB color space */
2663                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2664                                 ibuf->profile = IB_PROFILE_SRGB;
2665
2666                         ok= BKE_write_ibuf(scene, ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2667                         
2668                         if(ok==0) {
2669                                 printf("Render error: cannot save %s\n", name);
2670                                 G.afbreek=1;
2671                         }
2672                         else printf("Saved: %s", name);
2673                         
2674                         /* optional preview images for exr */
2675                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
2676                                 if(BLI_testextensie(name, ".exr")) 
2677                                         name[strlen(name)-4]= 0;
2678                                 BKE_add_image_extension(scene, name, R_JPEG90);
2679                                 ibuf->depth= 24; 
2680                                 BKE_write_ibuf(scene, ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
2681                                 printf("\nSaved: %s", name);
2682                         }
2683                         
2684                                         /* imbuf knows which rects are not part of ibuf */
2685                         IMB_freeImBuf(ibuf);
2686                 }
2687         }
2688         
2689         BLI_timestr(re->i.lastframetime, name);
2690         printf(" Time: %s\n", name);
2691         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2692 }
2693
2694 /* saves images to disk */
2695 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra, int tfra)
2696 {
2697         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
2698         unsigned int lay;
2699         int cfrao= scene->r.cfra;
2700         int nfra;
2701         
2702         /* do not fully call for each frame, it initializes & pops output window */
2703         if(!render_initialize_from_scene(re, scene, 0, 1))
2704                 return;
2705         
2706         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2707         /* is also set by caller renderwin.c */
2708         G.rendering= 1;
2709         re->result_ok= 0;
2710         
2711         if(BKE_imtype_is_movie(scene->r.imtype))
2712                 mh->start_movie(scene, &re->r, re->rectx, re->recty);
2713         
2714         if (mh->get_next_frame) {
2715                 while (!(G.afbreek == 1)) {
2716                         int nf = mh->get_next_frame(&re->r);
2717                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2718                                 scene->r.cfra = re->r.cfra = nf;
2719                                 
2720                                 do_render_all_options(re);
2721
2722                                 if(re->test_break(re->tbh) == 0) {
2723                                         do_write_image_or_movie(re, scene, mh);
2724                                 }
2725                         } else {
2726                                 re->test_break(re->tbh);
2727                         }
2728                 }
2729         } else {
2730                 for(nfra= sfra, scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
2731                         char name[FILE_MAX];
2732                         
2733                         /* only border now, todo: camera lens. (ton) */
2734                         render_initialize_from_scene(re, scene, 1, 0);
2735
2736                         if(nfra!=scene->r.cfra) {
2737                                 /*
2738                                  * Skip this frame, but update for physics and particles system.
2739                                  * From convertblender.c:
2740                                  * in localview, lamps are using normal layers, objects only local bits.
2741                                  */
2742                                 if(scene->lay & 0xFF000000)
2743                                         lay= scene->lay & 0xFF000000;
2744                                 else
2745                                         lay= scene->lay;
2746
2747                                 scene_update_for_newframe(scene, lay);
2748                                 continue;
2749                         }
2750                         else
2751                                 nfra+= tfra;
2752
2753                         /* Touch/NoOverwrite options are only valid for image's */
2754                         if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2755                                 if(scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2756                                         BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2757
2758                                 if(scene->r.mode & R_NO_OVERWRITE && BLI_exist(name)) {
2759                                         printf("skipping existing frame \"%s\"\n", name);
2760                                         continue;
2761                                 }
2762                                 if(scene->r.mode & R_TOUCH && !BLI_exist(name)) {
2763                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2764                                         BLI_touch(name);
2765                                 }
2766                         }
2767
2768                         re->r.cfra= scene->r.cfra;         /* weak.... */
2769                         
2770                         do_render_all_options(re);
2771                         
2772                         if(re->test_break(re->tbh) == 0) {
2773                                 do_write_image_or_movie(re, scene, mh);
2774                         }
2775                 
2776                         if(G.afbreek==1) {
2777                                 /* remove touched file */
2778                                 if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2779                                         if (scene->r.mode & R_TOUCH && BLI_exist(name) && BLI_filepathsize(name) == 0) {
2780                                                 BLI_delete(name, 0, 0);
2781                                         }
2782                                 }
2783                                 
2784                                 break;
2785                         }
2786                 }
2787         }
2788         
2789         /* end movie */
2790         if(BKE_imtype_is_movie(scene->r.imtype))
2791                 mh->end_movie();
2792
2793         scene->r.cfra= cfrao;
2794         
2795         /* UGLY WARNING */
2796         G.rendering= 0;
2797         re->result_ok= 1;
2798 }
2799
2800 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2801
2802 /* only the temp file! */
2803 void RE_ReadRenderResult(Scene *scene, Scene *scenode)
2804 {
2805         Render *re;
2806         int winx, winy;
2807         rcti disprect;
2808         
2809         /* calculate actual render result and display size */
2810         winx= (scene->r.size*scene->r.xsch)/100;
2811         winy= (scene->r.size*scene->r.ysch)/100;
2812         
2813         /* only in movie case we render smaller part */
2814         if(scene->r.mode & R_BORDER) {
2815                 disprect.xmin= scene->r.border.xmin*winx;
2816                 disprect.xmax= scene->r.border.xmax*winx;
2817                 
2818                 disprect.ymin= scene->r.border.ymin*winy;
2819                 disprect.ymax= scene->r.border.ymax*winy;
2820         }
2821         else {
2822                 disprect.xmin= disprect.ymin= 0;
2823                 disprect.xmax= winx;
2824                 disprect.ymax= winy;
2825         }
2826         
2827         if(scenode)
2828                 scene= scenode;
2829         
2830         /* get render: it can be called from UI with draw callbacks */
2831         re= RE_GetRender(scene->id.name);
2832         if(re==NULL)
2833                 re= RE_NewRender(scene->id.name);
2834         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2835         re->scene= scene;
2836         
2837         read_render_result(re, 0);
2838 }
2839
2840 void RE_set_max_threads(int threads)
2841 {
2842         if (threads==0) {
2843                 commandline_threads = BLI_system_thread_count();
2844         } else if(threads>=1 && threads<=BLENDER_MAX_THREADS) {
2845                 commandline_threads= threads;
2846         } else {
2847                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2848         }
2849 }
2850
2851 void RE_init_threadcount(Render *re) 
2852 {
2853         if(commandline_threads >= 1) { /* only set as an arg in background mode */
2854                 re->r.threads= MIN2(commandline_threads, BLENDER_MAX_THREADS);
2855         } else if ((re->r.mode & R_FIXED_THREADS)==0 || commandline_threads == 0) { /* Automatic threads */
2856                 re->r.threads = BLI_system_thread_count();
2857         }
2858 }
2859
2860 /************************** External Engines ***************************/
2861
2862 RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w, int h)
2863 {
2864         Render *re= engine->re;
2865         RenderResult *result;
2866         rcti disprect;
2867
2868         /* ensure the coordinates are within the right limits */
2869         CLAMP(x, 0, re->result->rectx);
2870         CLAMP(y, 0, re->result->recty);
2871         CLAMP(w, 0, re->result->rectx);
2872         CLAMP(h, 0, re->result->recty);
2873
2874         if(x + w > re->result->rectx)
2875                 w= re->result->rectx - x;
2876         if(y + h > re->result->recty)
2877                 h= re->result->recty - y;
2878
2879         /* allocate a render result */
2880         disprect.xmin= x;
2881         disprect.xmax= x+w;
2882         disprect.ymin= y;
2883         disprect.ymax= y+h;
2884
2885         if(0) { // XXX (re->r.scemode & R_FULL_SAMPLE)) {
2886                 result= new_full_sample_buffers(re, &engine->fullresult, &disprect, 0);
2887         }
2888         else {
2889                 result= new_render_result(re, &disprect, 0, RR_USEMEM);
2890                 BLI_addtail(&engine->fullresult, result);
2891         }
2892
2893         return result;
2894 }
2895
2896 void RE_engine_update_result(RenderEngine *engine, RenderResult *result)
2897 {
2898         Render *re= engine->re;
2899
2900         if(result && render_display_draw_enabled(re)) {
2901                 result->renlay= result->layers.first; // weak
2902                 re->display_draw(re->ddh, result, NULL);
2903         }
2904 }
2905
2906 void RE_engine_end_result(RenderEngine *engine, RenderResult *result)
2907 {
2908         Render *re= engine->re;
2909
2910         if(!result)
2911                 return;
2912
2913         /* merge */
2914         if(re->result->exrhandle) {
2915                 RenderResult *rr, *rrpart;
2916                 
2917                 // XXX crashes, exr expects very particular part sizes
2918                 for(rr= re->result, rrpart= result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
2919                         save_render_result_tile(rr, rrpart);
2920         }
2921         else if(render_display_draw_enabled(re)) {
2922                 /* on break, don't merge in result for preview renders, looks nicer */
2923                 if(re->test_break(re->tbh) && (re->r.scemode & R_PREVIEWBUTS));
2924                 else merge_render_result(re->result, result);
2925         }
2926
2927         /* draw */
2928         if(!re->test_break(re->tbh) && render_display_draw_enabled(re)) {
2929                 result->renlay= result->layers.first; // weak
2930                 re->display_draw(re->ddh, result, NULL);
2931         }
2932
2933         /* free */
2934         free_render_result(&engine->fullresult, result);
2935 }
2936
2937 int RE_engine_test_break(RenderEngine *engine)
2938 {
2939         Render *re= engine->re;
2940
2941         return re->test_break(re->tbh);
2942 }
2943
2944 void RE_engine_update_stats(RenderEngine *engine, char *stats, char *info)
2945 {
2946         Render *re= engine->re;
2947
2948         re->i.statstr= stats;
2949         re->i.infostr= info;
2950         re->stats_draw(re->sdh, &re->i);
2951         re->i.infostr= NULL;
2952         re->i.statstr= NULL;
2953 }
2954
2955 /* loads in image into a result, size must match
2956  * x/y offsets are only used on a partial copy when dimensions dont match */
2957 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, char *filename)
2958 {
2959         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect);
2960
2961         if(ibuf  && (ibuf->rect || ibuf->rect_float)) {
2962                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
2963                         if(ibuf->rect_float==NULL)
2964                                 IMB_float_from_rect(ibuf);
2965
2966                         memcpy(layer->rectf, ibuf->rect_float, sizeof(float)*4*layer->rectx*layer->recty);
2967                 } else {
2968                         if ((ibuf->x >= layer->rectx) && (ibuf->y >= layer->recty)) {
2969                                 ImBuf *ibuf_clip;
2970
2971                                 if(ibuf->rect_float==NULL)
2972                                         IMB_float_from_rect(ibuf);
2973
2974                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat, 0);
2975                                 if(ibuf_clip) {
2976                                         IMB_rectcpy(ibuf_clip, ibuf, 0,0, 0,0, layer->rectx, layer->recty);
2977
2978                                         memcpy(layer->rectf, ibuf_clip->rect_float, sizeof(float)*4*layer->rectx*layer->recty);
2979                                         IMB_freeImBuf(ibuf_clip);
2980                                 }
2981                                 else {
2982                                         BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'\n", filename);
2983                                 }
2984                         }
2985                         else {
2986                                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'\n", filename);
2987                         }
2988                 }
2989
2990                 IMB_freeImBuf(ibuf);
2991         }
2992         else {
2993                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
2994         }
2995 }
2996
2997 void RE_result_load_from_file(RenderResult *result, ReportList *reports, char *filename)
2998 {
2999         if(!read_render_result_from_file(filename, result)) {
3000                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
3001                 return;
3002         }
3003 }
3004
3005 static void external_render_3d(Render *re, RenderEngineType *type)
3006 {
3007         RenderEngine engine;
3008
3009         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
3010                 RE_FreeRenderResult(re->result);
3011         
3012                 if(0) // XXX re->r.scemode & R_FULL_SAMPLE)
3013                         re->result= new_full_sample_buffers_exr(re);
3014                 else
3015                         re->result= new_render_result(re, &re->disprect, 0, 0); // XXX re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
3016         }
3017         
3018         if(re->result==NULL)
3019                 return;
3020
3021         /* external */
3022         memset(&engine, 0, sizeof(engine));
3023         engine.type= type;
3024         engine.re= re;
3025
3026         type->render(&engine, re->scene);
3027
3028         free_render_result(&engine.fullresult, engine.fullresult.first);
3029
3030         if(re->result->exrhandle) {
3031                 RenderResult *rr;
3032
3033                 save_empty_result_tiles(re);
3034                 
3035                 for(rr= re->result; rr; rr= rr->next) {
3036                         IMB_exr_close(rr->exrhandle);
3037                         rr->exrhandle= NULL;
3038                 }
3039                 
3040                 free_render_result(&re->fullresult, re->result);
3041                 re->result= NULL;
3042                 
3043                 read_render_result(re, 0);
3044         }
3045 }
3046