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