A couple of render improvements;
[blender.git] / source / blender / render / intern / source / pipeline.c
1 /**  
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. 
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2006 Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <math.h>
30 #include <limits.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #include "DNA_group_types.h"
35 #include "DNA_node_types.h"
36 #include "DNA_object_types.h"
37 #include "DNA_scene_types.h"
38
39 #include "BKE_global.h"
40 #include "BKE_image.h"
41 #include "BKE_node.h"
42 #include "BKE_scene.h"
43 #include "BKE_writeavi.h"       /* <------ should be replaced once with generic movie module */
44
45 #include "MEM_guardedalloc.h"
46
47 #include "BLI_arithb.h"
48 #include "BLI_blenlib.h"
49 #include "BLI_threads.h"
50
51 #include "PIL_time.h"
52 #include "IMB_imbuf.h"
53 #include "IMB_imbuf_types.h"
54
55 #include "intern/openexr/openexr_multi.h"
56
57 #include "RE_pipeline.h"
58 #include "radio.h"
59
60 #include "BSE_sequence.h"  /* <----------------- bad!!! */
61
62 /* internal */
63 #include "render_types.h"
64 #include "renderpipeline.h"
65 #include "renderdatabase.h"
66 #include "rendercore.h"
67 #include "envmap.h"
68 #include "initrender.h"
69 #include "shadbuf.h"
70 #include "zbuf.h"
71
72 /* render flow
73
74 1) Initialize state
75 - state data, tables
76 - movie/image file init
77 - everything that doesn't change during animation
78
79 2) Initialize data
80 - camera, world, matrices
81 - make render verts, faces, halos, strands
82 - everything can change per frame/field
83
84 3) Render Processor
85 - multiple layers
86 - tiles, rect, baking
87 - layers/tiles optionally to disk or directly in Render Result
88
89 4) Composit Render Result
90 - also read external files etc
91
92 5) Image Files
93 - save file or append in movie
94
95 */
96
97
98 /* ********* globals ******** */
99
100 /* here we store all renders */
101 static struct ListBase RenderList= {NULL, NULL};
102
103 /* hardcopy of current render, used while rendering for speed */
104 Render R;
105
106 //static SDL_mutex *exrtile_lock= NULL;
107
108 /* ********* alloc and free ******** */
109
110
111 static volatile int g_break= 0;
112 static int thread_break(void)
113 {
114         return g_break;
115 }
116
117 /* default callbacks, set in each new render */
118 static void result_nothing(RenderResult *rr) {}
119 static void result_rcti_nothing(RenderResult *rr, volatile struct rcti *rect) {}
120 static void stats_nothing(RenderStats *rs) {}
121 static void int_nothing(int val) {}
122 static int void_nothing(void) {return 0;}
123 static void print_error(char *str) {printf("ERROR: %s\n", str);}
124
125 static void stats_background(RenderStats *rs)
126 {
127         extern unsigned long mem_in_use;
128         float megs_used_memory= mem_in_use/(1024.0*1024.0);
129         char str[400], *spos= str;
130         
131         if(rs->convertdone) {
132                 
133                 spos+= sprintf(spos, "Fra:%d Mem:%.2fM ", G.scene->r.cfra, megs_used_memory);
134                 
135                 if(rs->infostr) {
136                         spos+= sprintf(spos, " | %s", rs->infostr);
137                 }
138                 else {
139                         if(rs->tothalo)
140                                 spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
141                         else 
142                                 spos+= sprintf(spos, "Sce: %s Ve:%d Fa:%d La:%d", G.scene->id.name+2, rs->totvert, rs->totface, rs->totlamp);
143                 }
144                 printf(str); printf("\n");
145         }       
146 }
147
148 static void free_render_result(RenderResult *res)
149 {
150         if(res==NULL) return;
151
152         while(res->layers.first) {
153                 RenderLayer *rl= res->layers.first;
154                 
155                 if(rl->rectf) MEM_freeT(rl->rectf);
156                 while(rl->passes.first) {
157                         RenderPass *rpass= rl->passes.first;
158                         if(rpass->rect) MEM_freeT(rpass->rect);
159                         BLI_remlink(&rl->passes, rpass);
160                         MEM_freeT(rpass);
161                 }
162                 BLI_remlink(&res->layers, rl);
163                 MEM_freeT(rl);
164         }
165         
166         if(res->rect32)
167                 MEM_freeT(res->rect32);
168         if(res->rectz)
169                 MEM_freeT(res->rectz);
170         if(res->rectf)
171                 MEM_freeT(res->rectf);
172         
173         MEM_freeT(res);
174 }
175
176 /* all layers except the active one get temporally pushed away */
177 static void push_render_result(Render *re)
178 {
179         re->pushedresult= re->result;
180         re->result= NULL;
181 }
182
183 /* if scemode is R_SINGLE_LAYER, at end of rendering, merge the both render results */
184 static void pop_render_result(Render *re)
185 {
186         
187         if(re->result==NULL) {
188                 printf("pop render result error; no current result!\n");
189                 return;
190         }
191         if(re->pushedresult) {
192                 if(re->pushedresult->rectx==re->result->rectx && re->pushedresult->recty==re->result->recty) {
193                         /* find which layer in pushedresult should be replaced */
194                         SceneRenderLayer *srl;
195                         RenderLayer *rlpush;
196                         RenderLayer *rl= re->result->layers.first;
197                         int nr;
198                         
199                         /* render result should be empty after this */
200                         BLI_remlink(&re->result->layers, rl);
201                         
202                         /* reconstruct render result layers */
203                         for(nr=0, srl= re->scene->r.layers.first; srl; srl= srl->next, nr++) {
204                                 if(nr==re->r.actlay)
205                                         BLI_addtail(&re->result->layers, rl);
206                                 else {
207                                         rlpush= RE_GetRenderLayer(re->pushedresult, srl->name);
208                                         if(rlpush) {
209                                                 BLI_remlink(&re->pushedresult->layers, rlpush);
210                                                 BLI_addtail(&re->result->layers, rlpush);
211                                         }
212                                 }
213                         }
214                 }
215                 
216                 free_render_result(re->pushedresult);
217                 re->pushedresult= NULL;
218         }
219 }
220
221
222 static char *get_pass_name(int passtype, int channel)
223 {
224         
225         if(passtype == SCE_PASS_COMBINED) {
226                 if(channel==0) return "Combined.R";
227                 else if(channel==1) return "Combined.G";
228                 else if(channel==2) return "Combined.B";
229                 else return "Combined.A";
230         }
231         if(passtype == SCE_PASS_Z)
232                 return "Z";
233         if(passtype == SCE_PASS_VECTOR) {
234                 if(channel==0) return "Vector.X";
235                 else if(channel==1) return "Vector.Y";
236                 else if(channel==2) return "Vector.Z";
237                 else return "Vector.W";
238         }
239         if(passtype == SCE_PASS_NORMAL) {
240                 if(channel==0) return "Normal.X";
241                 else if(channel==1) return "Normal.Y";
242                 else return "Normal.Z";
243         }
244         if(passtype == SCE_PASS_RGBA) {
245                 if(channel==0) return "Color.R";
246                 else if(channel==1) return "Color.G";
247                 else if(channel==2) return "Color.B";
248                 else return "Color.A";
249         }
250         if(passtype == SCE_PASS_DIFFUSE) {
251                 if(channel==0) return "Diffuse.R";
252                 else if(channel==1) return "Diffuse.G";
253                 else return "Diffuse.B";
254         }
255         if(passtype == SCE_PASS_SPEC) {
256                 if(channel==0) return "Spec.R";
257                 else if(channel==1) return "Spec.G";
258                 else return "Spec.B";
259         }
260         if(passtype == SCE_PASS_SHADOW) {
261                 if(channel==0) return "Shadow.R";
262                 else if(channel==1) return "Shadow.G";
263                 else return "Shadow.B";
264         }
265         if(passtype == SCE_PASS_AO) {
266                 if(channel==0) return "AO.R";
267                 else if(channel==1) return "AO.G";
268                 else return "AO.B";
269         }
270         if(passtype == SCE_PASS_RAY) {
271                 if(channel==0) return "Ray.R";
272                 else if(channel==1) return "Ray.G";
273                 else return "Ray.B";
274         }
275         return "Unknown";
276 }
277
278 static void render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, int passtype)
279 {
280         char *typestr= get_pass_name(passtype, 0);
281         RenderPass *rpass= MEM_callocT(sizeof(RenderPass), typestr);
282         int rectsize= rr->rectx*rr->recty*channels;
283         
284         BLI_addtail(&rl->passes, rpass);
285         rpass->passtype= passtype;
286         rpass->channels= channels;
287         
288         if(rr->exrhandle) {
289                 int a;
290                 for(a=0; a<channels; a++)
291                         IMB_exr_add_channel(rr->exrhandle, rl->name, get_pass_name(passtype, a));
292         }
293         else {
294                 if(passtype==SCE_PASS_VECTOR) {
295                         float *rect;
296                         int x;
297                         
298                         /* initialize to max speed */
299                         rect= rpass->rect= MEM_mapallocT(sizeof(float)*rectsize, typestr);
300                         for(x= rectsize-1; x>=0; x--)
301                                 rect[x]= PASS_VECTOR_MAX;
302                 }
303                 else
304                         rpass->rect= MEM_mapallocT(sizeof(float)*rectsize, typestr);
305         }
306 }
307
308 float *RE_RenderLayerGetPass(RenderLayer *rl, int passtype)
309 {
310         RenderPass *rpass;
311         
312         for(rpass=rl->passes.first; rpass; rpass= rpass->next)
313                 if(rpass->passtype== passtype)
314                         return rpass->rect;
315         return NULL;
316 }
317
318 RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
319 {
320         RenderLayer *rl;
321         
322         if(rr==NULL) return NULL;
323         
324         for(rl= rr->layers.first; rl; rl= rl->next)
325                 if(strncmp(rl->name, name, RE_MAXNAME)==0)
326                         return rl;
327         return NULL;
328 }
329
330 /* called by main render as well for parts */
331 /* will read info from Render *re to define layers */
332 /* called in threads */
333 /* re->winx,winy is coordinate space of entire image, partrct the part within */
334 static RenderResult *new_render_result(Render *re, rcti *partrct, int crop)
335 {
336         RenderResult *rr;
337         RenderLayer *rl;
338         SceneRenderLayer *srl;
339         int rectx, recty, nr;
340         
341         rectx= partrct->xmax - partrct->xmin;
342         recty= partrct->ymax - partrct->ymin;
343         
344         if(rectx<=0 || recty<=0)
345                 return NULL;
346         
347         rr= MEM_callocT(sizeof(RenderResult), "new render result");
348         rr->rectx= rectx;
349         rr->recty= recty;
350         /* crop is one or two extra pixels rendered for filtering, is used for merging and display too */
351         rr->crop= crop;
352         
353         /* tilerect is relative coordinates within render disprect. do not subtract crop yet */
354         rr->tilerect.xmin= partrct->xmin - re->disprect.xmin;
355         rr->tilerect.xmax= partrct->xmax - re->disprect.xmax;
356         rr->tilerect.ymin= partrct->ymin - re->disprect.ymin;
357         rr->tilerect.ymax= partrct->ymax - re->disprect.ymax;
358         
359         /* this flag needs cleared immediate after result was made */
360         if(re->flag & R_FILEBUFFER) {
361                 rr->exrhandle= IMB_exr_get_handle();
362         }
363         
364         /* check renderdata for amount of layers */
365         for(nr=0, srl= re->r.layers.first; srl; srl= srl->next, nr++) {
366                 
367                 if((re->r.scemode & R_SINGLE_LAYER) && nr!=re->r.actlay)
368                         continue;
369                 
370                 rl= MEM_callocT(sizeof(RenderLayer), "new render layer");
371                 BLI_addtail(&rr->layers, rl);
372                 
373                 strcpy(rl->name, srl->name);
374                 rl->lay= srl->lay;
375                 rl->layflag= srl->layflag;
376                 rl->passflag= srl->passflag;
377                 
378                 if(rr->exrhandle) {
379                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.R");
380                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.G");
381                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.B");
382                         IMB_exr_add_channel(rr->exrhandle, rl->name, "Combined.A");
383                 }
384                 else
385                         rl->rectf= MEM_mapallocT(rectx*recty*sizeof(float)*4, "Combined rgba");
386                 
387                 if(srl->passflag  & SCE_PASS_Z)
388                         render_layer_add_pass(rr, rl, 1, SCE_PASS_Z);
389                 if(srl->passflag  & SCE_PASS_VECTOR)
390                         render_layer_add_pass(rr, rl, 4, SCE_PASS_VECTOR);
391                 if(srl->passflag  & SCE_PASS_NORMAL)
392                         render_layer_add_pass(rr, rl, 3, SCE_PASS_NORMAL);
393                 if(srl->passflag  & SCE_PASS_RGBA)
394                         render_layer_add_pass(rr, rl, 4, SCE_PASS_RGBA);
395                 if(srl->passflag  & SCE_PASS_DIFFUSE)
396                         render_layer_add_pass(rr, rl, 3, SCE_PASS_DIFFUSE);
397                 if(srl->passflag  & SCE_PASS_SPEC)
398                         render_layer_add_pass(rr, rl, 3, SCE_PASS_SPEC);
399                 if(srl->passflag  & SCE_PASS_SHADOW)
400                         render_layer_add_pass(rr, rl, 3, SCE_PASS_SHADOW);
401                 if(srl->passflag  & SCE_PASS_AO)
402                         render_layer_add_pass(rr, rl, 3, SCE_PASS_AO);
403                 if(srl->passflag  & SCE_PASS_RAY)
404                         render_layer_add_pass(rr, rl, 3, SCE_PASS_RAY);
405                 
406         }
407         /* previewrender and envmap don't do layers, so we make a default one */
408         if(rr->layers.first==NULL) {
409                 rl= MEM_callocT(sizeof(RenderLayer), "new render layer");
410                 BLI_addtail(&rr->layers, rl);
411                 
412                 rl->rectf= MEM_mapallocT(rectx*recty*sizeof(float)*4, "prev/env float rgba");
413                 
414                 /* note, this has to be in sync with scene.c */
415                 rl->lay= (1<<20) -1;
416                 rl->layflag= 0x7FFF;    /* solid ztra halo strand */
417                 rl->passflag= SCE_PASS_COMBINED;
418                 
419                 re->r.actlay= 0;
420         }
421         
422         return rr;
423 }
424
425 static int render_result_needs_vector(Render *re)
426 {
427         if(re->r.scemode & R_DOCOMP) {
428                 RenderLayer *rl;
429         
430                 for(rl= re->result->layers.first; rl; rl= rl->next)
431                         if(rl->passflag & SCE_PASS_VECTOR)
432                                 return 1;
433         }
434         return 0;
435 }
436
437 static void do_merge_tile(RenderResult *rr, RenderResult *rrpart, float *target, float *tile, int pixsize)
438 {
439         int y, ofs, copylen, tilex, tiley;
440         
441         copylen= tilex= rrpart->rectx;
442         tiley= rrpart->recty;
443         
444         if(rrpart->crop) {      /* filters add pixel extra */
445                 tile+= pixsize*(rrpart->crop + rrpart->crop*tilex);
446                 
447                 copylen= tilex - 2*rrpart->crop;
448                 tiley -= 2*rrpart->crop;
449                 
450                 ofs= (rrpart->tilerect.ymin + rrpart->crop)*rr->rectx + (rrpart->tilerect.xmin+rrpart->crop);
451                 target+= pixsize*ofs;
452         }
453         else {
454                 ofs= (rrpart->tilerect.ymin*rr->rectx + rrpart->tilerect.xmin);
455                 target+= pixsize*ofs;
456         }
457
458         copylen *= sizeof(float)*pixsize;
459         tilex *= pixsize;
460         ofs= pixsize*rr->rectx;
461
462         for(y=0; y<tiley; y++) {
463                 memcpy(target, tile, copylen);
464                 target+= ofs;
465                 tile+= tilex;
466         }
467 }
468
469 /* used when rendering to a full buffer, or when reading the exr part-layer-pass file */
470 /* no test happens here if it fits... we also assume layers are in sync */
471 /* is used within threads */
472 static void merge_render_result(RenderResult *rr, RenderResult *rrpart)
473 {
474         RenderLayer *rl, *rlp;
475         RenderPass *rpass, *rpassp;
476         
477         for(rl= rr->layers.first, rlp= rrpart->layers.first; rl && rlp; rl= rl->next, rlp= rlp->next) {
478                 
479                 /* combined */
480                 if(rl->rectf && rlp->rectf)
481                         do_merge_tile(rr, rrpart, rl->rectf, rlp->rectf, 4);
482                 
483                 /* passes are allocated in sync */
484                 for(rpass= rl->passes.first, rpassp= rlp->passes.first; rpass && rpassp; rpass= rpass->next, rpassp= rpassp->next) {
485                         do_merge_tile(rr, rrpart, rpass->rect, rpassp->rect, rpass->channels);
486                 }
487         }
488 }
489
490
491 static void save_render_result_tile(Render *re, RenderPart *pa)
492 {
493         RenderResult *rrpart= pa->result;
494         RenderLayer *rlp;
495         RenderPass *rpassp;
496         int offs, partx, party;
497         
498 //      if(exrtile_lock) SDL_mutexP(exrtile_lock);
499         
500         for(rlp= rrpart->layers.first; rlp; rlp= rlp->next) {
501                 
502                 if(rrpart->crop) {      /* filters add pixel extra */
503                         offs= (rrpart->crop + rrpart->crop*rrpart->rectx);
504                 }
505                 else {
506                         offs= 0;
507                 }
508                 
509                 /* combined */
510                 if(rlp->rectf) {
511                         int a, xstride= 4;
512                         for(a=0; a<xstride; a++)
513                                 IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(SCE_PASS_COMBINED, a), 
514                                                                 xstride, xstride*pa->rectx, rlp->rectf+a + xstride*offs);
515                 }
516                 
517                 /* passes are allocated in sync */
518                 for(rpassp= rlp->passes.first; rpassp; rpassp= rpassp->next) {
519                         int a, xstride= rpassp->channels;
520                         for(a=0; a<xstride; a++)
521                                 IMB_exr_set_channel(re->result->exrhandle, rlp->name, get_pass_name(rpassp->passtype, a), 
522                                                                         xstride, xstride*pa->rectx, rpassp->rect+a + xstride*offs);
523                 }
524                 
525         }
526
527         party= rrpart->tilerect.ymin + rrpart->crop;
528         partx= rrpart->tilerect.xmin + rrpart->crop;
529
530         IMB_exrtile_write_channels(re->result->exrhandle, partx, party);
531
532 //      if(exrtile_lock) SDL_mutexV(exrtile_lock);
533
534 }
535
536 static void read_render_result(Render *re)
537 {
538         RenderLayer *rl;
539         RenderPass *rpass;
540         void *exrhandle= IMB_exr_get_handle();
541         int rectx, recty;
542         
543         free_render_result(re->result);
544         re->result= new_render_result(re, &re->disprect, 0);
545
546         IMB_exr_begin_read(exrhandle, "/tmp/render.exr", &rectx, &recty);
547         if(rectx!=re->result->rectx || recty!=re->result->recty) {
548                 printf("error in reading render result\n");
549         }
550         else {
551                 for(rl= re->result->layers.first; rl; rl= rl->next) {
552                         
553                         /* combined */
554                         if(rl->rectf) {
555                                 int a, xstride= 4;
556                                 for(a=0; a<xstride; a++)
557                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(SCE_PASS_COMBINED, a), 
558                                                                                 xstride, xstride*rectx, rl->rectf+a);
559                         }
560                         
561                         /* passes are allocated in sync */
562                         for(rpass= rl->passes.first; rpass; rpass= rpass->next) {
563                                 int a, xstride= rpass->channels;
564                                 for(a=0; a<xstride; a++)
565                                         IMB_exr_set_channel(exrhandle, rl->name, get_pass_name(rpass->passtype, a), 
566                                                                                 xstride, xstride*rectx, rpass->rect+a);
567                         }
568                         
569                 }
570                 printf("before read\n");
571                 IMB_exr_read_channels(exrhandle);
572                 printf("after read\n");
573         }
574         
575         IMB_exr_close(exrhandle);
576 }
577
578 /* *************************************************** */
579
580 Render *RE_GetRender(const char *name)
581 {
582         Render *re;
583         
584         /* search for existing renders */
585         for(re= RenderList.first; re; re= re->next) {
586                 if(strncmp(re->name, name, RE_MAXNAME)==0) {
587                         break;
588                 }
589         }
590         return re;
591 }
592
593 /* if you want to know exactly what has been done */
594 RenderResult *RE_GetResult(Render *re)
595 {
596         if(re)
597                 return re->result;
598         return NULL;
599 }
600
601 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
602 {
603         RenderLayer *rl= BLI_findlink(&rr->layers, re->r.actlay);
604         
605         if(rl) 
606                 return rl;
607         else 
608                 return rr->layers.first;
609 }
610
611
612 /* fill provided result struct with what's currently active or done */
613 void RE_GetResultImage(Render *re, RenderResult *rr)
614 {
615         memset(rr, 0, sizeof(RenderResult));
616
617         if(re && re->result) {
618                 RenderLayer *rl;
619                 
620                 rr->rectx= re->result->rectx;
621                 rr->recty= re->result->recty;
622                 
623                 rr->rectf= re->result->rectf;
624                 rr->rectz= re->result->rectz;
625                 rr->rect32= re->result->rect32;
626                 
627                 /* active layer */
628                 rl= render_get_active_layer(re, re->result);
629
630                 if(rl) {
631                         if(rr->rectf==NULL)
632                                 rr->rectf= rl->rectf;
633                         if(rr->rectz==NULL)
634                                 rr->rectz= RE_RenderLayerGetPass(rl, SCE_PASS_Z);       
635                 }
636         }
637 }
638
639 #define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val))
640 /* caller is responsible for allocating rect in correct size! */
641 void RE_ResultGet32(Render *re, unsigned int *rect)
642 {
643         RenderResult rres;
644         
645         RE_GetResultImage(re, &rres);
646         if(rres.rect32) 
647                 memcpy(rect, rres.rect32, sizeof(int)*rres.rectx*rres.recty);
648         else if(rres.rectf) {
649                 float *fp= rres.rectf;
650                 int tot= rres.rectx*rres.recty;
651                 char *cp= (char *)rect;
652                 
653                 for(;tot>0; tot--, cp+=4, fp+=4) {
654                         cp[0] = FTOCHAR(fp[0]);
655                         cp[1] = FTOCHAR(fp[1]);
656                         cp[2] = FTOCHAR(fp[2]);
657                         cp[3] = FTOCHAR(fp[3]);
658                 }
659         }
660         else
661                 /* else fill with black */
662                 memset(rect, 0, sizeof(int)*re->rectx*re->recty);
663 }
664
665
666 RenderStats *RE_GetStats(Render *re)
667 {
668         return &re->i;
669 }
670
671 Render *RE_NewRender(const char *name)
672 {
673         Render *re;
674         
675         /* only one render per name exists */
676         re= RE_GetRender(name);
677         if(re)
678                 return re;
679         
680         /* new render data struct */
681         re= MEM_callocT(sizeof(Render), "new render");
682         BLI_addtail(&RenderList, re);
683         strncpy(re->name, name, RE_MAXNAME);
684         
685         /* set default empty callbacks */
686         re->display_init= result_nothing;
687         re->display_clear= result_nothing;
688         re->display_draw= result_rcti_nothing;
689         re->timecursor= int_nothing;
690         re->test_break= void_nothing;
691         re->test_return= void_nothing;
692         re->error= print_error;
693         if(G.background)
694                 re->stats_draw= stats_background;
695         else
696                 re->stats_draw= stats_nothing;
697         
698         /* init some variables */
699         re->ycor= 1.0f;
700         
701         return re;
702 }
703
704 /* only call this while you know it will remove the link too */
705 void RE_FreeRender(Render *re)
706 {
707         
708         free_renderdata_tables(re);
709         free_sample_tables(re);
710         
711         free_render_result(re->result);
712         free_render_result(re->pushedresult);
713         
714         BLI_remlink(&RenderList, re);
715         MEM_freeT(re);
716 }
717
718 /* exit blender */
719 void RE_FreeAllRender(void)
720 {
721         while(RenderList.first) {
722                 RE_FreeRender(RenderList.first);
723         }
724 }
725
726 /* ********* initialize state ******** */
727
728
729 /* what doesn't change during entire render sequence */
730 /* disprect is optional, if NULL it assumes full window render */
731 void RE_InitState(Render *re, RenderData *rd, int winx, int winy, rcti *disprect)
732 {
733         re->ok= TRUE;   /* maybe flag */
734         
735         re->i.starttime= PIL_check_seconds_timer();
736         re->r= *rd;             /* hardcopy */
737         
738         re->winx= winx;
739         re->winy= winy;
740         if(disprect) {
741                 re->disprect= *disprect;
742                 re->rectx= disprect->xmax-disprect->xmin;
743                 re->recty= disprect->ymax-disprect->ymin;
744         }
745         else {
746                 re->disprect.xmin= re->disprect.xmax= 0;
747                 re->disprect.xmax= winx;
748                 re->disprect.ymax= winy;
749                 re->rectx= winx;
750                 re->recty= winy;
751         }
752         
753         if(re->rectx < 2 || re->recty < 2) {
754                 re->error("Image too small");
755                 re->ok= 0;
756         }
757         else {
758                 /* check state variables, osa? */
759                 if(re->r.mode & (R_OSA|R_MBLUR)) {
760                         re->osa= re->r.osa;
761                         if(re->osa>16) re->osa= 16;
762                 }
763                 else re->osa= 0;
764                 
765                 /* always call, checks for gamma, gamma tables and jitter too */
766                 make_sample_tables(re); 
767                 
768                 free_render_result(re->result);
769                 re->result= new_render_result(re, &re->disprect, 0);
770         }
771 }
772
773 void RE_SetDispRect (struct Render *re, rcti *disprect)
774 {
775         re->disprect= *disprect;
776         re->rectx= disprect->xmax-disprect->xmin;
777         re->recty= disprect->ymax-disprect->ymin;
778         
779         /* initialize render result */
780         free_render_result(re->result);
781         re->result= new_render_result(re, &re->disprect, 0);
782 }
783
784 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
785 {
786         /* re->ok flag? */
787         
788         re->viewplane= *viewplane;
789         re->clipsta= clipsta;
790         re->clipend= clipend;
791
792         i_window(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
793 }
794
795 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
796 {
797         /* re->ok flag? */
798         
799         re->viewplane= *viewplane;
800         re->clipsta= clipsta;
801         re->clipend= clipend;
802         re->r.mode |= R_ORTHO;
803
804         i_ortho(re->viewplane.xmin, re->viewplane.xmax, re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend, re->winmat);
805 }
806
807 void RE_SetView(Render *re, float mat[][4])
808 {
809         /* re->ok flag? */
810         Mat4CpyMat4(re->viewmat, mat);
811         Mat4Invert(re->viewinv, re->viewmat);
812 }
813
814 /* image and movie output has to move to either imbuf or kernel */
815 void RE_display_init_cb(Render *re, void (*f)(RenderResult *rr))
816 {
817         re->display_init= f;
818 }
819 void RE_display_clear_cb(Render *re, void (*f)(RenderResult *rr))
820 {
821         re->display_clear= f;
822 }
823 void RE_display_draw_cb(Render *re, void (*f)(RenderResult *rr, volatile rcti *rect))
824 {
825         re->display_draw= f;
826 }
827
828 void RE_stats_draw_cb(Render *re, void (*f)(RenderStats *rs))
829 {
830         re->stats_draw= f;
831 }
832 void RE_timecursor_cb(Render *re, void (*f)(int))
833 {
834         re->timecursor= f;
835 }
836
837 void RE_test_break_cb(Render *re, int (*f)(void))
838 {
839         re->test_break= f;
840 }
841 void RE_test_return_cb(Render *re, int (*f)(void))
842 {
843         re->test_return= f;
844 }
845 void RE_error_cb(Render *re, void (*f)(char *str))
846 {
847         re->error= f;
848 }
849
850
851 /* ********* add object data (later) ******** */
852
853 /* object is considered fully prepared on correct time etc */
854 /* includes lights */
855 void RE_AddObject(Render *re, Object *ob)
856 {
857         
858 }
859
860 /* *************************************** */
861
862 static void *do_part_thread(void *pa_v)
863 {
864         RenderPart *pa= pa_v;
865         
866         /* need to return nicely all parts on esc */
867         if(R.test_break()==0) {
868                 
869                 pa->result= new_render_result(&R, &pa->disprect, pa->crop);
870                 
871                 if(R.osa)
872                         zbufshadeDA_tile(pa);
873                 else
874                         zbufshade_tile(pa);
875                 
876                 /* merge too on break! */
877                 if(R.result->exrhandle)
878                         save_render_result_tile(&R, pa);
879                 else
880                         merge_render_result(R.result, pa->result);
881         }
882         
883         pa->ready= 1;
884         
885         return NULL;
886 }
887
888 /* returns with render result filled, not threaded */
889 static void render_tile_processor(Render *re, int firsttile)
890 {
891         RenderPart *pa;
892         
893         if(re->test_break())
894                 return;
895         
896         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
897         re->stats_draw(&re->i);
898         re->i.starttime= PIL_check_seconds_timer();
899  
900         if(re->result==NULL)
901                 return;
902         
903         initparts(re);
904         
905         /* assuming no new data gets added to dbase... */
906         R= *re;
907         
908         for(pa= re->parts.first; pa; pa= pa->next) {
909                 if(firsttile) {
910                         re->i.partsdone++;      /* was reset in initparts */
911                         firsttile--;
912                 }
913                 else {
914                         do_part_thread(pa);
915                         
916                         if(pa->result) {
917                                 if(!re->test_break()) {
918                                         re->display_draw(pa->result, NULL);
919                                         
920                                         re->i.partsdone++;
921                                 }
922                                 free_render_result(pa->result);
923                                 pa->result= NULL;
924                         }               
925                         if(re->test_break())
926                                 break;
927                 }
928         }
929         
930         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
931         re->stats_draw(&re->i);
932
933         freeparts(re);
934 }
935
936 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
937 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
938 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
939 float panorama_pixel_rot(Render *re)
940 {
941         float psize, phi, xfac;
942         
943         /* size of 1 pixel mapped to viewplane coords */
944         psize= (re->viewplane.xmax-re->viewplane.xmin)/(float)re->winx;
945         /* angle of a pixel */
946         phi= atan(psize/re->clipsta);
947         
948         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
949         xfac= ((re->viewplane.xmax-re->viewplane.xmin))/(float)re->xparts;
950         xfac= atan(0.5f*xfac/re->clipsta); 
951         /* and how much the same viewplane angle is wrapped */
952         psize= 0.5f*phi*((float)re->partx);
953         
954         /* the ratio applied to final per-pixel angle */
955         phi*= xfac/psize;
956         
957         return phi;
958 }
959
960 /* call when all parts stopped rendering, to find the next Y slice */
961 /* if slice found, it rotates the dbase */
962 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
963 {
964         RenderPart *pa, *best= NULL;
965         
966         *minx= re->winx;
967         
968         /* most left part of the non-rendering parts */
969         for(pa= re->parts.first; pa; pa= pa->next) {
970                 if(pa->ready==0 && pa->nr==0) {
971                         if(pa->disprect.xmin < *minx) {
972                                 best= pa;
973                                 *minx= pa->disprect.xmin;
974                         }
975                 }
976         }
977                         
978         if(best) {
979                 float phi= panorama_pixel_rot(re);
980
981                 R.panodxp= (re->winx - (best->disprect.xmin + best->disprect.xmax) )/2;
982                 R.panodxv= ((viewplane->xmax-viewplane->xmin)*R.panodxp)/(float)R.winx;
983                 
984                 /* shift viewplane */
985                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
986                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
987                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
988                 Mat4CpyMat4(R.winmat, re->winmat);
989                 
990                 /* rotate database according to part coordinates */
991                 project_renderdata(re, projectverto, 1, -R.panodxp*phi);
992                 R.panosi= sin(R.panodxp*phi);
993                 R.panoco= cos(R.panodxp*phi);
994         }
995         return best;
996 }
997
998 static RenderPart *find_next_part(Render *re, int minx)
999 {
1000         RenderPart *pa, *best= NULL;
1001         int centx=re->winx/2, centy=re->winy/2, tot=1;
1002         int mindist, distx, disty;
1003         
1004         /* find center of rendered parts, image center counts for 1 too */
1005         for(pa= re->parts.first; pa; pa= pa->next) {
1006                 if(pa->ready) {
1007                         centx+= (pa->disprect.xmin+pa->disprect.xmax)/2;
1008                         centy+= (pa->disprect.ymin+pa->disprect.ymax)/2;
1009                         tot++;
1010                 }
1011         }
1012         centx/=tot;
1013         centy/=tot;
1014         
1015         /* closest of the non-rendering parts */
1016         mindist= re->winx*re->winy;
1017         for(pa= re->parts.first; pa; pa= pa->next) {
1018                 if(pa->ready==0 && pa->nr==0) {
1019                         distx= centx - (pa->disprect.xmin+pa->disprect.xmax)/2;
1020                         disty= centy - (pa->disprect.ymin+pa->disprect.ymax)/2;
1021                         distx= (int)sqrt(distx*distx + disty*disty);
1022                         if(distx<mindist) {
1023                                 if(re->r.mode & R_PANORAMA) {
1024                                         if(pa->disprect.xmin==minx) {
1025                                                 best= pa;
1026                                                 mindist= distx;
1027                                         }
1028                                 }
1029                                 else {
1030                                         best= pa;
1031                                         mindist= distx;
1032                                 }
1033                         }
1034                 }
1035         }
1036         return best;
1037 }
1038
1039 static void print_part_stats(Render *re, RenderPart *pa)
1040 {
1041         char str[64];
1042         
1043         sprintf(str, "Part %d-%d", pa->nr, re->i.totpart);
1044         re->i.infostr= str;
1045         re->stats_draw(&re->i);
1046         re->i.infostr= NULL;
1047 }
1048
1049 static void threaded_tile_processor(Render *re)
1050 {
1051         ListBase threads;
1052         RenderPart *pa, *nextpa;
1053         RenderResult *rr= re->result;
1054         rctf viewplane= re->viewplane;
1055         int maxthreads, rendering=1, counter= 1, drawtimer=0, hasdrawn, minx;
1056         
1057         if(rr==NULL)
1058                 return;
1059         if(re->test_break())
1060                 return;
1061         
1062         if(rr->exrhandle) {
1063                 IMB_exrtile_begin_write(rr->exrhandle, "/tmp/render.exr", rr->rectx, rr->recty, rr->rectx/re->xparts, rr->recty/re->yparts);
1064 //              exrtile_lock = SDL_CreateMutex();
1065         }
1066         
1067         if(re->r.mode & R_THREADS) maxthreads= 2;
1068         else maxthreads= 1;
1069         
1070         initparts(re);
1071         BLI_init_threads(&threads, do_part_thread, maxthreads);
1072         
1073         /* assuming no new data gets added to dbase... */
1074         R= *re;
1075         
1076         /* set threadsafe break */
1077         R.test_break= thread_break;
1078         
1079         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
1080         if(re->r.mode & R_PANORAMA)
1081                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1082         else
1083                 nextpa= find_next_part(re, 0);
1084         
1085         while(rendering) {
1086                 
1087                 if(re->test_break())
1088                         PIL_sleep_ms(50);
1089                 else if(nextpa && BLI_available_threads(&threads)) {
1090                         drawtimer= 0;
1091                         nextpa->nr= counter++;  /* for nicest part, and for stats */
1092                         nextpa->thread= BLI_available_thread_index(&threads);   /* sample index */
1093                         BLI_insert_thread(&threads, nextpa);
1094
1095                         nextpa= find_next_part(re, minx);
1096                 }
1097                 else if(re->r.mode & R_PANORAMA) {
1098                         if(nextpa==NULL && BLI_available_threads(&threads)==maxthreads)
1099                                 nextpa= find_next_pano_slice(re, &minx, &viewplane);
1100                         else {
1101                                 PIL_sleep_ms(50);
1102                                 drawtimer++;
1103                         }
1104                 }
1105                 else {
1106                         PIL_sleep_ms(50);
1107                         drawtimer++;
1108                 }
1109                 
1110                 /* check for ready ones to display, and if we need to continue */
1111                 rendering= 0;
1112                 hasdrawn= 0;
1113                 for(pa= re->parts.first; pa; pa= pa->next) {
1114                         if(pa->ready) {
1115                                 if(pa->result) {
1116                                         BLI_remove_thread(&threads, pa);
1117
1118                                         re->display_draw(pa->result, NULL);
1119                                         print_part_stats(re, pa);
1120                                         
1121                                         free_render_result(pa->result);
1122                                         pa->result= NULL;
1123                                         re->i.partsdone++;
1124                                         hasdrawn= 1;
1125                                 }
1126                         }
1127                         else {
1128                                 rendering= 1;
1129                                 if(pa->nr && pa->result && drawtimer>20) {
1130                                         re->display_draw(pa->result, &pa->result->renrect);
1131                                         hasdrawn= 1;
1132                                 }
1133                         }
1134                 }
1135                 if(hasdrawn)
1136                         drawtimer= 0;
1137
1138                 /* on break, wait for all slots to get freed */
1139                 if( (g_break=re->test_break()) && BLI_available_threads(&threads)==maxthreads)
1140                         rendering= 0;
1141                 
1142         }
1143         
1144         if(rr->exrhandle) {
1145 //              if(exrtile_lock) SDL_DestroyMutex(exrtile_lock); 
1146                 IMB_exr_close(rr->exrhandle);
1147                 read_render_result(re);
1148         }
1149         
1150         /* unset threadsafety */
1151         g_break= 0;
1152         
1153         BLI_end_threads(&threads);
1154         freeparts(re);
1155 }
1156
1157 /* currently only called by preview renders */
1158 void RE_TileProcessor(Render *re, int firsttile)
1159 {
1160         if(0) 
1161                 threaded_tile_processor(re);
1162         else
1163                 render_tile_processor(re, firsttile);   
1164 }
1165
1166
1167 /* ************  This part uses API, for rendering Blender scenes ********** */
1168
1169 void render_one_frame(Render *re)
1170 {
1171         
1172 //      re->cfra= cfra; /* <- unused! */
1173         
1174         /* make render verts/faces/halos/lamps */
1175         if(render_result_needs_vector(re))
1176                 RE_Database_FromScene_Vectors(re, re->scene);
1177         else
1178            RE_Database_FromScene(re, re->scene, 1);
1179         
1180         threaded_tile_processor(re);
1181         
1182         /* free all render verts etc */
1183         RE_Database_Free(re);
1184 }
1185
1186 #if 0
1187 /* accumulates osa frames */
1188 static void do_render_blurred(Render *re, float frame)
1189 {
1190         
1191 }
1192
1193 /* interleaves 2 frames */
1194 static void do_render_fields(Render *re)
1195 {
1196         
1197 }
1198 #endif
1199
1200 /* within context of current Render *re, render another scene.
1201    it uses current render image size and disprect, but doesn't execute composite
1202 */
1203 void RE_RenderScene(Render *re, Scene *sce, int cfra)
1204 {
1205         Render *resc= RE_NewRender(sce->id.name);
1206         
1207         sce->r.cfra= cfra;
1208         
1209         /* makes render result etc */
1210         RE_InitState(resc, &sce->r, re->winx, re->winy, &re->disprect);
1211         
1212         /* this to enable this scene to create speed vectors */
1213         resc->r.scemode |= R_DOCOMP;
1214         
1215         /* now use renderdata and camera to set viewplane */
1216         if(sce->camera==NULL) return;
1217         RE_SetCamera(resc, sce->camera);
1218         
1219         /* still unsure entity this... */
1220         resc->scene= sce;
1221         
1222         /* ensure scene has depsgraph, base flags etc OK. Warning... also sets G.scene */
1223         set_scene_bg(sce);
1224
1225         /* copy callbacks */
1226         resc->display_draw= re->display_draw;
1227         resc->test_break= re->test_break;
1228         resc->stats_draw= re->stats_draw;
1229         
1230         if(resc->r.mode & R_FIELDS)
1231                 printf("No field render yet...\n"); //do_render_fields(resc);
1232         else if(resc->r.mode & R_MBLUR)
1233                 printf("No mblur render yet...\n"); //do_render_blurred(resc, resc->r.cfra);
1234         //else
1235         render_one_frame(resc);
1236
1237 }
1238
1239 static void ntree_render_scenes(Render *re)
1240 {
1241         bNode *node;
1242         int cfra= re->scene->r.cfra;
1243         
1244         if(re->scene->nodetree==NULL) return;
1245         
1246         /* check for render-result nodes using other scenes, we tag them LIB_DOIT */
1247         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1248                 if(node->type==CMP_NODE_R_RESULT) {
1249                         if(node->id) {
1250                                 if(node->id != (ID *)re->scene)
1251                                         node->id->flag |= LIB_DOIT;
1252                                 else
1253                                         node->id->flag &= ~LIB_DOIT;
1254                         }
1255                 }
1256         }
1257         
1258         /* now foreach render-result node tagged we do a full render */
1259         /* results are stored in a way compisitor will find it */
1260         for(node= re->scene->nodetree->nodes.first; node; node= node->next) {
1261                 if(node->type==CMP_NODE_R_RESULT) {
1262                         if(node->id && node->id != (ID *)re->scene) {
1263                                 if(node->id->flag & LIB_DOIT) {
1264                                         RE_RenderScene(re, (Scene *)node->id, cfra);
1265                                         node->id->flag &= ~LIB_DOIT;
1266                                 }
1267                         }
1268                 }
1269         }
1270         
1271         /* still the global... */
1272         if(G.scene!=re->scene)
1273                 set_scene_bg(re->scene);
1274         
1275 }
1276
1277 /* helper call to detect if theres a render-result node */
1278 int composite_needs_render(Scene *sce)
1279 {
1280         bNodeTree *ntree= sce->nodetree;
1281         bNode *node;
1282         
1283         if(ntree==NULL) return 1;
1284         if(sce->use_nodes==0) return 1;
1285
1286         for(node= ntree->nodes.first; node; node= node->next) {
1287                 if(node->type==CMP_NODE_R_RESULT)
1288                         if(node->id==NULL || node->id!=&sce->id)
1289                                 return 1;
1290         }
1291         return 0;
1292 }
1293
1294 /* bad call... need to think over proper method still */
1295 static void render_composit_stats(char *str)
1296 {
1297         R.i.infostr= str;
1298         R.stats_draw(&R.i);
1299         R.i.infostr= NULL;
1300 }
1301
1302 static void do_render_final(Render *re)
1303 {
1304         /* we set start time here, for main Blender loops */
1305         re->i.starttime= PIL_check_seconds_timer();
1306
1307         if(re->r.scemode & R_DOSEQ) {
1308                 if (!re->result->rect32) {
1309                         re->result->rect32= MEM_callocT(sizeof(int)*re->rectx*re->recty, "do_render_final rectot");
1310                 }
1311                 if(!re->test_break()) 
1312                         do_render_seq(re->result, re->r.cfra);
1313         }
1314         else {
1315                 bNodeTree *ntree= re->scene->nodetree;
1316                 
1317                 if(composite_needs_render(re->scene)) {
1318                         /* save memory... free all cached images */
1319                         ntreeFreeCache(ntree);
1320                         
1321                         /* now use renderdata and camera to set viewplane */
1322                         RE_SetCamera(re, re->scene->camera);
1323                         
1324                         if(re->r.mode & R_FIELDS)
1325                                 printf("No field render yet...\n"); //do_render_fields(resc);
1326                         else if(re->r.mode & R_MBLUR)
1327                                 printf("No mblur render yet...\n"); //do_render_blurred(resc, resc->r.cfra);
1328                                                                                                         //else
1329                         render_one_frame(re);
1330                 }
1331                 
1332                 /* swap render result */
1333                 if(re->r.scemode & R_SINGLE_LAYER)
1334                         pop_render_result(re);
1335                 
1336                 if(!re->test_break() && ntree) {
1337                         ntreeCompositTagRender(ntree);
1338                         ntreeCompositTagAnimated(ntree);
1339                         
1340                         if(re->r.scemode & R_DOCOMP) {
1341                                 /* checks if there are render-result nodes that need scene */
1342                                 if((re->r.scemode & R_SINGLE_LAYER)==0)
1343                                         ntree_render_scenes(re);
1344                                 
1345                                 if(!re->test_break()) {
1346                                         ntree->stats_draw= render_composit_stats;
1347                                         /* in case it was never initialized */
1348                                         R.stats_draw= re->stats_draw;
1349                                         
1350                                         ntreeCompositExecTree(ntree, &re->r, G.background==0);
1351                                         ntree->stats_draw= NULL;
1352                                 }
1353                         }
1354                 }
1355         }
1356         
1357
1358         re->i.lastframetime= PIL_check_seconds_timer()- re->i.starttime;
1359         re->stats_draw(&re->i);
1360         
1361         re->display_draw(re->result, NULL);
1362 }
1363
1364
1365 static int is_rendering_allowed(Render *re)
1366 {
1367         
1368         /* forbidden combinations */
1369         if(re->r.mode & R_PANORAMA) {
1370                 if(re->r.mode & R_BORDER) {
1371                         re->error("No border supported for Panorama");
1372                         return 0;
1373                 }
1374                 if(re->r.mode & R_ORTHO) {
1375                         re->error("No Ortho render possible for Panorama");
1376                         return 0;
1377                 }
1378         }
1379         
1380         if(re->r.mode & R_BORDER) {
1381                 if(re->r.border.xmax <= re->r.border.xmin || 
1382                    re->r.border.ymax <= re->r.border.ymin) {
1383                         re->error("No border area selected.");
1384                         return 0;
1385                 }
1386         }
1387         
1388         if(re->r.scemode & R_DOCOMP) {
1389                 if(re->scene->use_nodes) {
1390                         bNodeTree *ntree= re->scene->nodetree;
1391                         bNode *node;
1392                 
1393                         if(ntree==NULL) {
1394                                 re->error("No Nodetree in Scene");
1395                                 return 0;
1396                         }
1397                 
1398                         for(node= ntree->nodes.first; node; node= node->next)
1399                                 if(node->type==CMP_NODE_COMPOSITE)
1400                                         break;
1401                         
1402                         if(node==NULL) {
1403                                 re->error("No Render Output Node in Scene");
1404                                 return 0;
1405                         }
1406                 }
1407         }
1408         
1409         /* check valid camera */
1410         if(re->scene->camera==NULL)
1411                 re->scene->camera= scene_find_camera(re->scene);
1412         if(re->scene->camera==NULL) {
1413                 re->error("No camera");
1414                 return 0;
1415         }
1416         
1417         
1418         return 1;
1419 }
1420
1421 /* evaluating scene options for general Blender render */
1422 static int render_initialize_from_scene(Render *re, Scene *scene)
1423 {
1424         int winx, winy;
1425         rcti disprect;
1426         
1427         /* r.xsch and r.ysch has the actual view window size
1428                 r.border is the clipping rect */
1429         
1430         /* calculate actual render result and display size */
1431         winx= (scene->r.size*scene->r.xsch)/100;
1432         winy= (scene->r.size*scene->r.ysch)/100;
1433         
1434         /* only in movie case we render smaller part */
1435         if(scene->r.mode & R_BORDER) {
1436                 disprect.xmin= scene->r.border.xmin*winx;
1437                 disprect.xmax= scene->r.border.xmax*winx;
1438                 
1439                 disprect.ymin= scene->r.border.ymin*winy;
1440                 disprect.ymax= scene->r.border.ymax*winy;
1441         }
1442         else {
1443                 disprect.xmin= disprect.ymin= 0;
1444                 disprect.xmax= winx;
1445                 disprect.ymax= winy;
1446         }
1447         
1448 /*      if(G.rt) re->flag |= R_FILEBUFFER; */
1449         
1450         if(scene->r.scemode & R_SINGLE_LAYER)
1451                 push_render_result(re);
1452         
1453         RE_InitState(re, &scene->r, winx, winy, &disprect);
1454         re->flag &= ~R_FILEBUFFER;
1455         
1456         re->scene= scene;
1457         if(!is_rendering_allowed(re))
1458                 return 0;
1459         
1460         re->display_init(re->result);
1461         re->display_clear(re->result);
1462         
1463         return 1;
1464 }
1465
1466 /* general Blender frame render call */
1467 void RE_BlenderFrame(Render *re, Scene *scene, int frame)
1468 {
1469         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
1470         /* is also set by caller renderwin.c */
1471         G.rendering= 1;
1472         
1473         if(render_initialize_from_scene(re, scene)) {
1474                 do_render_final(re);
1475                 
1476         }
1477 }
1478
1479 static void do_write_image_or_movie(Render *re, Scene *scene, bMovieHandle *mh)
1480 {
1481         char name[FILE_MAXDIR+FILE_MAXFILE];
1482         RenderResult rres;
1483         
1484         RE_GetResultImage(re, &rres);
1485
1486         /* write movie or image */
1487         if(BKE_imtype_is_movie(scene->r.imtype)) {
1488                 int dofree = 0;
1489                 /* note; the way it gets 32 bits rects is weak... */
1490                 if(rres.rect32==NULL) {
1491                         rres.rect32= MEM_mapallocT(sizeof(int)*rres.rectx*rres.recty, "temp 32 bits rect");
1492                         dofree = 1;
1493                 }
1494                 RE_ResultGet32(re, rres.rect32);
1495                 mh->append_movie(scene->r.cfra, rres.rect32, rres.rectx, rres.recty);
1496                 if(dofree) {
1497                         MEM_freeT(rres.rect32);
1498                 }
1499                 printf("Append frame %d", scene->r.cfra);
1500         } else {
1501                 ImBuf *ibuf= IMB_allocImBuf(rres.rectx, rres.recty, scene->r.planes, 0, 0);
1502                 int ok;
1503                 
1504                 BKE_makepicstring(name, (scene->r.cfra));
1505
1506                 /* if not exists, BKE_write_ibuf makes one */
1507                 ibuf->rect= rres.rect32;    
1508                 ibuf->rect_float= rres.rectf;
1509                 ibuf->zbuf_float= rres.rectz;
1510                 
1511                 /* float factor for random dither, imbuf takes care of it */
1512                 ibuf->dither= scene->r.dither_intensity;
1513
1514                 ok= BKE_write_ibuf(ibuf, name, scene->r.imtype, scene->r.subimtype, scene->r.quality);
1515                 
1516                 if(ok==0) {
1517                         printf("Render error: cannot save %s\n", name);
1518                         G.afbreek=1;
1519                         return;
1520                 }
1521                 else printf("Saved: %s", name);
1522                 
1523                 /* optional preview images for exr */
1524                 if(ok && scene->r.imtype==R_OPENEXR && (scene->r.subimtype & R_PREVIEW_JPG)) {
1525                         if(BLI_testextensie(name, ".exr")) 
1526                                 name[strlen(name)-4]= 0;
1527                         BKE_add_image_extension(name, R_JPEG90);
1528                         ibuf->depth= 24; 
1529                         BKE_write_ibuf(ibuf, name, R_JPEG90, scene->r.subimtype, scene->r.quality);
1530                         printf("Saved: %s", name);
1531                 }
1532                 
1533                 /* imbuf knows which rects are not part of ibuf */
1534                 IMB_freeImBuf(ibuf);    
1535         }
1536         
1537         BLI_timestr(re->i.lastframetime, name);
1538         printf(" Time: %s\n", name);
1539         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
1540 }
1541
1542 /* saves images to disk */
1543 void RE_BlenderAnim(Render *re, Scene *scene, int sfra, int efra)
1544 {
1545         bMovieHandle *mh= BKE_get_movie_handle(scene->r.imtype);
1546         int cfrao= scene->r.cfra;
1547         
1548         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
1549         /* is also set by caller renderwin.c */
1550         G.rendering= 1;
1551         
1552         if(!render_initialize_from_scene(re, scene))
1553            return;
1554         
1555         /* confusing... scene->r or re->r? make a decision once! */
1556         if(BKE_imtype_is_movie(scene->r.imtype))
1557                 mh->start_movie(&scene->r, re->rectx, re->recty);
1558
1559         if (mh->get_next_frame) {
1560                 while (!(G.afbreek == 1)) {
1561                         int nf = mh->get_next_frame();
1562                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
1563                                 scene->r.cfra = nf;
1564                                 re->r.cfra= scene->r.cfra; /* weak.... */
1565                 
1566                                 do_render_final(re);
1567
1568                                 if(re->test_break() == 0) {
1569                                         do_write_image_or_movie(re, scene, mh);
1570                                 }
1571                         }
1572                 }
1573         } else {
1574                 for(scene->r.cfra= sfra; 
1575                     scene->r.cfra<=efra; scene->r.cfra++) {
1576                         re->r.cfra= scene->r.cfra;         /* weak.... */
1577                 
1578                         do_render_final(re);
1579
1580                         if(re->test_break() == 0) {
1581                                 do_write_image_or_movie(re, scene, mh);
1582                         }
1583                 
1584                         if(G.afbreek==1) break;
1585                 }
1586         }
1587         
1588         /* end movie */
1589         if(BKE_imtype_is_movie(scene->r.imtype))
1590                 mh->end_movie();
1591
1592         scene->r.cfra= cfrao;
1593 }
1594
1595
1596