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