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