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