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