Merged changes in the trunk up to revision 25149.
[blender-staging.git] / source / blender / render / intern / source / pipeline.c
1 /**  
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. 
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2006 Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <math.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "DNA_group_types.h"
35 #include "DNA_image_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39 #include "DNA_sequence_types.h"
40 #include "DNA_userdef_types.h"
41
42 #include "BKE_utildefines.h"
43 #include "BKE_global.h"
44 #include "BKE_image.h"
45 #include "BKE_main.h"
46 #include "BKE_node.h"
47 #include "BKE_object.h"
48 #include "BKE_report.h"
49 #include "BKE_scene.h"
50 #include "BKE_writeavi.h"       /* <------ should be replaced once with generic movie module */
51 #include "BKE_sequence.h"
52 #include "BKE_pointcache.h"
53
54 #include "MEM_guardedalloc.h"
55
56 #include "BLI_math.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) Composite 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                 if (re->r.color_mgt_flag & R_COLOR_MANAGEMENT) {
1073                         /* Finally convert back to sRGB rendered image */ 
1074                         for(;tot>0; tot--, cp+=4, fp+=4) {
1075                                 cp[0] = FTOCHAR(linearrgb_to_srgb(fp[0]));
1076                                 cp[1] = FTOCHAR(linearrgb_to_srgb(fp[1]));
1077                                 cp[2] = FTOCHAR(linearrgb_to_srgb(fp[2]));
1078                                 cp[3] = FTOCHAR(fp[3]);
1079                         }
1080                 }
1081                 else {
1082                         /* Color management is off : no conversion necessary */
1083                         for(;tot>0; tot--, cp+=4, fp+=4) {
1084                                 cp[0] = FTOCHAR(fp[0]);
1085                                 cp[1] = FTOCHAR(fp[1]);
1086                                 cp[2] = FTOCHAR(fp[2]);
1087                                 cp[3] = FTOCHAR(fp[3]);
1088                         }
1089                 }
1090
1091         }
1092         else
1093                 /* else fill with black */
1094                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
1095
1096         RE_ReleaseResultImage(re);
1097 }
1098
1099
1100 RenderStats *RE_GetStats(Render *re)
1101 {
1102         return &re->i;
1103 }
1104
1105 Render *RE_NewRender(const char *name)
1106 {
1107         Render *re;
1108         
1109         /* only one render per name exists */
1110         re= RE_GetRender(name);
1111         if(re==NULL) {
1112                 
1113                 /* new render data struct */
1114                 re= MEM_callocN(sizeof(Render), "new render");
1115                 BLI_addtail(&RenderList, re);
1116                 strncpy(re->name, name, RE_MAXNAME);
1117                 BLI_rw_mutex_init(&re->resultmutex);
1118         }
1119         
1120         /* prevent UI to draw old results */
1121         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1122         RE_FreeRenderResult(re->result);
1123         re->result= NULL;
1124         re->result_ok= 0;
1125         BLI_rw_mutex_unlock(&re->resultmutex);
1126         
1127         /* set default empty callbacks */
1128         re->display_init= result_nothing;
1129         re->display_clear= result_nothing;
1130         re->display_draw= result_rcti_nothing;
1131         re->timecursor= int_nothing;
1132         re->test_break= void_nothing;
1133         re->error= print_error;
1134         if(G.background)
1135                 re->stats_draw= stats_background;
1136         else
1137                 re->stats_draw= stats_nothing;
1138         /* clear callback handles */
1139         re->dih= re->dch= re->ddh= re->sdh= re->tch= re->tbh= re->erh= NULL;
1140         
1141         /* init some variables */
1142         re->ycor= 1.0f;
1143         
1144         return re;
1145 }
1146
1147 /* only call this while you know it will remove the link too */
1148 void RE_FreeRender(Render *re)
1149 {
1150         BLI_rw_mutex_end(&re->resultmutex);
1151         
1152         free_renderdata_tables(re);
1153         free_sample_tables(re);
1154         
1155         RE_FreeRenderResult(re->result);
1156         RE_FreeRenderResult(re->pushedresult);
1157         
1158         BLI_remlink(&RenderList, re);
1159         MEM_freeN(re);
1160 }
1161
1162 /* exit blender */
1163 void RE_FreeAllRender(void)
1164 {
1165         while(RenderList.first) {
1166                 RE_FreeRender(RenderList.first);
1167         }
1168 }
1169
1170 /* ********* initialize state ******** */
1171
1172
1173 /* what doesn't change during entire render sequence */
1174 /* disprect is optional, if NULL it assumes full window render */
1175 void RE_InitState(Render *re, Render *source, RenderData *rd, int winx, int winy, rcti *disprect)
1176 {
1177         re->ok= TRUE;   /* maybe flag */
1178         
1179         re->i.starttime= PIL_check_seconds_timer();
1180         re->r= *rd;             /* hardcopy */
1181         
1182         re->winx= winx;
1183         re->winy= winy;
1184         if(disprect) {
1185                 re->disprect= *disprect;
1186                 re->rectx= disprect->xmax-disprect->xmin;
1187                 re->recty= disprect->ymax-disprect->ymin;
1188         }
1189         else {
1190                 re->disprect.xmin= re->disprect.ymin= 0;
1191                 re->disprect.xmax= winx;
1192                 re->disprect.ymax= winy;
1193                 re->rectx= winx;
1194                 re->recty= winy;
1195         }
1196         
1197         if(re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->imtype) &&
1198                                                                                   (re->rectx < 16 || re->recty < 16) )) {
1199                 re->error(re->erh, "Image too small");
1200                 re->ok= 0;
1201         }
1202         else {
1203 #ifdef WITH_OPENEXR
1204                 if(re->r.scemode & R_FULL_SAMPLE)
1205                         re->r.scemode |= R_EXR_TILE_FILE;       /* enable automatic */
1206 #else
1207                 /* can't do this without openexr support */
1208                 re->r.scemode &= ~(R_EXR_TILE_FILE|R_FULL_SAMPLE);
1209 #endif
1210                 
1211                 /* fullsample wants uniform osa levels */
1212                 if(source && (re->r.scemode & R_FULL_SAMPLE)) {
1213                         /* but, if source has no full sample we disable it */
1214                         if((source->r.scemode & R_FULL_SAMPLE)==0)
1215                                 re->r.scemode &= ~R_FULL_SAMPLE;
1216                         else
1217                                 re->r.osa= re->osa= source->osa;
1218                 }
1219                 else {
1220                         /* check state variables, osa? */
1221                         if(re->r.mode & (R_OSA)) {
1222                                 re->osa= re->r.osa;
1223                                 if(re->osa>16) re->osa= 16;
1224                         }
1225                         else re->osa= 0;
1226                 }
1227
1228                 /* always call, checks for gamma, gamma tables and jitter too */
1229                 make_sample_tables(re); 
1230                 
1231                 /* if preview render, we try to keep old result */
1232                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1233
1234                 if(re->r.scemode & R_PREVIEWBUTS) {
1235                         if(re->result && re->result->rectx==re->rectx && re->result->recty==re->recty);
1236                         else {
1237                                 RE_FreeRenderResult(re->result);
1238                                 re->result= NULL;
1239                         }
1240                 }
1241                 else {
1242                         
1243                         /* make empty render result, so display callbacks can initialize */
1244                         RE_FreeRenderResult(re->result);
1245                         re->result= MEM_callocN(sizeof(RenderResult), "new render result");
1246                         re->result->rectx= re->rectx;
1247                         re->result->recty= re->recty;
1248                 }
1249
1250                 BLI_rw_mutex_unlock(&re->resultmutex);
1251                 
1252                 /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
1253                 re->clipcrop= 1.0f + 2.0f/(float)(re->winx>re->winy?re->winy:re->winx);
1254                 
1255                 RE_init_threadcount(re);
1256         }
1257 }
1258
1259 /* part of external api, not called for regular render pipeline */
1260 void RE_SetDispRect (struct Render *re, rcti *disprect)
1261 {
1262         re->disprect= *disprect;
1263         re->rectx= disprect->xmax-disprect->xmin;
1264         re->recty= disprect->ymax-disprect->ymin;
1265         
1266         /* initialize render result */
1267         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1268
1269         RE_FreeRenderResult(re->result);
1270         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1271
1272         BLI_rw_mutex_unlock(&re->resultmutex);
1273 }
1274
1275 void RE_SetWindow(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         perspective_m4( re->winmat,re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
1285         
1286 }
1287
1288 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
1289 {
1290         /* re->ok flag? */
1291         
1292         re->viewplane= *viewplane;
1293         re->clipsta= clipsta;
1294         re->clipend= clipend;
1295         re->r.mode |= R_ORTHO;
1296
1297         orthographic_m4( re->winmat,re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
1298 }
1299
1300 void RE_SetView(Render *re, float mat[][4])
1301 {
1302         /* re->ok flag? */
1303         copy_m4_m4(re->viewmat, mat);
1304         invert_m4_m4(re->viewinv, re->viewmat);
1305 }
1306
1307 /* image and movie output has to move to either imbuf or kernel */
1308 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1309 {
1310         re->display_init= f;
1311         re->dih= handle;
1312 }
1313 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
1314 {
1315         re->display_clear= f;
1316         re->dch= handle;
1317 }
1318 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
1319 {
1320         re->display_draw= f;
1321         re->ddh= handle;
1322 }
1323 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
1324 {
1325         re->stats_draw= f;
1326         re->sdh= handle;
1327 }
1328 void RE_timecursor_cb(Render *re, void *handle, void (*f)(void *handle, int))
1329 {
1330         re->timecursor= f;
1331         re->tch= handle;
1332 }
1333
1334 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
1335 {
1336         re->test_break= f;
1337         re->tbh= handle;
1338 }
1339 void RE_error_cb(Render *re, void *handle, void (*f)(void *handle, char *str))
1340 {
1341         re->error= f;
1342         re->erh= handle;
1343 }
1344
1345
1346 /* ********* add object data (later) ******** */
1347
1348 /* object is considered fully prepared on correct time etc */
1349 /* includes lights */
1350 void RE_AddObject(Render *re, Object *ob)
1351 {
1352         
1353 }
1354
1355 /* *************************************** */
1356
1357 static int render_display_draw_enabled(Render *re)
1358 {
1359         /* don't show preprocess for previewrender sss */
1360         if(re->sss_points)
1361                 return !(re->r.scemode & R_PREVIEWBUTS);
1362         else
1363                 return 1;
1364 }
1365
1366 /* allocate osa new results for samples */
1367 static RenderResult *new_full_sample_buffers(Render *re, ListBase *lb, rcti *partrct, int crop)
1368 {
1369         int a;
1370         
1371         if(re->osa==0)
1372                 return new_render_result(re, partrct, crop, RR_USEMEM);
1373         
1374         for(a=0; a<re->osa; a++) {
1375                 RenderResult *rr= new_render_result(re, partrct, crop, RR_USEMEM);
1376                 BLI_addtail(lb, rr);
1377                 rr->sample_nr= a;
1378         }
1379         
1380         return lb->first;
1381 }
1382
1383
1384 /* the main thread call, renders an entire part */
1385 static void *do_part_thread(void *pa_v)
1386 {
1387         RenderPart *pa= pa_v;
1388         
1389         /* need to return nicely all parts on esc */
1390         if(R.test_break(R.tbh)==0) {
1391                 
1392                 if(!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
1393                         pa->result= new_full_sample_buffers(&R, &pa->fullresult, &pa->disprect, pa->crop);
1394                 else
1395                         pa->result= new_render_result(&R, &pa->disprect, pa->crop, RR_USEMEM);
1396
1397                 if(R.sss_points)
1398                         zbufshade_sss_tile(pa);
1399                 else if(R.osa)
1400                         zbufshadeDA_tile(pa);
1401                 else
1402                         zbufshade_tile(pa);
1403                 
1404                 /* merge too on break! */
1405                 if(R.result->exrhandle) {
1406                         RenderResult *rr, *rrpart;
1407                         
1408                         for(rr= R.result, rrpart= pa->result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
1409                                 save_render_result_tile(rr, rrpart);
1410                         
1411                 }
1412                 else if(render_display_draw_enabled(&R)) {
1413                         /* on break, don't merge in result for preview renders, looks nicer */
1414                         if(R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS));
1415                         else merge_render_result(R.result, pa->result);
1416                 }
1417         }
1418         
1419         pa->ready= 1;
1420         
1421         return NULL;
1422 }
1423
1424 /* returns with render result filled, not threaded, used for preview now only */
1425 static void render_tile_processor(Render *re, int firsttile)
1426 {
1427         RenderPart *pa;
1428         
1429         if(re->test_break(re->tbh))
1430                 return;
1431
1432         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1433
1434         /* hrmf... exception, this is used for preview render, re-entrant, so render result has to be re-used */
1435         if(re->result==NULL || re->result->layers.first==NULL) {
1436                 if(re->result) RE_FreeRenderResult(re->result);
1437                 re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1438         }
1439
1440         BLI_rw_mutex_unlock(&re->resultmutex);
1441         
1442         re->stats_draw(re->sdh, &re->i);
1443  
1444         if(re->result==NULL)
1445                 return;
1446         
1447         initparts(re);
1448
1449         /* assuming no new data gets added to dbase... */
1450         R= *re;
1451         
1452         for(pa= re->parts.first; pa; pa= pa->next) {
1453                 if(firsttile) {
1454                         re->i.partsdone++;      /* was reset in initparts */
1455                         firsttile--;
1456                 }
1457                 else {
1458                         do_part_thread(pa);
1459                         
1460                         if(pa->result) {
1461                                 if(!re->test_break(re->tbh)) {
1462                                         if(render_display_draw_enabled(re))
1463                                                 re->display_draw(re->ddh, pa->result, NULL);
1464                                         
1465                                         re->i.partsdone++;
1466                                         re->stats_draw(re->sdh, &re->i);
1467                                 }
1468                                 RE_FreeRenderResult(pa->result);
1469                                 pa->result= NULL;
1470                         }               
1471                         if(re->test_break(re->tbh))
1472                                 break;
1473                 }
1474         }
1475
1476         freeparts(re);
1477 }
1478
1479 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
1480 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
1481 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
1482 float panorama_pixel_rot(Render *re)
1483 {
1484         float psize, phi, xfac;
1485         
1486         /* size of 1 pixel mapped to viewplane coords */
1487         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
1488         /* angle of a pixel */
1489         phi= atan(psize/re->clipsta);
1490         
1491         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
1492         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
1493         xfac= atan(0.5f*xfac/re->clipsta); 
1494         /* and how much the same viewplane angle is wrapped */
1495         psize= 0.5f*phi*((float)re->partx);
1496         
1497         /* the ratio applied to final per-pixel angle */
1498         phi*= xfac/psize;
1499         
1500         return phi;
1501 }
1502
1503 /* call when all parts stopped rendering, to find the next Y slice */
1504 /* if slice found, it rotates the dbase */
1505 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
1506 {
1507         RenderPart *pa, *best= NULL;
1508         
1509         *minx= re->winx;
1510         
1511         /* most left part of the non-rendering parts */
1512         for(pa= re->parts.first; pa; pa= pa->next) {
1513                 if(pa->ready==0 && pa->nr==0) {
1514                         if(pa->disprect.xmin < *minx) {
1515                                 best= pa;
1516                                 *minx= pa->disprect.xmin;
1517                         }
1518                 }
1519         }
1520                         
1521         if(best) {
1522                 float phi= panorama_pixel_rot(re);
1523
1524                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
1525                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
1526                 
1527                 /* shift viewplane */
1528                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
1529                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
1530                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
1531                 copy_m4_m4(R.winmat, re->winmat);
1532                 
1533                 /* rotate database according to part coordinates */
1534                 project_renderdata(re, projectverto, 1, -R.panodxp*phi, 1);
1535                 R.panosi= sin(R.panodxp*phi);
1536                 R.panoco= cos(R.panodxp*phi);
1537         }
1538         return best;
1539 }
1540
1541 static RenderPart *find_next_part(Render *re, int minx)
1542 {
1543         RenderPart *pa, *best= NULL;
1544         int centx=re->winx/2, centy=re->winy/2, tot=1;
1545         int mindist, distx, disty;
1546         
1547         /* find center of rendered parts, image center counts for 1 too */
1548         for(pa= re->parts.first; pa; pa= pa->next) {
1549                 if(pa->ready) {
1550                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1551                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1552                         tot++;
1553                 }
1554         }
1555         centx/=tot;
1556         centy/=tot;
1557         
1558         /* closest of the non-rendering parts */
1559         mindist= re->winx*re->winy;
1560         for(pa= re->parts.first; pa; pa= pa->next) {
1561                 if(pa->ready==0 && pa->nr==0) {
1562                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1563                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1564                         distx= (int)sqrt(distx*distx + disty*disty);
1565                         if(distx<mindist) {
1566                                 if(re->r.mode & R_PANORAMA) {
1567                                         if(pa->disprect.xmin==minx) {
1568                                                 best= pa;
1569                                                 mindist= distx;
1570                                         }
1571                                 }
1572                                 else {
1573                                         best= pa;
1574                                         mindist= distx;
1575                                 }
1576                         }
1577                 }
1578         }
1579         return best;
1580 }
1581
1582 static void print_part_stats(Render *re, RenderPart *pa)
1583 {
1584         char str[64];
1585         
1586         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1587         re->i.infostr= str;
1588         re->stats_draw(re->sdh, &re->i);
1589         re->i.infostr= NULL;
1590 }
1591
1592 /* make osa new results for samples */
1593 static RenderResult *new_full_sample_buffers_exr(Render *re)
1594 {
1595         int a;
1596         
1597         for(a=0; a<re->osa; a++) {
1598                 RenderResult *rr= new_render_result(re, &re->disprect, 0, 1);
1599                 BLI_addtail(&re->fullresult, rr);
1600                 rr->sample_nr= a;
1601         }
1602         
1603         return re->fullresult.first;
1604 }
1605
1606 static void threaded_tile_processor(Render *re)
1607 {
1608         ListBase threads;
1609         RenderPart *pa, *nextpa;
1610         rctf viewplane= re->viewplane;
1611         int rendering=1, counter= 1, drawtimer=0, hasdrawn, minx=0;
1612         
1613         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1614
1615         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
1616         if(re->result==NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
1617                 RE_FreeRenderResult(re->result);
1618         
1619                 if(re->sss_points && render_display_draw_enabled(re))
1620                         re->result= new_render_result(re, &re->disprect, 0, 0);
1621                 else if(re->r.scemode & R_FULL_SAMPLE)
1622                         re->result= new_full_sample_buffers_exr(re);
1623                 else
1624                         re->result= new_render_result(re, &re->disprect, 0, re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE));
1625         }
1626
1627         BLI_rw_mutex_unlock(&re->resultmutex);
1628         
1629         if(re->result==NULL)
1630                 return;
1631         
1632         /* warning; no return here without closing exr file */
1633         
1634         initparts(re);
1635
1636         if(re->result->exrhandle) {
1637                 RenderResult *rr;
1638                 char str[FILE_MAX];
1639                 
1640                 for(rr= re->result; rr; rr= rr->next) {
1641                         render_unique_exr_name(re, str, rr->sample_nr);
1642                 
1643                         printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
1644                         IMB_exrtile_begin_write(rr->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
1645                 }
1646         }
1647         
1648         BLI_init_threads(&threads, do_part_thread, re->r.threads);
1649         
1650         /* assuming no new data gets added to dbase... */
1651         R= *re;
1652         
1653         /* set threadsafe break */
1654         R.test_break= thread_break;
1655         
1656         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1657         if(re->r.mode & R_PANORAMA)
1658                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1659         else
1660                 nextpa= find_next_part(re, 0);
1661         
1662         while(rendering) {
1663                 
1664                 if(re->test_break(re->tbh))
1665                         PIL_sleep_ms(50);
1666                 else if(nextpa && BLI_available_threads(&threads)) {
1667                         drawtimer= 0;
1668                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1669                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1670                         BLI_insert_thread(&threads, nextpa);
1671
1672                         nextpa= find_next_part(re, minx);
1673                 }
1674                 else if(re->r.mode & R_PANORAMA) {
1675                         if(nextpa==NULL && BLI_available_threads(&threads)==re->r.threads)
1676                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1677                         else {
1678                                 PIL_sleep_ms(50);
1679                                 drawtimer++;
1680                         }
1681                 }
1682                 else {
1683                         PIL_sleep_ms(50);
1684                         drawtimer++;
1685                 }
1686                 
1687                 /* check for ready ones to display, and if we need to continue */
1688                 rendering= 0;
1689                 hasdrawn= 0;
1690                 for(pa= re->parts.first; pa; pa= pa->next) {
1691                         if(pa->ready) {
1692                                 
1693                                 BLI_remove_thread(&threads, pa);
1694                                 
1695                                 if(pa->result) {
1696                                         if(render_display_draw_enabled(re))
1697                                                 re->display_draw(re->ddh, pa->result, NULL);
1698                                         print_part_stats(re, pa);
1699                                         
1700                                         free_render_result(&pa->fullresult, pa->result);
1701                                         pa->result= NULL;
1702                                         re->i.partsdone++;
1703                                         hasdrawn= 1;
1704                                 }
1705                         }
1706                         else {
1707                                 rendering= 1;
1708                                 if(pa->nr && pa->result && drawtimer>20) {
1709                                         if(render_display_draw_enabled(re))
1710                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
1711                                         hasdrawn= 1;
1712                                 }
1713                         }
1714                 }
1715                 if(hasdrawn)
1716                         drawtimer= 0;
1717
1718                 /* on break, wait for all slots to get freed */
1719                 if( (g_break=re->test_break(re->tbh)) && BLI_available_threads(&threads)==re->r.threads)
1720                         rendering= 0;
1721                 
1722         }
1723         
1724         if(re->result->exrhandle) {
1725                 RenderResult *rr;
1726
1727                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1728                 save_empty_result_tiles(re);
1729                 
1730                 for(rr= re->result; rr; rr= rr->next) {
1731                         IMB_exr_close(rr->exrhandle);
1732                         rr->exrhandle= NULL;
1733                 }
1734                 
1735                 free_render_result(&re->fullresult, re->result);
1736                 re->result= NULL;
1737
1738                 BLI_rw_mutex_unlock(&re->resultmutex);
1739                 
1740                 read_render_result(re, 0);
1741         }
1742         
1743         /* unset threadsafety */
1744         g_break= 0;
1745         
1746         BLI_end_threads(&threads);
1747         freeparts(re);
1748         re->viewplane= viewplane; /* restore viewplane, modified by pano render */
1749 }
1750
1751 /* currently only called by preview renders and envmap */
1752 void RE_TileProcessor(Render *re, int firsttile, int threaded)
1753 {
1754         /* the partsdone variable has to be reset to firsttile, to survive esc before it was set to zero */
1755         
1756         re->i.partsdone= firsttile;
1757
1758         if(!re->sss_points)
1759                 re->i.starttime= PIL_check_seconds_timer();
1760
1761         if(threaded)
1762                 threaded_tile_processor(re);
1763         else
1764                 render_tile_processor(re, firsttile);
1765                 
1766         if(!re->sss_points)
1767                 re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1768         re->stats_draw(re->sdh, &re->i);
1769 }
1770
1771
1772 /* ************  This part uses API, for rendering Blender scenes ********** */
1773
1774 static void external_render_3d(Render *re, RenderEngineType *type);
1775
1776 static void do_render_3d(Render *re)
1777 {
1778         RenderEngineType *type;
1779
1780         /* try external */
1781         for(type=R_engines.first; type; type=type->next)
1782                 if(strcmp(type->idname, re->r.engine) == 0)
1783                         break;
1784
1785         if(type && type->render) {
1786                 external_render_3d(re, type);
1787                 return;
1788         }
1789
1790         /* internal */
1791         
1792 //      re->cfra= cfra; /* <- unused! */
1793         
1794         /* make render verts/faces/halos/lamps */
1795         if(render_scene_needs_vector(re))
1796                 RE_Database_FromScene_Vectors(re, re->scene);
1797         else
1798            RE_Database_FromScene(re, re->scene, 1);
1799         
1800         threaded_tile_processor(re);
1801         
1802         /* do left-over 3d post effects (flares) */
1803         if(re->flag & R_HALO)
1804                 if(!re->test_break(re->tbh))
1805                         add_halo_flare(re);
1806         
1807         /* Freestyle  */
1808         if( re->r.mode & R_EDGE_FRS && re->r.renderer==R_INTERN)
1809                 FRS_add_Freestyle(re);
1810                 
1811         /* free all render verts etc */
1812         RE_Database_Free(re);
1813 }
1814
1815 /* called by blur loop, accumulate RGBA key alpha */
1816 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
1817 {
1818         float mfac= 1.0f - blurfac;
1819         int a, b, stride= 4*rr->rectx;
1820         int len= stride*sizeof(float);
1821         
1822         for(a=0; a<rr->recty; a++) {
1823                 if(blurfac==1.0f) {
1824                         memcpy(rectf, rectf1, len);
1825                 }
1826                 else {
1827                         float *rf= rectf, *rf1= rectf1;
1828                         
1829                         for( b= rr->rectx; b>0; b--, rf+=4, rf1+=4) {
1830                                 if(rf1[3]<0.01f)
1831                                         rf[3]= mfac*rf[3];
1832                                 else if(rf[3]<0.01f) {
1833                                         rf[0]= rf1[0];
1834                                         rf[1]= rf1[1];
1835                                         rf[2]= rf1[2];
1836                                         rf[3]= blurfac*rf1[3];
1837                                 }
1838                                 else {
1839                                         rf[0]= mfac*rf[0] + blurfac*rf1[0];
1840                                         rf[1]= mfac*rf[1] + blurfac*rf1[1];
1841                                         rf[2]= mfac*rf[2] + blurfac*rf1[2];
1842                                         rf[3]= mfac*rf[3] + blurfac*rf1[3];
1843                                 }                               
1844                         }
1845                 }
1846                 rectf+= stride;
1847                 rectf1+= stride;
1848         }
1849 }
1850
1851 /* called by blur loop, accumulate renderlayers */
1852 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1853 {
1854         float mfac= 1.0f - blurfac;
1855         int a, b, stride= channels*rr->rectx;
1856         int len= stride*sizeof(float);
1857         
1858         for(a=0; a<rr->recty; a++) {
1859                 if(blurfac==1.0f) {
1860                         memcpy(rectf, rectf1, len);
1861                 }
1862                 else {
1863                         float *rf= rectf, *rf1= rectf1;
1864                         
1865                         for( b= rr->rectx*channels; b>0; b--, rf++, rf1++) {
1866                                 rf[0]= mfac*rf[0] + blurfac*rf1[0];
1867                         }
1868                 }
1869                 rectf+= stride;
1870                 rectf1+= stride;
1871         }
1872 }
1873
1874
1875 /* called by blur loop, accumulate renderlayers */
1876 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1877 {
1878         RenderLayer *rl, *rl1;
1879         RenderPass *rpass, *rpass1;
1880         
1881         rl1= brr->layers.first;
1882         for(rl= rr->layers.first; rl && rl1; rl= rl->next, rl1= rl1->next) {
1883                 
1884                 /* combined */
1885                 if(rl->rectf && rl1->rectf) {
1886                         if(key_alpha)
1887                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1888                         else
1889                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1890                 }
1891                 
1892                 /* passes are allocated in sync */
1893                 rpass1= rl1->passes.first;
1894                 for(rpass= rl->passes.first; rpass && rpass1; rpass= rpass->next, rpass1= rpass1->next) {
1895                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1896                 }
1897         }
1898 }
1899
1900 /* main blur loop, can be called by fields too */
1901 static void do_render_blur_3d(Render *re)
1902 {
1903         RenderResult *rres;
1904         float blurfac;
1905         int blur= re->r.osa;
1906         
1907         /* create accumulation render result */
1908         rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
1909         
1910         /* do the blur steps */
1911         while(blur--) {
1912                 set_mblur_offs( re->r.blurfac*((float)(re->r.osa-blur))/(float)re->r.osa );
1913                 
1914                 re->i.curblur= re->r.osa-blur;  /* stats */
1915                 
1916                 do_render_3d(re);
1917                 
1918                 blurfac= 1.0f/(float)(re->r.osa-blur);
1919                 
1920                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1921                 if(re->test_break(re->tbh)) break;
1922         }
1923         
1924         /* swap results */
1925         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1926         RE_FreeRenderResult(re->result);
1927         re->result= rres;
1928         BLI_rw_mutex_unlock(&re->resultmutex);
1929         
1930         set_mblur_offs(0.0f);
1931         re->i.curblur= 0;       /* stats */
1932         
1933         /* weak... the display callback wants an active renderlayer pointer... */
1934         re->result->renlay= render_get_active_layer(re, re->result);
1935         re->display_draw(re->ddh, re->result, NULL);    
1936 }
1937
1938
1939 /* function assumes rectf1 and rectf2 to be half size of rectf */
1940 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1941 {
1942         int a, stride= channels*rr->rectx;
1943         int len= stride*sizeof(float);
1944         
1945         for(a=0; a<rr->recty; a+=2) {
1946                 memcpy(rectf, rectf1, len);
1947                 rectf+= stride;
1948                 rectf1+= stride;
1949                 memcpy(rectf, rectf2, len);
1950                 rectf+= stride;
1951                 rectf2+= stride;
1952         }
1953 }
1954
1955 /* merge render results of 2 fields */
1956 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1957 {
1958         RenderLayer *rl, *rl1, *rl2;
1959         RenderPass *rpass, *rpass1, *rpass2;
1960         
1961         rl1= rr1->layers.first;
1962         rl2= rr2->layers.first;
1963         for(rl= rr->layers.first; rl && rl1 && rl2; rl= rl->next, rl1= rl1->next, rl2= rl2->next) {
1964                 
1965                 /* combined */
1966                 if(rl->rectf && rl1->rectf && rl2->rectf)
1967                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1968                 
1969                 /* passes are allocated in sync */
1970                 rpass1= rl1->passes.first;
1971                 rpass2= rl2->passes.first;
1972                 for(rpass= rl->passes.first; rpass && rpass1 && rpass2; rpass= rpass->next, rpass1= rpass1->next, rpass2= rpass2->next) {
1973                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1974                 }
1975         }
1976 }
1977
1978
1979 /* interleaves 2 frames */
1980 static void do_render_fields_3d(Render *re)
1981 {
1982         RenderResult *rr1, *rr2= NULL;
1983         
1984         /* no render result was created, we can safely halve render y */
1985         re->winy /= 2;
1986         re->recty /= 2;
1987         re->disprect.ymin /= 2;
1988         re->disprect.ymax /= 2;
1989         
1990         re->i.curfield= 1;      /* stats */
1991         
1992         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1993         RE_SetCamera(re, re->scene->camera);
1994         if(re->r.mode & R_MBLUR)
1995                 do_render_blur_3d(re);
1996         else
1997                 do_render_3d(re);
1998
1999         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2000         rr1= re->result;
2001         re->result= NULL;
2002         BLI_rw_mutex_unlock(&re->resultmutex);
2003         
2004         /* second field */
2005         if(!re->test_break(re->tbh)) {
2006                 
2007                 re->i.curfield= 2;      /* stats */
2008                 
2009                 re->flag |= R_SEC_FIELD;
2010                 if((re->r.mode & R_FIELDSTILL)==0) 
2011                         set_field_offs(0.5f);
2012                 RE_SetCamera(re, re->scene->camera);
2013                 if(re->r.mode & R_MBLUR)
2014                         do_render_blur_3d(re);
2015                 else
2016                         do_render_3d(re);
2017                 re->flag &= ~R_SEC_FIELD;
2018                 set_field_offs(0.0f);
2019                 
2020                 rr2= re->result;
2021         }
2022         
2023         /* allocate original height new buffers */
2024         re->winy *= 2;
2025         re->recty *= 2;
2026         re->disprect.ymin *= 2;
2027         re->disprect.ymax *= 2;
2028
2029         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2030         re->result= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2031         RE_FreeRenderResult(rr1);
2032
2033         if(rr2) {
2034                 if(re->r.mode & R_ODDFIELD)
2035                         merge_renderresult_fields(re->result, rr2, rr1);
2036                 else
2037                         merge_renderresult_fields(re->result, rr1, rr2);
2038                 
2039                 RE_FreeRenderResult(rr2);
2040         }
2041         
2042         re->i.curfield= 0;      /* stats */
2043         
2044         /* weak... the display callback wants an active renderlayer pointer... */
2045         re->result->renlay= render_get_active_layer(re, re->result);
2046
2047         BLI_rw_mutex_unlock(&re->resultmutex);
2048
2049         re->display_draw(re->ddh, re->result, NULL);
2050 }
2051
2052 static void load_backbuffer(Render *re)
2053 {
2054         if(re->r.alphamode == R_ADDSKY) {
2055                 ImBuf *ibuf;
2056                 char name[256];
2057                 
2058                 strcpy(name, re->r.backbuf);
2059                 BLI_convertstringcode(name, G.sce);
2060                 BLI_convertstringframe(name, re->r.cfra);
2061                 
2062                 if(re->backbuf) {
2063                         re->backbuf->id.us--;
2064                         if(re->backbuf->id.us<1)
2065                                 BKE_image_signal(re->backbuf, NULL, IMA_SIGNAL_RELOAD);
2066                 }
2067                 
2068                 re->backbuf= BKE_add_image_file(name, re->r.cfra);
2069                 ibuf= BKE_image_get_ibuf(re->backbuf, NULL);
2070                 if(ibuf==NULL) {
2071                         // error() doesnt work with render window open
2072                         //error("No backbuf there!");
2073                         printf("Error: No backbuf %s\n", name);
2074                 }
2075                 else {
2076                         if (re->r.mode & R_FIELDS)
2077                                 image_de_interlace(re->backbuf, re->r.mode & R_ODDFIELD);
2078                 }
2079         }
2080 }
2081
2082 /* main render routine, no compositing */
2083 static void do_render_fields_blur_3d(Render *re)
2084 {
2085         /* also check for camera here */
2086         if(re->scene->camera==NULL) {
2087                 printf("ERROR: Cannot render, no camera\n");
2088                 G.afbreek= 1;
2089                 return;
2090         }
2091         
2092         /* backbuffer initialize */
2093         if(re->r.bufflag & 1)
2094                 load_backbuffer(re);
2095
2096         /* now use renderdata and camera to set viewplane */
2097         RE_SetCamera(re, re->scene->camera);
2098         
2099         if(re->r.mode & R_FIELDS)
2100                 do_render_fields_3d(re);
2101         else if(re->r.mode & R_MBLUR)
2102                 do_render_blur_3d(re);
2103         else
2104                 do_render_3d(re);
2105         
2106         /* when border render, check if we have to insert it in black */
2107         if(re->result) {
2108                 if(re->r.mode & R_BORDER) {
2109                         if((re->r.mode & R_CROP)==0) {
2110                                 RenderResult *rres;
2111                                 
2112                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2113
2114                                 /* sub-rect for merge call later on */
2115                                 re->result->tilerect= re->disprect;
2116                                 
2117                                 /* this copying sequence could become function? */
2118                                 /* weak is: it chances disprect from border */
2119                                 re->disprect.xmin= re->disprect.ymin= 0;
2120                                 re->disprect.xmax= re->winx;
2121                                 re->disprect.ymax= re->winy;
2122                                 re->rectx= re->winx;
2123                                 re->recty= re->winy;
2124                                 
2125                                 rres= new_render_result(re, &re->disprect, 0, RR_USEMEM);
2126                                 
2127                                 merge_render_result(rres, re->result);
2128                                 RE_FreeRenderResult(re->result);
2129                                 re->result= rres;
2130                                 
2131                                 /* weak... the display callback wants an active renderlayer pointer... */
2132                                 re->result->renlay= render_get_active_layer(re, re->result);
2133                                 
2134                                 BLI_rw_mutex_unlock(&re->resultmutex);
2135                 
2136                                 re->display_init(re->dih, re->result);
2137                                 re->display_draw(re->ddh, re->result, NULL);
2138                         }
2139                         else {
2140                                 /* set offset (again) for use in compositor, disprect was manipulated. */
2141                                 re->result->xof= 0;
2142                                 re->result->yof= 0;
2143                         }
2144                 }
2145         }
2146 }
2147
2148
2149 /* within context of current Render *re, render another scene.
2150    it uses current render image size and disprect, but doesn't execute composite
2151 */
2152 static void render_scene(Render *re, Scene *sce, int cfra)
2153 {
2154         Render *resc= RE_NewRender(sce->id.name);
2155         int winx= re->winx, winy= re->winy;
2156         
2157         sce->r.cfra= cfra;
2158                 
2159         /* exception: scene uses own size (unfinished code) */
2160         if(0) {
2161                 winx= (sce->r.size*sce->r.xsch)/100;
2162                 winy= (sce->r.size*sce->r.ysch)/100;
2163         }
2164         
2165         /* initial setup */
2166         RE_InitState(resc, re, &sce->r, winx, winy, &re->disprect);
2167         
2168         /* still unsure entity this... */
2169         resc->scene= sce;
2170         
2171         /* ensure scene has depsgraph, base flags etc OK */
2172         set_scene_bg(sce);
2173
2174         /* copy callbacks */
2175         resc->display_draw= re->display_draw;
2176         resc->ddh= re->ddh;
2177         resc->test_break= re->test_break;
2178         resc->tbh= re->tbh;
2179         resc->stats_draw= re->stats_draw;
2180         resc->sdh= re->sdh;
2181         
2182         do_render_fields_blur_3d(resc);
2183 }
2184
2185 static void tag_scenes_for_render(Render *re)
2186 {
2187         bNode *node;
2188         Scene *sce;
2189         
2190         for(sce= G.main->scene.first; sce; sce= sce->id.next)
2191                 sce->id.flag &= ~LIB_DOIT;
2192         
2193         re->scene->id.flag |= LIB_DOIT;
2194         
2195         if(re->scene->nodetree==NULL) return;
2196         
2197         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
2198         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2199                 if(node->type==CMP_NODE_R_LAYERS) {
2200                         if(node->id) {
2201                                 if(node->id != (ID *)re->scene)
2202                                         node->id->flag |= LIB_DOIT;
2203                         }
2204                 }
2205         }
2206         
2207 }
2208
2209 static void ntree_render_scenes(Render *re)
2210 {
2211         bNode *node;
2212         int cfra= re->scene->r.cfra;
2213         
2214         if(re->scene->nodetree==NULL) return;
2215         
2216         tag_scenes_for_render(re);
2217         
2218         /* now foreach render-result node tagged we do a full render */
2219         /* results are stored in a way compisitor will find it */
2220         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
2221                 if(node->type==CMP_NODE_R_LAYERS) {
2222                         if(node->id && node->id != (ID *)re->scene) {
2223                                 if(node->id->flag & LIB_DOIT) {
2224                                         render_scene(re, (Scene *)node->id, cfra);
2225                                         node->id->flag &= ~LIB_DOIT;
2226                                 }
2227                         }
2228                 }
2229         }
2230 }
2231
2232 /* helper call to detect if theres a composite with render-result node */
2233 static int composite_needs_render(Scene *sce)
2234 {
2235         bNodeTree *ntree= sce->nodetree;
2236         bNode *node;
2237         
2238         if(ntree==NULL) return 1;
2239         if(sce->use_nodes==0) return 1;
2240         if((sce->r.scemode & R_DOCOMP)==0) return 1;
2241                 
2242         for(node= ntree->nodes.first; node; node= node->next) {
2243                 if(node->type==CMP_NODE_R_LAYERS)
2244                         if(node->id==NULL || node->id==&sce->id)
2245                                 return 1;
2246         }
2247         return 0;
2248 }
2249
2250 /* bad call... need to think over proper method still */
2251 static void render_composit_stats(void *unused, char *str)
2252 {
2253         R.i.infostr= str;
2254         R.stats_draw(R.sdh, &R.i);
2255         R.i.infostr= NULL;
2256 }
2257
2258
2259 /* reads all buffers, calls optional composite, merges in first result->rectf */
2260 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
2261 {
2262         float *rectf, filt[3][3];
2263         int sample;
2264         
2265         /* filtmask needs it */
2266         R= *re;
2267         
2268         /* we accumulate in here */
2269         rectf= MEM_mapallocN(re->rectx*re->recty*sizeof(float)*4, "fullsample rgba");
2270         
2271         for(sample=0; sample<re->r.osa; sample++) {
2272                 RenderResult rres;
2273                 int x, y, mask;
2274                 
2275                 /* set all involved renders on the samplebuffers (first was done by render itself) */
2276                 /* also function below assumes this */
2277                 if(sample) {
2278                         Render *re1;
2279                         
2280                         tag_scenes_for_render(re);
2281                         for(re1= RenderList.first; re1; re1= re1->next) {
2282                                 if(re1->scene->id.flag & LIB_DOIT)
2283                                         if(re1->r.scemode & R_FULL_SAMPLE)
2284                                                 read_render_result(re1, sample);
2285                         }
2286                 }
2287
2288                 /* composite */
2289                 if(ntree) {
2290                         ntreeCompositTagRender(re->scene);
2291                         ntreeCompositTagAnimated(ntree);
2292                         
2293                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
2294                 }
2295                 
2296                 /* ensure we get either composited result or the active layer */
2297                 RE_AcquireResultImage(re, &rres);
2298                 
2299                 /* accumulate with filter, and clip */
2300                 mask= (1<<sample);
2301                 mask_array(mask, filt);
2302
2303                 for(y=0; y<re->recty; y++) {
2304                         float *rf= rectf + 4*y*re->rectx;
2305                         float *col= rres.rectf + 4*y*re->rectx;
2306                                 
2307                         for(x=0; x<re->rectx; x++, rf+=4, col+=4) {
2308                                 if(col[0]<0.0f) col[0]=0.0f; else if(col[0] > 1.0f) col[0]= 1.0f;
2309                                 if(col[1]<0.0f) col[1]=0.0f; else if(col[1] > 1.0f) col[1]= 1.0f;
2310                                 if(col[2]<0.0f) col[2]=0.0f; else if(col[2] > 1.0f) col[2]= 1.0f;
2311                                 
2312                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
2313                         }
2314                 }
2315                 
2316                 RE_ReleaseResultImage(re);
2317
2318                 /* show stuff */
2319                 if(sample!=re->osa-1) {
2320                         /* weak... the display callback wants an active renderlayer pointer... */
2321                         re->result->renlay= render_get_active_layer(re, re->result);
2322                         re->display_draw(re->ddh, re->result, NULL);
2323                 }
2324                 
2325                 if(re->test_break(re->tbh))
2326                         break;
2327         }
2328         
2329         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2330         if(re->result->rectf) 
2331                 MEM_freeN(re->result->rectf);
2332         re->result->rectf= rectf;
2333         BLI_rw_mutex_unlock(&re->resultmutex);
2334 }
2335
2336 void RE_MergeFullSample(Render *re, Scene *sce, bNodeTree *ntree)
2337 {
2338         Scene *scene;
2339         bNode *node;
2340         
2341         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
2342         
2343         /* tag scenes unread */
2344         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2345                 scene->id.flag |= LIB_DOIT;
2346         
2347         for(node= ntree->nodes.first; node; node= node->next) {
2348                 if(node->type==CMP_NODE_R_LAYERS) {
2349                         Scene *nodescene= (Scene *)node->id;
2350                         
2351                         if(nodescene==NULL) nodescene= sce;
2352                         if(nodescene->id.flag & LIB_DOIT) {
2353                                 nodescene->r.mode |= R_OSA;     /* render struct needs tables */
2354                                 RE_ReadRenderResult(sce, nodescene);
2355                                 nodescene->id.flag &= ~LIB_DOIT;
2356                         }
2357                 }
2358         }
2359         
2360         /* own render result should be read/allocated */
2361         if(re->scene->id.flag & LIB_DOIT)
2362                 RE_ReadRenderResult(re->scene, re->scene);
2363         
2364         /* and now we can draw (result is there) */
2365         re->display_init(re->dih, re->result);
2366         re->display_clear(re->dch, re->result);
2367         
2368         do_merge_fullsample(re, ntree);
2369 }
2370
2371 /* returns fully composited render-result on given time step (in RenderData) */
2372 static void do_render_composite_fields_blur_3d(Render *re)
2373 {
2374         bNodeTree *ntree= re->scene->nodetree;
2375         
2376         /* INIT seeding, compositor can use random texture */
2377         BLI_srandom(re->r.cfra);
2378         
2379         if(composite_needs_render(re->scene)) {
2380                 /* save memory... free all cached images */
2381                 ntreeFreeCache(ntree);
2382                 
2383                 do_render_fields_blur_3d(re);
2384         }
2385         
2386         /* swap render result */
2387         if(re->r.scemode & R_SINGLE_LAYER)
2388                 pop_render_result(re);
2389         
2390         if(!re->test_break(re->tbh)) {
2391                 
2392                 if(ntree) {
2393                         ntreeCompositTagRender(re->scene);
2394                         ntreeCompositTagAnimated(ntree);
2395                 }
2396                 
2397                 if(1 || !(re->r.scemode & R_COMP_RERENDER)) {
2398                         if(ntree && re->r.scemode & R_DOCOMP) {
2399                                 /* checks if there are render-result nodes that need scene */
2400                                 if((re->r.scemode & R_SINGLE_LAYER)==0)
2401                                         ntree_render_scenes(re);
2402                                 
2403                                 if(!re->test_break(re->tbh)) {
2404                                         ntree->stats_draw= render_composit_stats;
2405                                         ntree->test_break= re->test_break;
2406                                         ntree->sdh= re->sdh;
2407                                         ntree->tbh= re->tbh;
2408                                         /* in case it was never initialized */
2409                                         R.sdh= re->sdh;
2410                                         R.stats_draw= re->stats_draw;
2411                                         
2412                                         if(re->r.scemode & R_FULL_SAMPLE) 
2413                                                 do_merge_fullsample(re, ntree);
2414                                         else
2415                                                 ntreeCompositExecTree(ntree, &re->r, G.background==0);
2416                                         
2417                                         ntree->stats_draw= NULL;
2418                                         ntree->test_break= NULL;
2419                                         ntree->tbh= ntree->sdh= NULL;
2420                                 }
2421                         }
2422                         else if(re->r.scemode & R_FULL_SAMPLE)
2423                                 do_merge_fullsample(re, NULL);
2424                 }
2425         }
2426
2427         /* weak... the display callback wants an active renderlayer pointer... */
2428         re->result->renlay= render_get_active_layer(re, re->result);
2429         re->display_draw(re->ddh, re->result, NULL);
2430 }
2431
2432 static void renderresult_stampinfo(Scene *scene)
2433 {
2434         RenderResult rres;
2435         Render *re= RE_GetRender(scene->id.name);
2436
2437         /* this is the basic trick to get the displayed float or char rect from render result */
2438         RE_AcquireResultImage(re, &rres);
2439         BKE_stamp_buf(scene, (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
2440         RE_ReleaseResultImage(re);
2441 }
2442
2443 static void do_render_seq(Render * re)
2444 {
2445         static int recurs_depth = 0;
2446         struct ImBuf *ibuf;
2447         RenderResult *rr = re->result;
2448         int cfra = re->r.cfra;
2449
2450         recurs_depth++;
2451
2452         ibuf= give_ibuf_seq(re->scene, rr->rectx, rr->recty, cfra, 0, 100.0);
2453
2454         recurs_depth--;
2455         
2456         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2457
2458         if(ibuf) {
2459                 if(ibuf->rect_float) {
2460                         if (!rr->rectf)
2461                                 rr->rectf= MEM_mallocN(4*sizeof(float)*rr->rectx*rr->recty, "render_seq rectf");
2462                         
2463                         memcpy(rr->rectf, ibuf->rect_float, 4*sizeof(float)*rr->rectx*rr->recty);
2464                         
2465                         /* TSK! Since sequence render doesn't free the *rr render result, the old rect32
2466                            can hang around when sequence render has rendered a 32 bits one before */
2467                         if(rr->rect32) {
2468                                 MEM_freeN(rr->rect32);
2469                                 rr->rect32= NULL;
2470                         }
2471                 }
2472                 else if(ibuf->rect) {
2473                         if (!rr->rect32)
2474                                 rr->rect32= MEM_mallocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2475
2476                         memcpy(rr->rect32, ibuf->rect, 4*rr->rectx*rr->recty);
2477
2478                         /* if (ibuf->zbuf) { */
2479                         /*      if (R.rectz) freeN(R.rectz); */
2480                         /*      R.rectz = BLI_dupallocN(ibuf->zbuf); */
2481                         /* } */
2482                 }
2483                 
2484                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
2485                         Editing * ed = re->scene->ed;
2486                         if (ed) {
2487                                 free_imbuf_seq(re->scene, &ed->seqbase, TRUE);
2488                         }
2489                 }
2490         }
2491         else {
2492                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
2493                 if (rr->rectf)
2494                         memset(rr->rectf, 0, 4*sizeof(float)*rr->rectx*rr->recty);
2495                 else if (rr->rect32)
2496                         memset(rr->rect32, 0, 4*rr->rectx*rr->recty);
2497                 else
2498                         rr->rect32= MEM_callocN(sizeof(int)*rr->rectx*rr->recty, "render_seq rect");
2499         }
2500
2501         BLI_rw_mutex_unlock(&re->resultmutex);
2502 }
2503
2504 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
2505
2506 /* main loop: doing sequence + fields + blur + 3d render + compositing */
2507 static void do_render_all_options(Render *re)
2508 {
2509         re->i.starttime= PIL_check_seconds_timer();
2510
2511         /* ensure no images are in memory from previous animated sequences */
2512         BKE_image_all_free_anim_ibufs(re->r.cfra);
2513         
2514         if((re->r.scemode & R_DOSEQ) && re->scene->ed && re->scene->ed->seqbase.first) {
2515                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
2516                 if(!re->test_break(re->tbh)) 
2517                         do_render_seq(re);
2518                 
2519                 re->stats_draw(re->sdh, &re->i);
2520                 re->display_draw(re->ddh, re->result, NULL);
2521         }
2522         else {
2523                 do_render_composite_fields_blur_3d(re);
2524         }
2525         
2526         /* for UI only */
2527         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2528         renderresult_add_names(re->result);
2529         BLI_rw_mutex_unlock(&re->resultmutex);
2530         
2531         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
2532         
2533         re->stats_draw(re->sdh, &re->i);
2534         
2535         /* stamp image info here */
2536         if((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
2537                 renderresult_stampinfo(re->scene);
2538                 re->display_draw(re->ddh, re->result, NULL);
2539         }
2540 }
2541
2542 static int is_rendering_allowed(Render *re)
2543 {
2544         SceneRenderLayer *srl;
2545         
2546         /* forbidden combinations */
2547         if(re->r.mode & R_PANORAMA) {
2548                 if(re->r.mode & R_BORDER) {
2549                         re->error(re->erh, "No border supported for Panorama");
2550                         return 0;
2551                 }
2552                 if(re->r.mode & R_ORTHO) {
2553                         re->error(re->erh, "No Ortho render possible for Panorama");
2554                         return 0;
2555                 }
2556         }
2557         
2558         if(re->r.mode & R_BORDER) {
2559                 if(re->r.border.xmax <= re->r.border.xmin || 
2560                    re->r.border.ymax <= re->r.border.ymin) {
2561                         re->error(re->erh, "No border area selected.");
2562                         return 0;
2563                 }
2564                 if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2565                         re->error(re->erh, "Border render and Buffer-save not supported yet");
2566                         return 0;
2567                 }
2568         }
2569         
2570         if(re->r.scemode & (R_EXR_TILE_FILE|R_FULL_SAMPLE)) {
2571                 char str[FILE_MAX];
2572                 
2573                 render_unique_exr_name(re, str, 0);
2574                 
2575                 if (BLI_is_writable(str)==0) {
2576                         re->error(re->erh, "Can not save render buffers, check the temp default path");
2577                         return 0;
2578                 }
2579                 
2580                 /* no osa + fullsample won't work... */
2581                 if(re->osa==0)
2582                         re->r.scemode &= ~R_FULL_SAMPLE;
2583                 
2584                 /* no fullsample and edge */
2585                 if((re->r.scemode & R_FULL_SAMPLE) && (re->r.mode & R_EDGE)) {
2586                         re->error(re->erh, "Full Sample doesn't support Edge Enhance");
2587                         return 0;
2588                 }
2589                 
2590         }
2591         else
2592                 re->r.scemode &= ~R_FULL_SAMPLE;        /* clear to be sure */
2593         
2594         if(re->r.scemode & R_DOCOMP) {
2595                 if(re->scene->use_nodes) {
2596                         bNodeTree *ntree= re->scene->nodetree;
2597                         bNode *node;
2598                 
2599                         if(ntree==NULL) {
2600                                 re->error(re->erh, "No Nodetree in Scene");
2601                                 return 0;
2602                         }
2603                         
2604                         for(node= ntree->nodes.first; node; node= node->next)
2605                                 if(node->type==CMP_NODE_COMPOSITE)
2606                                         break;
2607                         
2608                         
2609                         if(node==NULL) {
2610                                 re->error(re->erh, "No Render Output Node in Scene");
2611                                 return 0;
2612                         }
2613                 }
2614         }
2615         
2616         /* check valid camera, without camera render is OK (compo, seq) */
2617         if(re->scene->camera==NULL)
2618                 re->scene->camera= scene_find_camera(re->scene);
2619         
2620         if(!(re->r.scemode & (R_DOSEQ|R_DOCOMP))) {
2621                 if(re->scene->camera==NULL) {
2622                         re->error(re->erh, "No camera");
2623                         return 0;
2624                 }
2625         }
2626         
2627         /* layer flag tests */
2628         if(re->r.scemode & R_SINGLE_LAYER) {
2629                 srl= BLI_findlink(&re->scene->r.layers, re->r.actlay);
2630                 /* force layer to be enabled */
2631                 srl->layflag &= ~SCE_LAY_DISABLE;
2632         }
2633         
2634         for(srl= re->scene->r.layers.first; srl; srl= srl->next)
2635                 if(!(srl->layflag & SCE_LAY_DISABLE))
2636                         break;
2637         if(srl==NULL) {
2638                 re->error(re->erh, "All RenderLayers are disabled");
2639                 return 0;
2640         }
2641         
2642         /* renderer */
2643         if(!ELEM(re->r.renderer, R_INTERN, R_YAFRAY)) {
2644                 re->error(re->erh, "Unknown render engine set");
2645                 return 0;
2646         }
2647         return 1;
2648 }
2649
2650 static void update_physics_cache(Render *re, Scene *scene, int anim_init)
2651 {
2652         PTCacheBaker baker;
2653
2654         baker.scene = scene;
2655         baker.pid = NULL;
2656         baker.bake = 0;
2657         baker.render = 1;
2658         baker.anim_init = 1;
2659         baker.quick_step = 1;
2660         baker.break_test = re->test_break;
2661         baker.break_data = re->tbh;
2662         baker.progressbar = NULL;
2663
2664         BKE_ptcache_make_cache(&baker);
2665 }
2666 /* evaluating scene options for general Blender render */
2667 static int render_initialize_from_scene(Render *re, Scene *scene, int anim, int anim_init)
2668 {
2669         int winx, winy;
2670         rcti disprect;
2671         
2672         /* r.xsch and r.ysch has the actual view window size
2673                 r.border is the clipping rect */
2674         
2675         /* calculate actual render result and display size */
2676         winx= (scene->r.size*scene->r.xsch)/100;
2677         winy= (scene->r.size*scene->r.ysch)/100;
2678         
2679         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2680         if(scene->r.mode & R_BORDER) {
2681                 disprect.xmin= scene->r.border.xmin*winx;
2682                 disprect.xmax= scene->r.border.xmax*winx;
2683                 
2684                 disprect.ymin= scene->r.border.ymin*winy;
2685                 disprect.ymax= scene->r.border.ymax*winy;
2686         }
2687         else {
2688                 disprect.xmin= disprect.ymin= 0;
2689                 disprect.xmax= winx;
2690                 disprect.ymax= winy;
2691         }
2692         
2693         re->scene= scene;
2694         
2695         /* not too nice, but it survives anim-border render */
2696         if(anim) {
2697                 re->disprect= disprect;
2698                 return 1;
2699         }
2700         
2701         /* check all scenes involved */
2702         tag_scenes_for_render(re);
2703
2704         /*
2705          * Disabled completely for now,
2706          * can be later set as render profile option
2707          * and default for background render.
2708         */
2709         if(0) {
2710                 /* make sure dynamics are up to date */
2711                 update_physics_cache(re, scene, anim_init);
2712         }
2713         
2714         if(scene->r.scemode & R_SINGLE_LAYER)
2715                 push_render_result(re);
2716         
2717         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2718         if(!re->ok)  /* if an error was printed, abort */
2719                 return 0;
2720         
2721         /* initstate makes new result, have to send changed tags around */
2722         ntreeCompositTagRender(re->scene);
2723         
2724         if(!is_rendering_allowed(re))
2725                 return 0;
2726         
2727         re->display_init(re->dih, re->result);
2728         re->display_clear(re->dch, re->result);
2729         
2730         return 1;
2731 }
2732
2733 /* general Blender frame render call */
2734 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
2735 {
2736         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2737         G.rendering= 1;
2738         re->result_ok= 0;
2739         
2740         scene->r.cfra= frame;
2741         
2742         if(render_initialize_from_scene(re, scene, 0, 0)) {
2743                 do_render_all_options(re);
2744         }
2745         
2746         /* UGLY WARNING */
2747         G.rendering= 0;
2748         re->result_ok= 1;
2749 }
2750
2751 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
2752 {
2753         char name[FILE_MAX];
2754         RenderResult rres;
2755         
2756         RE_AcquireResultImage(re, &rres);
2757
2758         /* write movie or image */
2759         if(BKE_imtype_is_movie(scene->r.imtype)) {
2760                 int dofree = 0;
2761                 /* note; the way it gets 32 bits rects is weak... */
2762                 if(rres.rect32==NULL) {
2763                         rres.rect32= MEM_mapallocN(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
2764                         dofree = 1;
2765                 }
2766                 RE_ResultGet32(re, (unsigned int *)rres.rect32);
2767                 mh->append_movie(&re->r, scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
2768                 if(dofree) {
2769                         MEM_freeN(rres.rect32);
2770                 }
2771                 printf("Append frame %d", scene->r.cfra);
2772         } 
2773         else {
2774                 BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2775                 
2776                 if(re->r.imtype==R_MULTILAYER) {
2777                         if(re->result) {
2778                                 RE_WriteRenderResult(re->result, name, scene->r.quality);
2779                                 printf("Saved: %s", name);
2780                         }
2781                 }
2782                 else {
2783                         ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
2784                         int ok;
2785                         
2786                         /* if not exists, BKE_write_ibuf makes one */
2787                         ibuf->rect= (unsigned int *)rres.rect32;    
2788                         ibuf->rect_float= rres.rectf;
2789                         ibuf->zbuf_float= rres.rectz;
2790                         
2791                         /* float factor for random dither, imbuf takes care of it */
2792                         ibuf->dither= scene->r.dither_intensity;
2793                         /* gamma correct to sRGB color space */
2794                         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2795                                 ibuf->profile = IB_PROFILE_SRGB;
2796
2797                         ok= BKE_write_ibuf(scene, ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
2798                         
2799                         if(ok==0) {
2800                                 printf("Render error: cannot save %s\n", name);
2801                                 G.afbreek=1;
2802                         }
2803                         else printf("Saved: %s", name);
2804                         
2805                         /* optional preview images for exr */
2806                         if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
2807                                 if(BLI_testextensie(name, ".exr")) 
2808                                         name[strlen(name)-4]= 0;
2809                                 BKE_add_image_extension(scene, name, R_JPEG90);
2810                                 ibuf->depth= 24; 
2811                                 BKE_write_ibuf(scene, ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
2812                                 printf("\nSaved: %s", name);
2813                         }
2814                         
2815                                         /* imbuf knows which rects are not part of ibuf */
2816                         IMB_freeImBuf(ibuf);
2817                 }
2818         }
2819         
2820         RE_ReleaseResultImage(re);
2821
2822         BLI_timestr(re->i.lastframetime, name);
2823         printf(" Time: %s\n", name);
2824         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2825 }
2826
2827 /* saves images to disk */
2828 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra, int tfra)
2829 {
2830         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
2831         unsigned int lay;
2832         int cfrao= scene->r.cfra;
2833         int nfra;
2834         
2835         /* do not fully call for each frame, it initializes & pops output window */
2836         if(!render_initialize_from_scene(re, scene, 0, 1))
2837                 return;
2838         
2839         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2840         /* is also set by caller renderwin.c */
2841         G.rendering= 1;
2842         re->result_ok= 0;
2843         
2844         if(BKE_imtype_is_movie(scene->r.imtype))
2845                 mh->start_movie(scene, &re->r, re->rectx, re->recty);
2846         
2847         if (mh->get_next_frame) {
2848                 while (!(G.afbreek == 1)) {
2849                         int nf = mh->get_next_frame(&re->r);
2850                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2851                                 scene->r.cfra = re->r.cfra = nf;
2852                                 
2853                                 do_render_all_options(re);
2854
2855                                 if(re->test_break(re->tbh) == 0) {
2856                                         do_write_image_or_movie(re, scene, mh);
2857                                 }
2858                         } else {
2859                                 if(re->test_break(re->tbh))
2860                                         G.afbreek= 1;
2861                         }
2862                 }
2863         } else {
2864                 for(nfra= sfra, scene->r.cfra= sfra; scene->r.cfra<=efra; scene->r.cfra++) {
2865                         char name[FILE_MAX];
2866                         
2867                         /* only border now, todo: camera lens. (ton) */
2868                         render_initialize_from_scene(re, scene, 1, 0);
2869
2870                         if(nfra!=scene->r.cfra) {
2871                                 /*
2872                                  * Skip this frame, but update for physics and particles system.
2873                                  * From convertblender.c:
2874                                  * in localview, lamps are using normal layers, objects only local bits.
2875                                  */
2876                                 if(scene->lay & 0xFF000000)
2877                                         lay= scene->lay & 0xFF000000;
2878                                 else
2879                                         lay= scene->lay;
2880
2881                                 scene_update_for_newframe(scene, lay);
2882                                 continue;
2883                         }
2884                         else
2885                                 nfra+= tfra;
2886
2887                         /* Touch/NoOverwrite options are only valid for image's */
2888                         if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2889                                 if(scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2890                                         BKE_makepicstring(scene, name, scene->r.pic, scene->r.cfra, scene->r.imtype);
2891
2892                                 if(scene->r.mode & R_NO_OVERWRITE && BLI_exist(name)) {
2893                                         printf("skipping existing frame \"%s\"\n", name);
2894                                         continue;
2895                                 }
2896                                 if(scene->r.mode & R_TOUCH && !BLI_exist(name)) {
2897                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2898                                         BLI_touch(name);
2899                                 }
2900                         }
2901
2902                         re->r.cfra= scene->r.cfra;         /* weak.... */
2903                         
2904                         do_render_all_options(re);
2905                         
2906                         if(re->test_break(re->tbh) == 0)
2907                                 do_write_image_or_movie(re, scene, mh);
2908                         else
2909                                 G.afbreek= 1;
2910                 
2911                         if(G.afbreek==1) {
2912                                 /* remove touched file */
2913                                 if(BKE_imtype_is_movie(scene->r.imtype) == 0) {
2914                                         if (scene->r.mode & R_TOUCH && BLI_exist(name) && BLI_filepathsize(name) == 0) {
2915                                                 BLI_delete(name, 0, 0);
2916                                         }
2917                                 }
2918                                 
2919                                 break;
2920                         }
2921                 }
2922         }
2923         
2924         /* end movie */
2925         if(BKE_imtype_is_movie(scene->r.imtype))
2926                 mh->end_movie();
2927
2928         scene->r.cfra= cfrao;
2929         
2930         /* UGLY WARNING */
2931         G.rendering= 0;
2932         re->result_ok= 1;
2933 }
2934
2935 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2936
2937 /* only the temp file! */
2938 void RE_ReadRenderResult(Scene *scene, Scene *scenode)
2939 {
2940         Render *re;
2941         int winx, winy;
2942         rcti disprect;
2943         
2944         /* calculate actual render result and display size */
2945         winx= (scene->r.size*scene->r.xsch)/100;
2946         winy= (scene->r.size*scene->r.ysch)/100;
2947         
2948         /* only in movie case we render smaller part */
2949         if(scene->r.mode & R_BORDER) {
2950                 disprect.xmin= scene->r.border.xmin*winx;
2951                 disprect.xmax= scene->r.border.xmax*winx;
2952                 
2953                 disprect.ymin= scene->r.border.ymin*winy;
2954                 disprect.ymax= scene->r.border.ymax*winy;
2955         }
2956         else {
2957                 disprect.xmin= disprect.ymin= 0;
2958                 disprect.xmax= winx;
2959                 disprect.ymax= winy;
2960         }
2961         
2962         if(scenode)
2963                 scene= scenode;
2964         
2965         /* get render: it can be called from UI with draw callbacks */
2966         re= RE_GetRender(scene->id.name);
2967         if(re==NULL)
2968                 re= RE_NewRender(scene->id.name);
2969         RE_InitState(re, NULL, &scene->r, winx, winy, &disprect);
2970         re->scene= scene;
2971         
2972         read_render_result(re, 0);
2973 }
2974
2975 void RE_set_max_threads(int threads)
2976 {
2977         if (threads==0) {
2978                 commandline_threads = BLI_system_thread_count();
2979         } else if(threads>=1 && threads<=BLENDER_MAX_THREADS) {
2980                 commandline_threads= threads;
2981         } else {
2982                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2983         }
2984 }
2985
2986 void RE_init_threadcount(Render *re) 
2987 {
2988         if(commandline_threads >= 1) { /* only set as an arg in background mode */
2989                 re->r.threads= MIN2(commandline_threads, BLENDER_MAX_THREADS);
2990         } else if ((re->r.mode & R_FIXED_THREADS)==0 || commandline_threads == 0) { /* Automatic threads */
2991                 re->r.threads = BLI_system_thread_count();
2992         }
2993 }
2994
2995 /************************** External Engines ***************************/
2996
2997 RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w, int h)
2998 {
2999         Render *re= engine->re;
3000         RenderResult *result;
3001         rcti disprect;
3002
3003         /* ensure the coordinates are within the right limits */
3004         CLAMP(x, 0, re->result->rectx);
3005         CLAMP(y, 0, re->result->recty);
3006         CLAMP(w, 0, re->result->rectx);
3007         CLAMP(h, 0, re->result->recty);
3008
3009         if(x + w > re->result->rectx)
3010                 w= re->result->rectx - x;
3011         if(y + h > re->result->recty)
3012                 h= re->result->recty - y;
3013
3014         /* allocate a render result */
3015         disprect.xmin= x;
3016         disprect.xmax= x+w;
3017         disprect.ymin= y;
3018         disprect.ymax= y+h;
3019
3020         if(0) { // XXX (re->r.scemode & R_FULL_SAMPLE)) {
3021                 result= new_full_sample_buffers(re, &engine->fullresult, &disprect, 0);
3022         }
3023         else {
3024                 result= new_render_result(re, &disprect, 0, RR_USEMEM);
3025                 BLI_addtail(&engine->fullresult, result);
3026         }
3027
3028         return result;
3029 }
3030
3031 void RE_engine_update_result(RenderEngine *engine, RenderResult *result)
3032 {
3033         Render *re= engine->re;
3034
3035         if(result && render_display_draw_enabled(re)) {
3036                 result->renlay= result->layers.first; // weak
3037                 re->display_draw(re->ddh, result, NULL);
3038         }
3039 }
3040
3041 void RE_engine_end_result(RenderEngine *engine, RenderResult *result)
3042 {
3043         Render *re= engine->re;
3044
3045         if(!result)
3046                 return;
3047
3048         /* merge */
3049         if(re->result->exrhandle) {
3050                 RenderResult *rr, *rrpart;
3051                 
3052                 // XXX crashes, exr expects very particular part sizes
3053                 for(rr= re->result, rrpart= result; rr && rrpart; rr= rr->next, rrpart= rrpart->next)
3054                         save_render_result_tile(rr, rrpart);
3055         }
3056         else if(render_display_draw_enabled(re)) {
3057                 /* on break, don't merge in result for preview renders, looks nicer */
3058                 if(re->test_break(re->tbh) && (re->r.scemode & R_PREVIEWBUTS));
3059                 else merge_render_result(re->result, result);
3060         }
3061
3062         /* draw */
3063         if(!re->test_break(re->tbh) && render_display_draw_enabled(re)) {
3064                 result->renlay= result->layers.first; // weak
3065                 re->display_draw(re->ddh, result, NULL);
3066         }
3067
3068         /* free */
3069         free_render_result(&engine->fullresult, result);
3070 }
3071
3072 int RE_engine_test_break(RenderEngine *engine)
3073 {
3074         Render *re= engine->re;
3075
3076         return re->test_break(re->tbh);
3077 }
3078
3079 void RE_engine_update_stats(RenderEngine *engine, char *stats, char *info)
3080 {
3081         Render *re= engine->re;
3082
3083         re->i.statstr= stats;
3084         re->i.infostr= info;
3085         re->stats_draw(re->sdh, &re->i);
3086         re->i.infostr= NULL;
3087         re->i.statstr= NULL;