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