Merged changes in the trunk up to revision 47977.
[blender.git] / source / blender / render / intern / source / pipeline.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2006 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/render/intern/source/pipeline.c
29  *  \ingroup render
30  */
31
32 #include <math.h>
33 #include <limits.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stddef.h>
37
38 #include "DNA_group_types.h"
39 #include "DNA_image_types.h"
40 #include "DNA_node_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_sequence_types.h"
44 #include "DNA_userdef_types.h"
45
46 #include "MEM_guardedalloc.h"
47
48 #include "BKE_animsys.h"  /* <------ should this be here?, needed for sequencer update */
49 #include "BKE_camera.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_library.h"
53 #include "BKE_main.h"
54 #include "BKE_node.h"
55 #include "BKE_pointcache.h"
56 #include "BKE_report.h"
57 #include "BKE_scene.h"
58 #include "BKE_sequencer.h"
59 #include "BKE_utildefines.h"
60 #include "BKE_writeavi.h"  /* <------ should be replaced once with generic movie module */
61
62 #include "BLI_math.h"
63 #include "BLI_listbase.h"
64 #include "BLI_string.h"
65 #include "BLI_path_util.h"
66 #include "BLI_fileops.h"
67 #include "BLI_rand.h"
68 #include "BLI_callbacks.h"
69
70 #include "PIL_time.h"
71 #include "IMB_imbuf.h"
72 #include "IMB_imbuf_types.h"
73
74 #include "RE_engine.h"
75 #include "RE_pipeline.h"
76
77 #include "FRS_freestyle.h"
78
79 /* internal */
80 #include "render_result.h"
81 #include "render_types.h"
82 #include "renderpipeline.h"
83 #include "renderdatabase.h"
84 #include "rendercore.h"
85 #include "initrender.h"
86 #include "shadbuf.h"
87 #include "pixelblending.h"
88 #include "zbuf.h"
89
90 /* render flow
91  *
92  * 1) Initialize state
93  * - state data, tables
94  * - movie/image file init
95  * - everything that doesn't change during animation
96  *
97  * 2) Initialize data
98  * - camera, world, matrices
99  * - make render verts, faces, halos, strands
100  * - everything can change per frame/field
101  *
102  * 3) Render Processor
103  * - multiple layers
104  * - tiles, rect, baking
105  * - layers/tiles optionally to disk or directly in Render Result
106  *
107  * 4) Composite Render Result
108  * - also read external files etc
109  *
110  * 5) Image Files
111  * - save file or append in movie
112  *
113  */
114
115
116 /* ********* globals ******** */
117
118 /* here we store all renders */
119 static struct {
120         ListBase renderlist;
121
122         /* commandline thread override */
123         int threads;
124 } RenderGlobal = {{NULL, NULL}, -1}; 
125
126 /* hardcopy of current render, used while rendering for speed */
127 Render R;
128
129 /* ********* alloc and free ******** */
130
131 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override);
132
133 static volatile int g_break = 0;
134 static int thread_break(void *UNUSED(arg))
135 {
136         return g_break;
137 }
138
139 /* default callbacks, set in each new render */
140 static void result_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr)) {}
141 static void result_rcti_nothing(void *UNUSED(arg), RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect)) {}
142 static void stats_nothing(void *UNUSED(arg), RenderStats *UNUSED(rs)) {}
143 static void float_nothing(void *UNUSED(arg), float UNUSED(val)) {}
144 static int default_break(void *UNUSED(arg)) {return G.afbreek == 1;}
145
146 static void stats_background(void *UNUSED(arg), RenderStats *rs)
147 {
148         uintptr_t mem_in_use, mmap_in_use, peak_memory;
149         float megs_used_memory, mmap_used_memory, megs_peak_memory;
150
151         mem_in_use = MEM_get_memory_in_use();
152         mmap_in_use = MEM_get_mapped_memory_in_use();
153         peak_memory = MEM_get_peak_memory();
154
155         megs_used_memory = (mem_in_use - mmap_in_use) / (1024.0 * 1024.0);
156         mmap_used_memory = (mmap_in_use) / (1024.0 * 1024.0);
157         megs_peak_memory = (peak_memory) / (1024.0 * 1024.0);
158
159         fprintf(stdout, "Fra:%d Mem:%.2fM (%.2fM, peak %.2fM) ", rs->cfra,
160                 megs_used_memory, mmap_used_memory, megs_peak_memory);
161
162         if (rs->curfield)
163                 fprintf(stdout, "Field %d ", rs->curfield);
164         if (rs->curblur)
165                 fprintf(stdout, "Blur %d ", rs->curblur);
166
167         if (rs->infostr) {
168                 fprintf(stdout, "| %s", rs->infostr);
169         }
170         else {
171                 if (rs->tothalo)
172                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d Ha:%d La:%d", rs->scenename, rs->totvert, rs->totface, rs->tothalo, rs->totlamp);
173                 else
174                         fprintf(stdout, "Sce: %s Ve:%d Fa:%d La:%d", rs->scenename, rs->totvert, rs->totface, rs->totlamp);
175         }
176
177         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
178
179         fputc('\n', stdout);
180         fflush(stdout);
181 }
182
183 void RE_FreeRenderResult(RenderResult *res)
184 {
185         render_result_free(res);
186 }
187
188 float *RE_RenderLayerGetPass(RenderLayer *rl, int passtype)
189 {
190         RenderPass *rpass;
191         
192         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
193                 if (rpass->passtype == passtype)
194                         return rpass->rect;
195         return NULL;
196 }
197
198 RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
199 {
200         RenderLayer *rl;
201         
202         if (rr == NULL) return NULL;
203         
204         for (rl = rr->layers.first; rl; rl = rl->next)
205                 if (strncmp(rl->name, name, RE_MAXNAME) == 0)
206                         return rl;
207         return NULL;
208 }
209
210 RenderResult *RE_MultilayerConvert(void *exrhandle, int rectx, int recty)
211 {
212         return render_result_new_from_exr(exrhandle, rectx, recty);
213 }
214
215 RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
216 {
217         RenderLayer *rl = BLI_findlink(&rr->layers, re->r.actlay);
218         
219         if (rl)
220                 return rl;
221         else 
222                 return rr->layers.first;
223 }
224
225 static int render_scene_needs_vector(Render *re)
226 {
227         SceneRenderLayer *srl;
228         
229         for (srl = re->scene->r.layers.first; srl; srl = srl->next)
230                 if (!(srl->layflag & SCE_LAY_DISABLE))
231                         if (srl->passflag & SCE_PASS_VECTOR)
232                                 return 1;
233
234         return 0;
235 }
236
237 /* *************************************************** */
238
239 Render *RE_GetRender(const char *name)
240 {
241         Render *re;
242
243         /* search for existing renders */
244         for (re = RenderGlobal.renderlist.first; re; re = re->next)
245                 if (strncmp(re->name, name, RE_MAXNAME) == 0)
246                         break;
247
248         return re;
249 }
250
251 /* if you want to know exactly what has been done */
252 RenderResult *RE_AcquireResultRead(Render *re)
253 {
254         if (re) {
255                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
256                 return re->result;
257         }
258
259         return NULL;
260 }
261
262 RenderResult *RE_AcquireResultWrite(Render *re)
263 {
264         if (re) {
265                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
266                 return re->result;
267         }
268
269         return NULL;
270 }
271
272 void RE_SwapResult(Render *re, RenderResult **rr)
273 {
274         /* for keeping render buffers */
275         if (re) {
276                 SWAP(RenderResult *, re->result, *rr);
277         }
278 }
279
280
281 void RE_ReleaseResult(Render *re)
282 {
283         if (re)
284                 BLI_rw_mutex_unlock(&re->resultmutex);
285 }
286
287 /* displist.c util.... */
288 Scene *RE_GetScene(Render *re)
289 {
290         if (re)
291                 return re->scene;
292         return NULL;
293 }
294
295 /* fill provided result struct with what's currently active or done */
296 void RE_AcquireResultImage(Render *re, RenderResult *rr)
297 {
298         memset(rr, 0, sizeof(RenderResult));
299
300         if (re) {
301                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_READ);
302
303                 if (re->result) {
304                         RenderLayer *rl;
305                         
306                         rr->rectx = re->result->rectx;
307                         rr->recty = re->result->recty;
308                         
309                         rr->rectf = re->result->rectf;
310                         rr->rectz = re->result->rectz;
311                         rr->rect32 = re->result->rect32;
312                         
313                         /* active layer */
314                         rl = render_get_active_layer(re, re->result);
315
316                         if (rl) {
317                                 if (rr->rectf == NULL)
318                                         rr->rectf = rl->rectf;
319                                 if (rr->rectz == NULL)
320                                         rr->rectz = RE_RenderLayerGetPass(rl, SCE_PASS_Z);
321                         }
322
323                         rr->have_combined = (re->result->rectf != NULL);
324                         rr->layers = re->result->layers;
325                 }
326         }
327 }
328
329 void RE_ReleaseResultImage(Render *re)
330 {
331         if (re)
332                 BLI_rw_mutex_unlock(&re->resultmutex);
333 }
334
335 /* caller is responsible for allocating rect in correct size! */
336 void RE_ResultGet32(Render *re, unsigned int *rect)
337 {
338         RenderResult rres;
339         
340         RE_AcquireResultImage(re, &rres);
341         render_result_rect_get_pixels(&rres, &re->r, rect, re->rectx, re->recty);
342         RE_ReleaseResultImage(re);
343 }
344
345 RenderStats *RE_GetStats(Render *re)
346 {
347         return &re->i;
348 }
349
350 Render *RE_NewRender(const char *name)
351 {
352         Render *re;
353
354         /* only one render per name exists */
355         re = RE_GetRender(name);
356         if (re == NULL) {
357                 
358                 /* new render data struct */
359                 re = MEM_callocN(sizeof(Render), "new render");
360                 BLI_addtail(&RenderGlobal.renderlist, re);
361                 BLI_strncpy(re->name, name, RE_MAXNAME);
362                 BLI_rw_mutex_init(&re->resultmutex);
363         }
364         
365         RE_InitRenderCB(re);
366
367         /* init some variables */
368         re->ycor = 1.0f;
369         
370         return re;
371 }
372
373 /* called for new renders and when finishing rendering so
374  * we always have valid callbacks on a render */
375 void RE_InitRenderCB(Render *re)
376 {
377         /* set default empty callbacks */
378         re->display_init = result_nothing;
379         re->display_clear = result_nothing;
380         re->display_draw = result_rcti_nothing;
381         re->progress = float_nothing;
382         re->test_break = default_break;
383         if (G.background)
384                 re->stats_draw = stats_background;
385         else
386                 re->stats_draw = stats_nothing;
387         /* clear callback handles */
388         re->dih = re->dch = re->ddh = re->sdh = re->prh = re->tbh = NULL;
389 }
390
391 /* only call this while you know it will remove the link too */
392 void RE_FreeRender(Render *re)
393 {
394         BLI_rw_mutex_end(&re->resultmutex);
395         
396         free_renderdata_tables(re);
397         free_sample_tables(re);
398         
399         render_result_free(re->result);
400         render_result_free(re->pushedresult);
401         
402         BLI_remlink(&RenderGlobal.renderlist, re);
403         MEM_freeN(re);
404 }
405
406 /* exit blender */
407 void RE_FreeAllRender(void)
408 {
409         while (RenderGlobal.renderlist.first) {
410                 RE_FreeRender(RenderGlobal.renderlist.first);
411         }
412 }
413
414 /* on file load, free all re */
415 void RE_FreeAllRenderResults(void)
416 {
417         Render *re;
418
419         for (re = RenderGlobal.renderlist.first; re; re = re->next) {
420                 render_result_free(re->result);
421                 render_result_free(re->pushedresult);
422
423                 re->result = NULL;
424                 re->pushedresult = NULL;
425         }
426 }
427
428 /* ********* initialize state ******** */
429
430
431 /* what doesn't change during entire render sequence */
432 /* disprect is optional, if NULL it assumes full window render */
433 void RE_InitState(Render *re, Render *source, RenderData *rd, SceneRenderLayer *srl, int winx, int winy, rcti *disprect)
434 {
435         re->ok = TRUE;   /* maybe flag */
436         
437         re->i.starttime = PIL_check_seconds_timer();
438         re->r = *rd;     /* hardcopy */
439         
440         re->winx = winx;
441         re->winy = winy;
442         if (disprect) {
443                 re->disprect = *disprect;
444                 re->rectx = disprect->xmax - disprect->xmin;
445                 re->recty = disprect->ymax - disprect->ymin;
446         }
447         else {
448                 re->disprect.xmin = re->disprect.ymin = 0;
449                 re->disprect.xmax = winx;
450                 re->disprect.ymax = winy;
451                 re->rectx = winx;
452                 re->recty = winy;
453         }
454         
455         if (re->rectx < 2 || re->recty < 2 || (BKE_imtype_is_movie(rd->im_format.imtype) &&
456                                                (re->rectx < 16 || re->recty < 16) ))
457         {
458                 BKE_report(re->reports, RPT_ERROR, "Image too small");
459                 re->ok = 0;
460                 return;
461         }
462
463         if ((re->r.mode & (R_OSA)) == 0)
464                 re->r.scemode &= ~R_FULL_SAMPLE;
465
466 #ifdef WITH_OPENEXR
467         if (re->r.scemode & R_FULL_SAMPLE)
468                 re->r.scemode |= R_EXR_TILE_FILE;   /* enable automatic */
469
470         /* Until use_border is made compatible with save_buffers/full_sample, render without the later instead of not rendering at all.*/
471         if (re->r.mode & R_BORDER) {
472                 re->r.scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
473         }
474
475 #else
476         /* can't do this without openexr support */
477         re->r.scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
478 #endif
479         
480         /* fullsample wants uniform osa levels */
481         if (source && (re->r.scemode & R_FULL_SAMPLE)) {
482                 /* but, if source has no full sample we disable it */
483                 if ((source->r.scemode & R_FULL_SAMPLE) == 0)
484                         re->r.scemode &= ~R_FULL_SAMPLE;
485                 else
486                         re->r.osa = re->osa = source->osa;
487         }
488         else {
489                 /* check state variables, osa? */
490                 if (re->r.mode & (R_OSA)) {
491                         re->osa = re->r.osa;
492                         if (re->osa > 16) re->osa = 16;
493                 }
494                 else re->osa = 0;
495         }
496         
497         if (srl) {
498                 int index = BLI_findindex(&re->r.layers, srl);
499                 if (index != -1) {
500                         re->r.actlay = index;
501                         re->r.scemode |= R_SINGLE_LAYER;
502                 }
503         }
504                 
505         /* always call, checks for gamma, gamma tables and jitter too */
506         make_sample_tables(re); 
507         
508         /* if preview render, we try to keep old result */
509         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
510
511         if (re->r.scemode & R_PREVIEWBUTS) {
512                 if (re->result && re->result->rectx == re->rectx && re->result->recty == re->recty) ;
513                 else {
514                         render_result_free(re->result);
515                         re->result = NULL;
516                 }
517         }
518         else {
519                 
520                 /* make empty render result, so display callbacks can initialize */
521                 render_result_free(re->result);
522                 re->result = MEM_callocN(sizeof(RenderResult), "new render result");
523                 re->result->rectx = re->rectx;
524                 re->result->recty = re->recty;
525         }
526
527         BLI_rw_mutex_unlock(&re->resultmutex);
528         
529         /* we clip faces with a minimum of 2 pixel boundary outside of image border. see zbuf.c */
530         re->clipcrop = 1.0f + 2.0f / (float)(re->winx > re->winy ? re->winy : re->winx);
531         
532         re->mblur_offs = re->field_offs = 0.f;
533         
534         RE_init_threadcount(re);
535 }
536
537 void RE_SetWindow(Render *re, rctf *viewplane, float clipsta, float clipend)
538 {
539         /* re->ok flag? */
540         
541         re->viewplane = *viewplane;
542         re->clipsta = clipsta;
543         re->clipend = clipend;
544         re->r.mode &= ~R_ORTHO;
545
546         perspective_m4(re->winmat,
547                        re->viewplane.xmin, re->viewplane.xmax,
548                        re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
549         
550 }
551
552 void RE_SetOrtho(Render *re, rctf *viewplane, float clipsta, float clipend)
553 {
554         /* re->ok flag? */
555         
556         re->viewplane = *viewplane;
557         re->clipsta = clipsta;
558         re->clipend = clipend;
559         re->r.mode |= R_ORTHO;
560
561         orthographic_m4(re->winmat,
562                         re->viewplane.xmin, re->viewplane.xmax,
563                         re->viewplane.ymin, re->viewplane.ymax, re->clipsta, re->clipend);
564 }
565
566 void RE_SetView(Render *re, float mat[][4])
567 {
568         /* re->ok flag? */
569         copy_m4_m4(re->viewmat, mat);
570         invert_m4_m4(re->viewinv, re->viewmat);
571 }
572
573 /* image and movie output has to move to either imbuf or kernel */
574 void RE_display_init_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
575 {
576         re->display_init = f;
577         re->dih = handle;
578 }
579 void RE_display_clear_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr))
580 {
581         re->display_clear = f;
582         re->dch = handle;
583 }
584 void RE_display_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderResult *rr, volatile rcti *rect))
585 {
586         re->display_draw = f;
587         re->ddh = handle;
588 }
589 void RE_stats_draw_cb(Render *re, void *handle, void (*f)(void *handle, RenderStats *rs))
590 {
591         re->stats_draw = f;
592         re->sdh = handle;
593 }
594 void RE_progress_cb(Render *re, void *handle, void (*f)(void *handle, float))
595 {
596         re->progress = f;
597         re->prh = handle;
598 }
599
600 void RE_draw_lock_cb(Render *re, void *handle, void (*f)(void *handle, int i))
601 {
602         re->draw_lock = f;
603         re->tbh = handle;
604 }
605
606 void RE_test_break_cb(Render *re, void *handle, int (*f)(void *handle))
607 {
608         re->test_break = f;
609         re->tbh = handle;
610 }
611
612
613 /* ********* add object data (later) ******** */
614
615 /* object is considered fully prepared on correct time etc */
616 /* includes lights */
617 #if 0
618 void RE_AddObject(Render *UNUSED(re), Object *UNUSED(ob))
619 {
620         
621 }
622 #endif
623
624 /* *************************************** */
625
626 static int render_display_draw_enabled(Render *re)
627 {
628         /* don't show preprocess for previewrender sss */
629         if (re->sss_points)
630                 return !(re->r.scemode & R_PREVIEWBUTS);
631         else
632                 return 1;
633 }
634
635 /* the main thread call, renders an entire part */
636 static void *do_part_thread(void *pa_v)
637 {
638         RenderPart *pa = pa_v;
639         
640         /* need to return nicely all parts on esc */
641         if (R.test_break(R.tbh) == 0) {
642                 
643                 if (!R.sss_points && (R.r.scemode & R_FULL_SAMPLE))
644                         pa->result = render_result_new_full_sample(&R, &pa->fullresult, &pa->disprect, pa->crop, RR_USE_MEM);
645                 else
646                         pa->result = render_result_new(&R, &pa->disprect, pa->crop, RR_USE_MEM);
647
648                 if (R.sss_points)
649                         zbufshade_sss_tile(pa);
650                 else if (R.osa)
651                         zbufshadeDA_tile(pa);
652                 else
653                         zbufshade_tile(pa);
654                 
655                 /* merge too on break! */
656                 if (R.result->exrhandle) {
657                         render_result_exr_file_merge(R.result, pa->result);
658                 }
659                 else if (render_display_draw_enabled(&R)) {
660                         /* on break, don't merge in result for preview renders, looks nicer */
661                         if (R.test_break(R.tbh) && (R.r.scemode & R_PREVIEWBUTS)) ;
662                         else render_result_merge(R.result, pa->result);
663                 }
664         }
665         
666         pa->ready = 1;
667         
668         return NULL;
669 }
670
671 /* calculus for how much 1 pixel rendered should rotate the 3d geometry */
672 /* is not that simple, needs to be corrected for errors of larger viewplane sizes */
673 /* called in initrender.c, initparts() and convertblender.c, for speedvectors */
674 float panorama_pixel_rot(Render *re)
675 {
676         float psize, phi, xfac;
677         float borderfac = (float)(re->disprect.xmax - re->disprect.xmin) / (float)re->winx;
678         
679         /* size of 1 pixel mapped to viewplane coords */
680         psize = (re->viewplane.xmax - re->viewplane.xmin) / (float)(re->winx);
681         /* angle of a pixel */
682         phi = atan(psize / re->clipsta);
683         
684         /* correction factor for viewplane shifting, first calculate how much the viewplane angle is */
685         xfac = borderfac * ((re->viewplane.xmax - re->viewplane.xmin)) / (float)re->xparts;
686         xfac = atan(0.5f * xfac / re->clipsta);
687         /* and how much the same viewplane angle is wrapped */
688         psize = 0.5f * phi * ((float)re->partx);
689         
690         /* the ratio applied to final per-pixel angle */
691         phi *= xfac / psize;
692         
693         return phi;
694 }
695
696 /* call when all parts stopped rendering, to find the next Y slice */
697 /* if slice found, it rotates the dbase */
698 static RenderPart *find_next_pano_slice(Render *re, int *minx, rctf *viewplane)
699 {
700         RenderPart *pa, *best = NULL;
701         
702         *minx = re->winx;
703         
704         /* most left part of the non-rendering parts */
705         for (pa = re->parts.first; pa; pa = pa->next) {
706                 if (pa->ready == 0 && pa->nr == 0) {
707                         if (pa->disprect.xmin < *minx) {
708                                 best = pa;
709                                 *minx = pa->disprect.xmin;
710                         }
711                 }
712         }
713                         
714         if (best) {
715                 float phi = panorama_pixel_rot(re);
716
717                 R.panodxp = (re->winx - (best->disprect.xmin + best->disprect.xmax) ) / 2;
718                 R.panodxv = ((viewplane->xmax - viewplane->xmin) * R.panodxp) / (float)(re->winx);
719                 
720                 /* shift viewplane */
721                 R.viewplane.xmin = viewplane->xmin + R.panodxv;
722                 R.viewplane.xmax = viewplane->xmax + R.panodxv;
723                 RE_SetWindow(re, &R.viewplane, R.clipsta, R.clipend);
724                 copy_m4_m4(R.winmat, re->winmat);
725                 
726                 /* rotate database according to part coordinates */
727                 project_renderdata(re, projectverto, 1, -R.panodxp * phi, 1);
728                 R.panosi = sin(R.panodxp * phi);
729                 R.panoco = cos(R.panodxp * phi);
730         }
731         return best;
732 }
733
734 static RenderPart *find_next_part(Render *re, int minx)
735 {
736         RenderPart *pa, *best = NULL;
737
738         /* long long int's needed because of overflow [#24414] */
739         long long int centx = re->winx / 2, centy = re->winy / 2, tot = 1;
740         long long int mindist = (long long int)re->winx * (long long int)re->winy;
741         
742         /* find center of rendered parts, image center counts for 1 too */
743         for (pa = re->parts.first; pa; pa = pa->next) {
744                 if (pa->ready) {
745                         centx += (pa->disprect.xmin + pa->disprect.xmax) / 2;
746                         centy += (pa->disprect.ymin + pa->disprect.ymax) / 2;
747                         tot++;
748                 }
749         }
750         centx /= tot;
751         centy /= tot;
752         
753         /* closest of the non-rendering parts */
754         for (pa = re->parts.first; pa; pa = pa->next) {
755                 if (pa->ready == 0 && pa->nr == 0) {
756                         long long int distx = centx - (pa->disprect.xmin + pa->disprect.xmax) / 2;
757                         long long int disty = centy - (pa->disprect.ymin + pa->disprect.ymax) / 2;
758                         distx = (long long int)sqrt(distx * distx + disty * disty);
759                         if (distx < mindist) {
760                                 if (re->r.mode & R_PANORAMA) {
761                                         if (pa->disprect.xmin == minx) {
762                                                 best = pa;
763                                                 mindist = distx;
764                                         }
765                                 }
766                                 else {
767                                         best = pa;
768                                         mindist = distx;
769                                 }
770                         }
771                 }
772         }
773         return best;
774 }
775
776 static void print_part_stats(Render *re, RenderPart *pa)
777 {
778         char str[64];
779         
780         BLI_snprintf(str, sizeof(str), "%s, Part %d-%d", re->scene->id.name + 2, pa->nr, re->i.totpart);
781         re->i.infostr = str;
782         re->stats_draw(re->sdh, &re->i);
783         re->i.infostr = NULL;
784 }
785
786 static void threaded_tile_processor(Render *re)
787 {
788         ListBase threads;
789         RenderPart *pa, *nextpa;
790         rctf viewplane = re->viewplane;
791         int rendering = 1, counter = 1, drawtimer = 0, hasdrawn, minx = 0;
792         
793         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
794
795         /* first step; free the entire render result, make new, and/or prepare exr buffer saving */
796         if (re->result == NULL || !(re->r.scemode & R_PREVIEWBUTS)) {
797                 render_result_free(re->result);
798         
799                 if (re->sss_points && render_display_draw_enabled(re))
800                         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM);
801                 else if (re->r.scemode & R_FULL_SAMPLE)
802                         re->result = render_result_new_full_sample(re, &re->fullresult, &re->disprect, 0, RR_USE_EXR);
803                 else
804                         re->result = render_result_new(re, &re->disprect, 0,
805                                                        (re->r.scemode & R_EXR_TILE_FILE) ? RR_USE_EXR : RR_USE_MEM);
806         }
807
808         BLI_rw_mutex_unlock(&re->resultmutex);
809         
810         if (re->result == NULL)
811                 return;
812         
813         /* warning; no return here without closing exr file */
814         
815         initparts(re);
816
817         if (re->result->exrhandle)
818                 render_result_exr_file_begin(re);
819         
820         BLI_init_threads(&threads, do_part_thread, re->r.threads);
821         
822         /* assuming no new data gets added to dbase... */
823         R = *re;
824         
825         /* set threadsafe break */
826         R.test_break = thread_break;
827         
828         /* timer loop demands to sleep when no parts are left, so we enter loop with a part */
829         if (re->r.mode & R_PANORAMA)
830                 nextpa = find_next_pano_slice(re, &minx, &viewplane);
831         else
832                 nextpa = find_next_part(re, 0);
833         
834         while (rendering) {
835                 
836                 if (re->test_break(re->tbh))
837                         PIL_sleep_ms(50);
838                 else if (nextpa && BLI_available_threads(&threads)) {
839                         drawtimer = 0;
840                         nextpa->nr = counter++;  /* for nicest part, and for stats */
841                         nextpa->thread = BLI_available_thread_index(&threads);   /* sample index */
842                         BLI_insert_thread(&threads, nextpa);
843
844                         nextpa = find_next_part(re, minx);
845                 }
846                 else if (re->r.mode & R_PANORAMA) {
847                         if (nextpa == NULL && BLI_available_threads(&threads) == re->r.threads)
848                                 nextpa = find_next_pano_slice(re, &minx, &viewplane);
849                         else {
850                                 PIL_sleep_ms(50);
851                                 drawtimer++;
852                         }
853                 }
854                 else {
855                         PIL_sleep_ms(50);
856                         drawtimer++;
857                 }
858                 
859                 /* check for ready ones to display, and if we need to continue */
860                 rendering = 0;
861                 hasdrawn = 0;
862                 for (pa = re->parts.first; pa; pa = pa->next) {
863                         if (pa->ready) {
864                                 
865                                 BLI_remove_thread(&threads, pa);
866                                 
867                                 if (pa->result) {
868                                         if (render_display_draw_enabled(re))
869                                                 re->display_draw(re->ddh, pa->result, NULL);
870                                         print_part_stats(re, pa);
871                                         
872                                         render_result_free_list(&pa->fullresult, pa->result);
873                                         pa->result = NULL;
874                                         re->i.partsdone++;
875                                         re->progress(re->prh, re->i.partsdone / (float)re->i.totpart);
876                                         hasdrawn = 1;
877                                 }
878                         }
879                         else {
880                                 rendering = 1;
881                                 if (pa->nr && pa->result && drawtimer > 20) {
882                                         if (render_display_draw_enabled(re))
883                                                 re->display_draw(re->ddh, pa->result, &pa->result->renrect);
884                                         hasdrawn = 1;
885                                 }
886                         }
887                 }
888                 if (hasdrawn)
889                         drawtimer = 0;
890
891                 /* on break, wait for all slots to get freed */
892                 if ( (g_break = re->test_break(re->tbh)) && BLI_available_threads(&threads) == re->r.threads)
893                         rendering = 0;
894                 
895         }
896         
897         if (re->result->exrhandle) {
898                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
899                 render_result_exr_file_end(re);
900                 BLI_rw_mutex_unlock(&re->resultmutex);
901         }
902         
903         /* unset threadsafety */
904         g_break = 0;
905         
906         BLI_end_threads(&threads);
907         freeparts(re);
908         re->viewplane = viewplane; /* restore viewplane, modified by pano render */
909 }
910
911 /* currently only called by preview renders and envmap */
912 void RE_TileProcessor(Render *re)
913 {
914         threaded_tile_processor(re);
915 }
916
917 /* ************  This part uses API, for rendering Blender scenes ********** */
918
919 static void add_freestyle(Render *re);
920
921 static void do_render_3d(Render *re)
922 {
923         /* try external */
924         if (RE_engine_render(re, 0))
925                 return;
926
927         /* internal */
928         
929 //      re->cfra= cfra; /* <- unused! */
930         re->scene->r.subframe = re->mblur_offs + re->field_offs;
931         
932         /* lock drawing in UI during data phase */
933         if (re->draw_lock)
934                 re->draw_lock(re->dlh, 1);
935         
936         /* make render verts/faces/halos/lamps */
937         if (render_scene_needs_vector(re))
938                 RE_Database_FromScene_Vectors(re, re->main, re->scene, re->lay);
939         else
940                 RE_Database_FromScene(re, re->main, re->scene, re->lay, 1);
941         
942         /* clear UI drawing locks */
943         if (re->draw_lock)
944                 re->draw_lock(re->dlh, 0);
945         
946         threaded_tile_processor(re);
947         
948         /* do left-over 3d post effects (flares) */
949         if (re->flag & R_HALO)
950                 if (!re->test_break(re->tbh))
951                         add_halo_flare(re);
952         
953         /* Freestyle  */
954         if( re->r.mode & R_EDGE_FRS)
955                 if(!re->test_break(re->tbh))
956                         add_freestyle(re);
957                 
958         /* free all render verts etc */
959         RE_Database_Free(re);
960         
961         re->scene->r.subframe = 0.f;
962 }
963
964 /* called by blur loop, accumulate RGBA key alpha */
965 static void addblur_rect_key(RenderResult *rr, float *rectf, float *rectf1, float blurfac)
966 {
967         float mfac = 1.0f - blurfac;
968         int a, b, stride = 4 * rr->rectx;
969         int len = stride * sizeof(float);
970         
971         for (a = 0; a < rr->recty; a++) {
972                 if (blurfac == 1.0f) {
973                         memcpy(rectf, rectf1, len);
974                 }
975                 else {
976                         float *rf = rectf, *rf1 = rectf1;
977                         
978                         for (b = rr->rectx; b > 0; b--, rf += 4, rf1 += 4) {
979                                 if (rf1[3] < 0.01f)
980                                         rf[3] = mfac * rf[3];
981                                 else if (rf[3] < 0.01f) {
982                                         rf[0] = rf1[0];
983                                         rf[1] = rf1[1];
984                                         rf[2] = rf1[2];
985                                         rf[3] = blurfac * rf1[3];
986                                 }
987                                 else {
988                                         rf[0] = mfac * rf[0] + blurfac * rf1[0];
989                                         rf[1] = mfac * rf[1] + blurfac * rf1[1];
990                                         rf[2] = mfac * rf[2] + blurfac * rf1[2];
991                                         rf[3] = mfac * rf[3] + blurfac * rf1[3];
992                                 }                               
993                         }
994                 }
995                 rectf += stride;
996                 rectf1 += stride;
997         }
998 }
999
1000 /* called by blur loop, accumulate renderlayers */
1001 static void addblur_rect(RenderResult *rr, float *rectf, float *rectf1, float blurfac, int channels)
1002 {
1003         float mfac = 1.0f - blurfac;
1004         int a, b, stride = channels * rr->rectx;
1005         int len = stride * sizeof(float);
1006         
1007         for (a = 0; a < rr->recty; a++) {
1008                 if (blurfac == 1.0f) {
1009                         memcpy(rectf, rectf1, len);
1010                 }
1011                 else {
1012                         float *rf = rectf, *rf1 = rectf1;
1013                         
1014                         for (b = rr->rectx * channels; b > 0; b--, rf++, rf1++) {
1015                                 rf[0] = mfac * rf[0] + blurfac * rf1[0];
1016                         }
1017                 }
1018                 rectf += stride;
1019                 rectf1 += stride;
1020         }
1021 }
1022
1023
1024 /* called by blur loop, accumulate renderlayers */
1025 static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float blurfac, int key_alpha)
1026 {
1027         RenderLayer *rl, *rl1;
1028         RenderPass *rpass, *rpass1;
1029         
1030         rl1 = brr->layers.first;
1031         for (rl = rr->layers.first; rl && rl1; rl = rl->next, rl1 = rl1->next) {
1032                 
1033                 /* combined */
1034                 if (rl->rectf && rl1->rectf) {
1035                         if (key_alpha)
1036                                 addblur_rect_key(rr, rl->rectf, rl1->rectf, blurfac);
1037                         else
1038                                 addblur_rect(rr, rl->rectf, rl1->rectf, blurfac, 4);
1039                 }
1040                 
1041                 /* passes are allocated in sync */
1042                 rpass1 = rl1->passes.first;
1043                 for (rpass = rl->passes.first; rpass && rpass1; rpass = rpass->next, rpass1 = rpass1->next) {
1044                         addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
1045                 }
1046         }
1047 }
1048
1049 /* main blur loop, can be called by fields too */
1050 static void do_render_blur_3d(Render *re)
1051 {
1052         RenderResult *rres;
1053         float blurfac;
1054         int blur = re->r.mblur_samples;
1055         
1056         /* create accumulation render result */
1057         rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM);
1058         
1059         /* do the blur steps */
1060         while (blur--) {
1061                 re->mblur_offs = re->r.blurfac * ((float)(re->r.mblur_samples - blur)) / (float)re->r.mblur_samples;
1062                 
1063                 re->i.curblur = re->r.mblur_samples - blur;    /* stats */
1064                 
1065                 do_render_3d(re);
1066                 
1067                 blurfac = 1.0f / (float)(re->r.mblur_samples - blur);
1068                 
1069                 merge_renderresult_blur(rres, re->result, blurfac, re->r.alphamode & R_ALPHAKEY);
1070                 if (re->test_break(re->tbh)) break;
1071         }
1072         
1073         /* swap results */
1074         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1075         render_result_free(re->result);
1076         re->result = rres;
1077         BLI_rw_mutex_unlock(&re->resultmutex);
1078         
1079         re->mblur_offs = 0.0f;
1080         re->i.curblur = 0;   /* stats */
1081         
1082         /* weak... the display callback wants an active renderlayer pointer... */
1083         re->result->renlay = render_get_active_layer(re, re->result);
1084         re->display_draw(re->ddh, re->result, NULL);    
1085 }
1086
1087
1088 /* function assumes rectf1 and rectf2 to be half size of rectf */
1089 static void interleave_rect(RenderResult *rr, float *rectf, float *rectf1, float *rectf2, int channels)
1090 {
1091         int a, stride = channels * rr->rectx;
1092         int len = stride * sizeof(float);
1093         
1094         for (a = 0; a < rr->recty; a += 2) {
1095                 memcpy(rectf, rectf1, len);
1096                 rectf += stride;
1097                 rectf1 += stride;
1098                 memcpy(rectf, rectf2, len);
1099                 rectf += stride;
1100                 rectf2 += stride;
1101         }
1102 }
1103
1104 /* merge render results of 2 fields */
1105 static void merge_renderresult_fields(RenderResult *rr, RenderResult *rr1, RenderResult *rr2)
1106 {
1107         RenderLayer *rl, *rl1, *rl2;
1108         RenderPass *rpass, *rpass1, *rpass2;
1109         
1110         rl1 = rr1->layers.first;
1111         rl2 = rr2->layers.first;
1112         for (rl = rr->layers.first; rl && rl1 && rl2; rl = rl->next, rl1 = rl1->next, rl2 = rl2->next) {
1113                 
1114                 /* combined */
1115                 if (rl->rectf && rl1->rectf && rl2->rectf)
1116                         interleave_rect(rr, rl->rectf, rl1->rectf, rl2->rectf, 4);
1117                 
1118                 /* passes are allocated in sync */
1119                 rpass1 = rl1->passes.first;
1120                 rpass2 = rl2->passes.first;
1121                 for (rpass = rl->passes.first; rpass && rpass1 && rpass2; rpass = rpass->next, rpass1 = rpass1->next, rpass2 = rpass2->next) {
1122                         interleave_rect(rr, rpass->rect, rpass1->rect, rpass2->rect, rpass->channels);
1123                 }
1124         }
1125 }
1126
1127
1128 /* interleaves 2 frames */
1129 static void do_render_fields_3d(Render *re)
1130 {
1131         Object *camera = RE_GetCamera(re);
1132         RenderResult *rr1, *rr2 = NULL;
1133         
1134         /* no render result was created, we can safely halve render y */
1135         re->winy /= 2;
1136         re->recty /= 2;
1137         re->disprect.ymin /= 2;
1138         re->disprect.ymax /= 2;
1139         
1140         re->i.curfield = 1;  /* stats */
1141         
1142         /* first field, we have to call camera routine for correct aspect and subpixel offset */
1143         RE_SetCamera(re, camera);
1144         if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1145                 do_render_blur_3d(re);
1146         else
1147                 do_render_3d(re);
1148
1149         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1150         rr1 = re->result;
1151         re->result = NULL;
1152         BLI_rw_mutex_unlock(&re->resultmutex);
1153         
1154         /* second field */
1155         if (!re->test_break(re->tbh)) {
1156                 
1157                 re->i.curfield = 2;  /* stats */
1158                 
1159                 re->flag |= R_SEC_FIELD;
1160                 if ((re->r.mode & R_FIELDSTILL) == 0) {
1161                         re->field_offs = 0.5f;
1162                 }
1163                 RE_SetCamera(re, camera);
1164                 if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1165                         do_render_blur_3d(re);
1166                 else
1167                         do_render_3d(re);
1168                 re->flag &= ~R_SEC_FIELD;
1169                 
1170                 re->field_offs = 0.0f;
1171                 
1172                 rr2 = re->result;
1173         }
1174         
1175         /* allocate original height new buffers */
1176         re->winy *= 2;
1177         re->recty *= 2;
1178         re->disprect.ymin *= 2;
1179         re->disprect.ymax *= 2;
1180
1181         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1182         re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM);
1183
1184         if (rr2) {
1185                 if (re->r.mode & R_ODDFIELD)
1186                         merge_renderresult_fields(re->result, rr2, rr1);
1187                 else
1188                         merge_renderresult_fields(re->result, rr1, rr2);
1189                 
1190                 render_result_free(rr2);
1191         }
1192
1193         render_result_free(rr1);
1194         
1195         re->i.curfield = 0;  /* stats */
1196         
1197         /* weak... the display callback wants an active renderlayer pointer... */
1198         re->result->renlay = render_get_active_layer(re, re->result);
1199
1200         BLI_rw_mutex_unlock(&re->resultmutex);
1201
1202         re->display_draw(re->ddh, re->result, NULL);
1203 }
1204
1205 /* main render routine, no compositing */
1206 static void do_render_fields_blur_3d(Render *re)
1207 {
1208         Object *camera = RE_GetCamera(re);
1209         /* also check for camera here */
1210         if (camera == NULL) {
1211                 printf("ERROR: Cannot render, no camera\n");
1212                 G.afbreek = 1;
1213                 return;
1214         }
1215
1216         /* now use renderdata and camera to set viewplane */
1217         RE_SetCamera(re, camera);
1218         
1219         if (re->r.mode & R_FIELDS)
1220                 do_render_fields_3d(re);
1221         else if (re->r.mode & R_MBLUR && (re->r.scemode & R_FULL_SAMPLE) == 0)
1222                 do_render_blur_3d(re);
1223         else
1224                 do_render_3d(re);
1225         
1226         /* when border render, check if we have to insert it in black */
1227         if (re->result) {
1228                 if (re->r.mode & R_BORDER) {
1229                         if ((re->r.mode & R_CROP) == 0) {
1230                                 RenderResult *rres;
1231                                 
1232                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1233
1234                                 /* sub-rect for merge call later on */
1235                                 re->result->tilerect = re->disprect;
1236                                 
1237                                 /* this copying sequence could become function? */
1238                                 /* weak is: it chances disprect from border */
1239                                 re->disprect.xmin = re->disprect.ymin = 0;
1240                                 re->disprect.xmax = re->winx;
1241                                 re->disprect.ymax = re->winy;
1242                                 re->rectx = re->winx;
1243                                 re->recty = re->winy;
1244                                 
1245                                 rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM);
1246                                 
1247                                 render_result_merge(rres, re->result);
1248                                 render_result_free(re->result);
1249                                 re->result = rres;
1250                                 
1251                                 /* weak... the display callback wants an active renderlayer pointer... */
1252                                 re->result->renlay = render_get_active_layer(re, re->result);
1253                                 
1254                                 BLI_rw_mutex_unlock(&re->resultmutex);
1255                 
1256                                 re->display_init(re->dih, re->result);
1257                                 re->display_draw(re->ddh, re->result, NULL);
1258                         }
1259                         else {
1260                                 /* set offset (again) for use in compositor, disprect was manipulated. */
1261                                 re->result->xof = 0;
1262                                 re->result->yof = 0;
1263                         }
1264                 }
1265         }
1266 }
1267
1268
1269 /* within context of current Render *re, render another scene.
1270  * it uses current render image size and disprect, but doesn't execute composite
1271  */
1272 static void render_scene(Render *re, Scene *sce, int cfra)
1273 {
1274         Render *resc = RE_NewRender(sce->id.name);
1275         int winx = re->winx, winy = re->winy;
1276         
1277         sce->r.cfra = cfra;
1278
1279         BKE_scene_camera_switch_update(sce);
1280
1281         /* exception: scene uses own size (unfinished code) */
1282         if (0) {
1283                 winx = (sce->r.size * sce->r.xsch) / 100;
1284                 winy = (sce->r.size * sce->r.ysch) / 100;
1285         }
1286         
1287         /* initial setup */
1288         RE_InitState(resc, re, &sce->r, NULL, winx, winy, &re->disprect);
1289         
1290         /* still unsure entity this... */
1291         resc->main = re->main;
1292         resc->scene = sce;
1293         resc->lay = sce->lay;
1294         
1295         /* ensure scene has depsgraph, base flags etc OK */
1296         BKE_scene_set_background(re->main, sce);
1297
1298         /* copy callbacks */
1299         resc->display_draw = re->display_draw;
1300         resc->ddh = re->ddh;
1301         resc->test_break = re->test_break;
1302         resc->tbh = re->tbh;
1303         resc->stats_draw = re->stats_draw;
1304         resc->sdh = re->sdh;
1305         
1306         do_render_fields_blur_3d(resc);
1307 }
1308
1309 /* helper call to detect if this scene needs a render, or if there's a any render layer to render */
1310 static int composite_needs_render(Scene *sce, int this_scene)
1311 {
1312         bNodeTree *ntree = sce->nodetree;
1313         bNode *node;
1314         
1315         if (ntree == NULL) return 1;
1316         if (sce->use_nodes == FALSE) return 1;
1317         if ((sce->r.scemode & R_DOCOMP) == 0) return 1;
1318         
1319         for (node = ntree->nodes.first; node; node = node->next) {
1320                 if (node->type == CMP_NODE_R_LAYERS)
1321                         if (this_scene == 0 || node->id == NULL || node->id == &sce->id)
1322                                 return 1;
1323         }
1324         return 0;
1325 }
1326
1327 static void tag_scenes_for_render(Render *re)
1328 {
1329         bNode *node;
1330         Scene *sce;
1331         
1332         for (sce = re->main->scene.first; sce; sce = sce->id.next)
1333                 sce->id.flag &= ~LIB_DOIT;
1334         
1335         if (RE_GetCamera(re) && composite_needs_render(re->scene, 1))
1336                 re->scene->id.flag |= LIB_DOIT;
1337         
1338         if (re->scene->nodetree == NULL) return;
1339         
1340         /* check for render-layers nodes using other scenes, we tag them LIB_DOIT */
1341         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1342                 if (node->type == CMP_NODE_R_LAYERS) {
1343                         if (node->id) {
1344                                 if (node->id != (ID *)re->scene)
1345                                         node->id->flag |= LIB_DOIT;
1346                         }
1347                 }
1348         }
1349         
1350 }
1351
1352 static void ntree_render_scenes(Render *re)
1353 {
1354         bNode *node;
1355         int cfra = re->scene->r.cfra;
1356         int restore_scene = 0;
1357         
1358         if (re->scene->nodetree == NULL) return;
1359         
1360         tag_scenes_for_render(re);
1361         
1362         /* now foreach render-result node tagged we do a full render */
1363         /* results are stored in a way compisitor will find it */
1364         for (node = re->scene->nodetree->nodes.first; node; node = node->next) {
1365                 if (node->type == CMP_NODE_R_LAYERS) {
1366                         if (node->id && node->id != (ID *)re->scene) {
1367                                 if (node->id->flag & LIB_DOIT) {
1368                                         Scene *scene = (Scene *)node->id;
1369
1370                                         render_scene(re, scene, cfra);
1371                                         restore_scene = (scene != re->scene);
1372                                         node->id->flag &= ~LIB_DOIT;
1373                                         
1374                                         nodeUpdate(re->scene->nodetree, node);
1375                                 }
1376                         }
1377                 }
1378         }
1379
1380         /* restore scene if we rendered another last */
1381         if (restore_scene)
1382                 BKE_scene_set_background(re->main, re->scene);
1383 }
1384
1385 /* bad call... need to think over proper method still */
1386 static void render_composit_stats(void *UNUSED(arg), char *str)
1387 {
1388         R.i.infostr = str;
1389         R.stats_draw(R.sdh, &R.i);
1390         R.i.infostr = NULL;
1391 }
1392
1393 /* invokes Freestyle stroke rendering */
1394 static void add_freestyle(Render *re)
1395 {
1396         SceneRenderLayer *srl, *actsrl;
1397         LinkData *link;
1398
1399         actsrl = BLI_findlink(&re->r.layers, re->r.actlay);
1400
1401         FRS_init_stroke_rendering(re);
1402
1403         for (srl= (SceneRenderLayer *)re->r.layers.first; srl; srl= srl->next) {
1404
1405                 link = (LinkData *)MEM_callocN(sizeof(LinkData), "LinkData to Freestyle render");
1406                 BLI_addtail(&re->freestyle_renders, link);
1407
1408                 if ((re->r.scemode & R_SINGLE_LAYER) && srl != actsrl)
1409                         continue;
1410                 if (FRS_is_freestyle_enabled(srl)) {
1411                         link->data = (void *)FRS_do_stroke_rendering(re, srl);
1412                 }
1413         }
1414
1415         FRS_finish_stroke_rendering(re);
1416 }
1417
1418 /* merges the results of Freestyle stroke rendering into a given render result */
1419 static void composite_freestyle_renders(Render *re, int sample)
1420 {
1421         Render *freestyle_render;
1422         SceneRenderLayer *srl, *actsrl;
1423         LinkData *link;
1424
1425         actsrl = BLI_findlink(&re->r.layers, re->r.actlay);
1426
1427         link = (LinkData *)re->freestyle_renders.first;
1428         for (srl= (SceneRenderLayer *)re->r.layers.first; srl; srl= srl->next) {
1429                 if ((re->r.scemode & R_SINGLE_LAYER) && srl != actsrl)
1430                         continue;
1431                 if (FRS_is_freestyle_enabled(srl)) {
1432                         freestyle_render = (Render *)link->data;
1433                         render_result_exr_file_read(freestyle_render, sample);
1434                         FRS_composite_result(re, srl, freestyle_render);
1435                         RE_FreeRenderResult(freestyle_render->result);
1436                         freestyle_render->result = NULL;
1437                 }
1438                 link = link->next;
1439         }
1440 }
1441
1442 /* releases temporary scenes and renders for Freestyle stroke rendering */
1443 static void free_all_freestyle_renders(Scene *scene)
1444 {
1445         Render *re1, *freestyle_render;
1446         LinkData *link;
1447
1448         for (re1= RenderGlobal.renderlist.first; re1; re1= re1->next) {
1449                 for (link = (LinkData *)re1->freestyle_renders.first; link; link = link->next) {
1450                         if (link->data) {
1451                                 freestyle_render = (Render *)link->data;
1452                                 BKE_scene_unlink(G.main, freestyle_render->scene, scene);
1453                                 RE_FreeRender(freestyle_render);
1454                         }
1455                 }
1456                 BLI_freelistN( &re1->freestyle_renders );
1457         }
1458 }
1459
1460
1461 /* reads all buffers, calls optional composite, merges in first result->rectf */
1462 static void do_merge_fullsample(Render *re, bNodeTree *ntree)
1463 {
1464         float *rectf, filt[3][3];
1465         int sample;
1466         
1467         /* interaction callbacks */
1468         if (ntree) {
1469                 ntree->stats_draw = render_composit_stats;
1470                 ntree->test_break = re->test_break;
1471                 ntree->progress = re->progress;
1472                 ntree->sdh = re->sdh;
1473                 ntree->tbh = re->tbh;
1474                 ntree->prh = re->prh;
1475         }
1476         
1477         /* filtmask needs it */
1478         R = *re;
1479         
1480         /* we accumulate in here */
1481         rectf = MEM_mapallocN(re->rectx * re->recty * sizeof(float) * 4, "fullsample rgba");
1482         
1483         for (sample = 0; sample < re->r.osa; sample++) {
1484                 Render *re1;
1485                 RenderResult rres;
1486                 int x, y, mask;
1487                 
1488                 /* enable full sample print */
1489                 R.i.curfsa = sample + 1;
1490                 
1491                 /* set all involved renders on the samplebuffers (first was done by render itself, but needs tagged) */
1492                 /* also function below assumes this */
1493                         
1494                 tag_scenes_for_render(re);
1495                 for (re1 = RenderGlobal.renderlist.first; re1; re1 = re1->next) {
1496                         if (re1->scene->id.flag & LIB_DOIT) {
1497                                 if (re1->r.scemode & R_FULL_SAMPLE) {
1498                                         if (sample) {
1499                                                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1500                                                 render_result_exr_file_read(re1, sample);
1501                                                 if( re1->r.mode & R_EDGE_FRS)
1502                                                         composite_freestyle_renders(re1, sample);
1503                                                 BLI_rw_mutex_unlock(&re->resultmutex);
1504                                         }
1505                                         ntreeCompositTagRender(re1->scene); /* ensure node gets exec to put buffers on stack */
1506                                 }
1507                         }
1508                 }
1509                 
1510                 /* composite */
1511                 if (ntree) {
1512                         ntreeCompositTagRender(re->scene);
1513                         ntreeCompositTagAnimated(ntree);
1514                         
1515                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0);
1516                 }
1517                 
1518                 /* ensure we get either composited result or the active layer */
1519                 RE_AcquireResultImage(re, &rres);
1520                 
1521                 /* accumulate with filter, and clip */
1522                 mask = (1 << sample);
1523                 mask_array(mask, filt);
1524
1525                 for (y = 0; y < re->recty; y++) {
1526                         float *rf = rectf + 4 * y * re->rectx;
1527                         float *col = rres.rectf + 4 * y * re->rectx;
1528                                 
1529                         for (x = 0; x < re->rectx; x++, rf += 4, col += 4) {
1530                                 /* clamping to 1.0 is needed for correct AA */
1531                                 if (col[0] < 0.0f) col[0] = 0.0f; else if (col[0] > 1.0f) col[0] = 1.0f;
1532                                 if (col[1] < 0.0f) col[1] = 0.0f; else if (col[1] > 1.0f) col[1] = 1.0f;
1533                                 if (col[2] < 0.0f) col[2] = 0.0f; else if (col[2] > 1.0f) col[2] = 1.0f;
1534                                 
1535                                 add_filt_fmask_coord(filt, col, rf, re->rectx, re->recty, x, y);
1536                         }
1537                 }
1538                 
1539                 RE_ReleaseResultImage(re);
1540
1541                 /* show stuff */
1542                 if (sample != re->osa - 1) {
1543                         /* weak... the display callback wants an active renderlayer pointer... */
1544                         re->result->renlay = render_get_active_layer(re, re->result);
1545                         re->display_draw(re->ddh, re->result, NULL);
1546                 }
1547                 
1548                 if (re->test_break(re->tbh))
1549                         break;
1550         }
1551         
1552         /* clear interaction callbacks */
1553         if (ntree) {
1554                 ntree->stats_draw = NULL;
1555                 ntree->test_break = NULL;
1556                 ntree->progress = NULL;
1557                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1558         }
1559         
1560         /* disable full sample print */
1561         R.i.curfsa = 0;
1562         
1563         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1564         if (re->result->rectf)
1565                 MEM_freeN(re->result->rectf);
1566         re->result->rectf = rectf;
1567         BLI_rw_mutex_unlock(&re->resultmutex);
1568 }
1569
1570 /* called externally, via compositor */
1571 void RE_MergeFullSample(Render *re, Main *bmain, Scene *sce, bNodeTree *ntree)
1572 {
1573         Scene *scene;
1574         bNode *node;
1575
1576         /* default start situation */
1577         G.afbreek = 0;
1578         
1579         re->main = bmain;
1580         re->scene = sce;
1581         
1582         /* first call RE_ReadRenderResult on every renderlayer scene. this creates Render structs */
1583         
1584         /* tag scenes unread */
1585         for (scene = re->main->scene.first; scene; scene = scene->id.next)
1586                 scene->id.flag |= LIB_DOIT;
1587         
1588         for (node = ntree->nodes.first; node; node = node->next) {
1589                 if (node->type == CMP_NODE_R_LAYERS) {
1590                         Scene *nodescene = (Scene *)node->id;
1591                         
1592                         if (nodescene == NULL) nodescene = sce;
1593                         if (nodescene->id.flag & LIB_DOIT) {
1594                                 nodescene->r.mode |= R_OSA; /* render struct needs tables */
1595                                 RE_ReadRenderResult(sce, nodescene);
1596                                 nodescene->id.flag &= ~LIB_DOIT;
1597                         }
1598                 }
1599         }
1600         
1601         /* own render result should be read/allocated */
1602         if (re->scene->id.flag & LIB_DOIT) {
1603                 RE_ReadRenderResult(re->scene, re->scene);
1604                 re->scene->id.flag &= ~LIB_DOIT;
1605         }
1606         
1607         /* and now we can draw (result is there) */
1608         re->display_init(re->dih, re->result);
1609         re->display_clear(re->dch, re->result);
1610         
1611         do_merge_fullsample(re, ntree);
1612 }
1613
1614 /* returns fully composited render-result on given time step (in RenderData) */
1615 static void do_render_composite_fields_blur_3d(Render *re)
1616 {
1617         bNodeTree *ntree = re->scene->nodetree;
1618         int update_newframe = 0;
1619         
1620         /* INIT seeding, compositor can use random texture */
1621         BLI_srandom(re->r.cfra);
1622         
1623         if (composite_needs_render(re->scene, 1)) {
1624                 /* save memory... free all cached images */
1625                 ntreeFreeCache(ntree);
1626                 
1627                 do_render_fields_blur_3d(re);
1628         } 
1629         else {
1630                 /* ensure new result gets added, like for regular renders */
1631                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1632                 
1633                 render_result_free(re->result);
1634                 re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM);
1635
1636                 BLI_rw_mutex_unlock(&re->resultmutex);
1637                 
1638                 /* scene render process already updates animsys */
1639                 update_newframe = 1;
1640         }
1641         
1642         /* swap render result */
1643         if (re->r.scemode & R_SINGLE_LAYER) {
1644                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1645                 render_result_single_layer_end(re);
1646                 BLI_rw_mutex_unlock(&re->resultmutex);
1647         }
1648         
1649         if (!re->test_break(re->tbh)) {
1650                 
1651                 if (ntree) {
1652                         ntreeCompositTagRender(re->scene);
1653                         ntreeCompositTagAnimated(ntree);
1654                 }
1655                 
1656                 if (ntree && re->scene->use_nodes && re->r.scemode & R_DOCOMP) {
1657                         /* checks if there are render-result nodes that need scene */
1658                         if ((re->r.scemode & R_SINGLE_LAYER) == 0)
1659                                 ntree_render_scenes(re);
1660                         
1661                         if (!re->test_break(re->tbh)) {
1662                                 ntree->stats_draw = render_composit_stats;
1663                                 ntree->test_break = re->test_break;
1664                                 ntree->progress = re->progress;
1665                                 ntree->sdh = re->sdh;
1666                                 ntree->tbh = re->tbh;
1667                                 ntree->prh = re->prh;
1668                                 
1669                                 /* in case it was never initialized */
1670                                 R.sdh = re->sdh;
1671                                 R.stats_draw = re->stats_draw;
1672                                 
1673                                 if (update_newframe)
1674                                         BKE_scene_update_for_newframe(re->main, re->scene, re->lay);
1675                                 
1676                                 if (re->r.scemode & R_FULL_SAMPLE)
1677                                         do_merge_fullsample(re, ntree);
1678                                 else {
1679                                         ntreeCompositExecTree(ntree, &re->r, 1, G.background == 0);
1680                                 }
1681                                 
1682                                 ntree->stats_draw = NULL;
1683                                 ntree->test_break = NULL;
1684                                 ntree->progress = NULL;
1685                                 ntree->tbh = ntree->sdh = ntree->prh = NULL;
1686                         }
1687                 }
1688                 else if (re->r.scemode & R_FULL_SAMPLE)
1689                         do_merge_fullsample(re, NULL);
1690         }
1691
1692         free_all_freestyle_renders(re->scene);
1693
1694         /* weak... the display callback wants an active renderlayer pointer... */
1695         re->result->renlay = render_get_active_layer(re, re->result);
1696         re->display_draw(re->ddh, re->result, NULL);
1697 }
1698
1699 static void renderresult_stampinfo(Render *re)
1700 {
1701         RenderResult rres;
1702
1703         /* this is the basic trick to get the displayed float or char rect from render result */
1704         RE_AcquireResultImage(re, &rres);
1705         BKE_stamp_buf(re->scene, RE_GetCamera(re), (unsigned char *)rres.rect32, rres.rectf, rres.rectx, rres.recty, 4);
1706         RE_ReleaseResultImage(re);
1707 }
1708
1709 int RE_seq_render_active(Scene *scene, RenderData *rd)
1710 {
1711         Editing *ed;
1712         Sequence *seq;
1713
1714         ed = scene->ed;
1715         
1716         if (!(rd->scemode & R_DOSEQ) || !ed || !ed->seqbase.first)
1717                 return 0;
1718         
1719         for (seq = ed->seqbase.first; seq; seq = seq->next) {
1720                 if (seq->type != SEQ_TYPE_SOUND_RAM)
1721                         return 1;
1722         }
1723         
1724         return 0;
1725 }
1726
1727 static void do_render_seq(Render *re)
1728 {
1729         static int recurs_depth = 0;
1730         struct ImBuf *ibuf;
1731         RenderResult *rr; /* don't assign re->result here as it might change during give_ibuf_seq */
1732         int cfra = re->r.cfra;
1733         SeqRenderData context;
1734
1735         re->i.cfra = cfra;
1736
1737         if (recurs_depth == 0) {
1738                 /* otherwise sequencer animation isn't updated */
1739                 BKE_animsys_evaluate_all_animation(re->main, re->scene, (float)cfra); // XXX, was BKE_scene_frame_get(re->scene)
1740         }
1741
1742         recurs_depth++;
1743
1744         if ((re->r.mode & R_BORDER) && (re->r.mode & R_CROP) == 0) {
1745                 /* if border rendering is used and cropping is disabled, final buffer should
1746                  * be as large as the whole frame */
1747                 context = seq_new_render_data(re->main, re->scene,
1748                                               re->winx, re->winy,
1749                                               100);
1750         }
1751         else {
1752                 context = seq_new_render_data(re->main, re->scene,
1753                                               re->result->rectx, re->result->recty,
1754                                               100);
1755         }
1756
1757         ibuf = give_ibuf_seq(context, cfra, 0);
1758
1759         recurs_depth--;
1760
1761         rr = re->result;
1762         
1763         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
1764
1765         if (ibuf) {
1766                 /* copy ibuf into combined pixel rect */
1767                 render_result_rect_from_ibuf(rr, &re->r, ibuf);
1768                 
1769                 if (recurs_depth == 0) { /* with nested scenes, only free on toplevel... */
1770                         Editing *ed = re->scene->ed;
1771                         if (ed)
1772                                 free_imbuf_seq(re->scene, &ed->seqbase, TRUE, TRUE);
1773                 }
1774                 IMB_freeImBuf(ibuf);
1775         }
1776         else {
1777                 /* render result is delivered empty in most cases, nevertheless we handle all cases */
1778                 render_result_rect_fill_zero(rr);
1779         }
1780
1781         BLI_rw_mutex_unlock(&re->resultmutex);
1782
1783         /* just in case this flag went missing at some point */
1784         re->r.scemode |= R_DOSEQ;
1785
1786         /* set overall progress of sequence rendering */
1787         if (re->r.efra != re->r.sfra)
1788                 re->progress(re->prh, (float)(cfra - re->r.sfra) / (re->r.efra - re->r.sfra));
1789         else
1790                 re->progress(re->prh, 1.0f);
1791 }
1792
1793 /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
1794
1795 /* main loop: doing sequence + fields + blur + 3d render + compositing */
1796 static void do_render_all_options(Render *re)
1797 {
1798         BKE_scene_camera_switch_update(re->scene);
1799
1800         re->i.starttime = PIL_check_seconds_timer();
1801
1802         /* ensure no images are in memory from previous animated sequences */
1803         BKE_image_all_free_anim_ibufs(re->r.cfra);
1804
1805         if (RE_engine_render(re, 1)) {
1806                 /* in this case external render overrides all */
1807         }
1808         else if (RE_seq_render_active(re->scene, &re->r)) {
1809                 /* note: do_render_seq() frees rect32 when sequencer returns float images */
1810                 if (!re->test_break(re->tbh))
1811                         do_render_seq(re);
1812                 
1813                 re->stats_draw(re->sdh, &re->i);
1814                 re->display_draw(re->ddh, re->result, NULL);
1815         }
1816         else {
1817                 do_render_composite_fields_blur_3d(re);
1818         }
1819         
1820         re->i.lastframetime = PIL_check_seconds_timer() - re->i.starttime;
1821         
1822         re->stats_draw(re->sdh, &re->i);
1823         
1824         /* stamp image info here */
1825         if ((re->r.stamp & R_STAMP_ALL) && (re->r.stamp & R_STAMP_DRAW)) {
1826                 renderresult_stampinfo(re);
1827                 re->display_draw(re->ddh, re->result, NULL);
1828         }
1829 }
1830
1831 static int check_valid_camera(Scene *scene, Object *camera_override)
1832 {
1833         int check_comp = 1;
1834
1835         if (camera_override == NULL && scene->camera == NULL)
1836                 scene->camera = BKE_scene_camera_find(scene);
1837
1838         if (scene->r.scemode & R_DOSEQ) {
1839                 if (scene->ed) {
1840                         Sequence *seq = scene->ed->seqbase.first;
1841
1842                         check_comp = 0;
1843
1844                         while (seq) {
1845                                 if (seq->type == SEQ_TYPE_SCENE && seq->scene) {
1846                                         if (!seq->scene_camera) {
1847                                                 if (!seq->scene->camera && !BKE_scene_camera_find(seq->scene)) {
1848                                                         if (seq->scene == scene) {
1849                                                                 /* for current scene camera could be unneeded due to compisite nodes */
1850                                                                 check_comp = 1;
1851                                                         }
1852                                                         else {
1853                                                                 /* for other scenes camera is necessary */
1854                                                                 return 0;
1855                                                         }
1856                                                 }
1857                                         }
1858                                 }
1859
1860                                 seq = seq->next;
1861                         }
1862                 }
1863         }
1864
1865         if (check_comp) { /* no sequencer or sequencer depends on compositor */
1866                 if (scene->r.scemode & R_DOCOMP && scene->use_nodes) {
1867                         bNode *node = scene->nodetree->nodes.first;
1868
1869                         while (node) {
1870                                 if (node->type == CMP_NODE_R_LAYERS) {
1871                                         Scene *sce = node->id ? (Scene *)node->id : scene;
1872
1873                                         if (!sce->camera && !BKE_scene_camera_find(sce)) {
1874                                                 /* all render layers nodes need camera */
1875                                                 return 0;
1876                                         }
1877                                 }
1878
1879                                 node = node->next;
1880                         }
1881                 }
1882                 else {
1883                         return (camera_override != NULL || scene->camera != NULL);
1884                 }
1885         }
1886
1887         return 1;
1888 }
1889
1890 static int node_tree_has_composite_output(bNodeTree *ntree)
1891 {
1892         bNode *node;
1893
1894         for (node = ntree->nodes.first; node; node = node->next) {
1895                 if (node->type == CMP_NODE_COMPOSITE) {
1896                         return TRUE;
1897                 }
1898                 else if (node->type == NODE_GROUP) {
1899                         if (node_tree_has_composite_output((bNodeTree *)node->id))
1900                                 return TRUE;
1901                 }
1902         }
1903
1904         return FALSE;
1905 }
1906
1907 static int check_composite_output(Scene *scene)
1908 {
1909         return node_tree_has_composite_output(scene->nodetree);
1910 }
1911
1912 int RE_is_rendering_allowed(Scene *scene, Object *camera_override, ReportList *reports)
1913 {
1914         SceneRenderLayer *srl;
1915         
1916         if (scene->r.mode & R_BORDER) {
1917                 if (scene->r.border.xmax <= scene->r.border.xmin ||
1918                     scene->r.border.ymax <= scene->r.border.ymin)
1919                 {
1920                         BKE_report(reports, RPT_ERROR, "No border area selected.");
1921                         return 0;
1922                 }
1923         }
1924         
1925         if (scene->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
1926                 char str[FILE_MAX];
1927                 
1928                 render_result_exr_file_path(scene, 0, str);
1929                 
1930                 if (BLI_file_is_writable(str) == 0) {
1931                         BKE_report(reports, RPT_ERROR, "Can not save render buffers, check the temp default path");
1932                         return 0;
1933                 }
1934                 
1935                 /* no fullsample and edge */
1936                 if ((scene->r.scemode & R_FULL_SAMPLE) && (scene->r.mode & R_EDGE)) {
1937                         BKE_report(reports, RPT_ERROR, "Full Sample doesn't support Edge Enhance");
1938                         return 0;
1939                 }
1940                 
1941         }
1942         else
1943                 scene->r.scemode &= ~R_FULL_SAMPLE;  /* clear to be sure */
1944         
1945         if (scene->r.scemode & R_DOCOMP) {
1946                 if (scene->use_nodes) {
1947                         if (!scene->nodetree) {
1948                                 BKE_report(reports, RPT_ERROR, "No Nodetree in Scene");
1949                                 return 0;
1950                         }
1951                         
1952                         if (!check_composite_output(scene)) {
1953                                 BKE_report(reports, RPT_ERROR, "No Render Output Node in Scene");
1954                                 return 0;
1955                         }
1956                         
1957                         if (scene->r.scemode & R_FULL_SAMPLE) {
1958                                 if (composite_needs_render(scene, 0) == 0) {
1959                                         BKE_report(reports, RPT_ERROR, "Full Sample AA not supported without 3d rendering");
1960                                         return 0;
1961                                 }
1962                         }
1963                 }
1964         }
1965         
1966         /* check valid camera, without camera render is OK (compo, seq) */
1967         if (!check_valid_camera(scene, camera_override)) {
1968                 BKE_report(reports, RPT_ERROR, "No camera");
1969                 return 0;
1970         }
1971         
1972         /* get panorama & ortho, only after camera is set */
1973         BKE_camera_object_mode(&scene->r, camera_override ? camera_override : scene->camera);
1974
1975         /* forbidden combinations */
1976         if (scene->r.mode & R_PANORAMA) {
1977                 if (scene->r.mode & R_ORTHO) {
1978                         BKE_report(reports, RPT_ERROR, "No Ortho render possible for Panorama");
1979                         return 0;
1980                 }
1981         }
1982
1983         /* layer flag tests */
1984         if (scene->r.scemode & R_SINGLE_LAYER) {
1985                 srl = BLI_findlink(&scene->r.layers, scene->r.actlay);
1986                 /* force layer to be enabled */
1987                 srl->layflag &= ~SCE_LAY_DISABLE;
1988         }
1989         
1990         for (srl = scene->r.layers.first; srl; srl = srl->next)
1991                 if (!(srl->layflag & SCE_LAY_DISABLE))
1992                         break;
1993         if (srl == NULL) {
1994                 BKE_report(reports, RPT_ERROR, "All RenderLayers are disabled");
1995                 return 0;
1996         }
1997
1998         return 1;
1999 }
2000
2001 static void validate_render_settings(Render *re)
2002 {
2003         if (re->r.scemode & (R_EXR_TILE_FILE | R_FULL_SAMPLE)) {
2004                 /* no osa + fullsample won't work... */
2005                 if (re->r.osa == 0)
2006                         re->r.scemode &= ~R_FULL_SAMPLE;
2007         }
2008         else re->r.scemode &= ~R_FULL_SAMPLE;   /* clear to be sure */
2009
2010         if (RE_engine_is_external(re)) {
2011                 /* not supported yet */
2012                 re->r.scemode &= ~(R_EXR_TILE_FILE | R_FULL_SAMPLE);
2013                 re->r.mode &= ~(R_FIELDS | R_MBLUR);
2014         }
2015 }
2016
2017 static void update_physics_cache(Render *re, Scene *scene, int UNUSED(anim_init))
2018 {
2019         PTCacheBaker baker;
2020
2021         baker.main = re->main;
2022         baker.scene = scene;
2023         baker.pid = NULL;
2024         baker.bake = 0;
2025         baker.render = 1;
2026         baker.anim_init = 1;
2027         baker.quick_step = 1;
2028         baker.break_test = re->test_break;
2029         baker.break_data = re->tbh;
2030         baker.progressbar = NULL;
2031
2032         BKE_ptcache_bake(&baker);
2033 }
2034 /* evaluating scene options for general Blender render */
2035 static int render_initialize_from_main(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int anim, int anim_init)
2036 {
2037         int winx, winy;
2038         rcti disprect;
2039         
2040         /* r.xsch and r.ysch has the actual view window size
2041          * r.border is the clipping rect */
2042         
2043         /* calculate actual render result and display size */
2044         winx = (scene->r.size * scene->r.xsch) / 100;
2045         winy = (scene->r.size * scene->r.ysch) / 100;
2046         
2047         /* we always render smaller part, inserting it in larger image is compositor bizz, it uses disprect for it */
2048         if (scene->r.mode & R_BORDER) {
2049                 disprect.xmin = scene->r.border.xmin * winx;
2050                 disprect.xmax = scene->r.border.xmax * winx;
2051                 
2052                 disprect.ymin = scene->r.border.ymin * winy;
2053                 disprect.ymax = scene->r.border.ymax * winy;
2054         }
2055         else {
2056                 disprect.xmin = disprect.ymin = 0;
2057                 disprect.xmax = winx;
2058                 disprect.ymax = winy;
2059         }
2060         
2061         re->main = bmain;
2062         re->scene = scene;
2063         re->camera_override = camera_override;
2064         re->lay = lay;
2065         
2066         /* not too nice, but it survives anim-border render */
2067         if (anim) {
2068                 re->disprect = disprect;
2069                 return 1;
2070         }
2071         
2072         /* check all scenes involved */
2073         tag_scenes_for_render(re);
2074
2075         /*
2076          * Disabled completely for now,
2077          * can be later set as render profile option
2078          * and default for background render.
2079          */
2080         if (0) {
2081                 /* make sure dynamics are up to date */
2082                 update_physics_cache(re, scene, anim_init);
2083         }
2084         
2085         if (srl || scene->r.scemode & R_SINGLE_LAYER) {
2086                 BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2087                 render_result_single_layer_begin(re);
2088                 BLI_rw_mutex_unlock(&re->resultmutex);
2089         }
2090         
2091         RE_InitState(re, NULL, &scene->r, srl, winx, winy, &disprect);
2092         if (!re->ok)  /* if an error was printed, abort */
2093                 return 0;
2094         
2095         /* initstate makes new result, have to send changed tags around */
2096         ntreeCompositTagRender(re->scene);
2097
2098         validate_render_settings(re);
2099
2100         re->display_init(re->dih, re->result);
2101         re->display_clear(re->dch, re->result);
2102         
2103         return 1;
2104 }
2105
2106 void RE_SetReports(Render *re, ReportList *reports)
2107 {
2108         re->reports = reports;
2109 }
2110
2111 /* general Blender frame render call */
2112 void RE_BlenderFrame(Render *re, Main *bmain, Scene *scene, SceneRenderLayer *srl, Object *camera_override, unsigned int lay, int frame, const short write_still)
2113 {
2114         /* ugly global still... is to prevent preview events and signal subsurfs etc to make full resol */
2115         G.rendering = 1;
2116         
2117         scene->r.cfra = frame;
2118         
2119         if (render_initialize_from_main(re, bmain, scene, srl, camera_override, lay, 0, 0)) {
2120                 MEM_reset_peak_memory();
2121
2122                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2123
2124                 do_render_all_options(re);
2125                 
2126                 if (write_still && !G.afbreek) {
2127                         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2128                                 /* operator checks this but in case its called from elsewhere */
2129                                 printf("Error: cant write single images with a movie format!\n");
2130                         }
2131                         else {
2132                                 char name[FILE_MAX];
2133                                 BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, FALSE);
2134
2135                                 /* reports only used for Movie */
2136                                 do_write_image_or_movie(re, bmain, scene, NULL, name);
2137                         }
2138                 }
2139
2140                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2141         }
2142
2143         BLI_callback_exec(re->main, (ID *)scene, G.afbreek ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2144
2145         /* UGLY WARNING */
2146         G.rendering = 0;
2147 }
2148
2149 void RE_RenderFreestyleStrokes(Render *re, Main *bmain, Scene *scene)
2150 {
2151         re->result_ok= 0;
2152         if(render_initialize_from_main(re, bmain, scene, NULL, NULL, scene->lay, 0, 0)) {
2153                 do_render_fields_blur_3d(re);
2154         }
2155         re->result_ok= 1;
2156 }
2157
2158 static int do_write_image_or_movie(Render *re, Main *bmain, Scene *scene, bMovieHandle *mh, const char *name_override)
2159 {
2160         char name[FILE_MAX];
2161         RenderResult rres;
2162         Object *camera = RE_GetCamera(re);
2163         int ok = 1;
2164         
2165         RE_AcquireResultImage(re, &rres);
2166
2167         /* write movie or image */
2168         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
2169                 int do_free = FALSE;
2170                 unsigned int *rect32 = (unsigned int *)rres.rect32;
2171                 /* note; the way it gets 32 bits rects is weak... */
2172                 if (rres.rect32 == NULL) {
2173                         rect32 = MEM_mapallocN(sizeof(int) * rres.rectx * rres.recty, "temp 32 bits rect");
2174                         RE_ResultGet32(re, rect32);
2175                         do_free = TRUE;
2176                 }
2177
2178                 ok = mh->append_movie(&re->r, scene->r.sfra, scene->r.cfra, (int *)rect32,
2179                                       rres.rectx, rres.recty, re->reports);
2180                 if (do_free) {
2181                         MEM_freeN(rect32);
2182                 }
2183                 printf("Append frame %d", scene->r.cfra);
2184         } 
2185         else {
2186                 if (name_override)
2187                         BLI_strncpy(name, name_override, sizeof(name));
2188                 else
2189                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, TRUE);
2190                 
2191                 if (re->r.im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
2192                         if (re->result) {
2193                                 RE_WriteRenderResult(re->reports, re->result, name, scene->r.im_format.exr_codec);
2194                                 printf("Saved: %s", name);
2195                         }
2196                 }
2197                 else {
2198                         ImBuf *ibuf = render_result_rect_to_ibuf(&rres, &scene->r);
2199
2200                         ok = BKE_imbuf_write_stamp(scene, camera, ibuf, name, &scene->r.im_format);
2201                         
2202                         if (ok == 0) {
2203                                 printf("Render error: cannot save %s\n", name);
2204                         }
2205                         else printf("Saved: %s", name);
2206                         
2207                         /* optional preview images for exr */
2208                         if (ok && scene->r.im_format.imtype == R_IMF_IMTYPE_OPENEXR && (scene->r.im_format.flag & R_IMF_FLAG_PREVIEW_JPG)) {
2209                                 ImageFormatData imf = scene->r.im_format;
2210                                 imf.imtype = R_IMF_IMTYPE_JPEG90;
2211
2212                                 if (BLI_testextensie(name, ".exr"))
2213                                         name[strlen(name) - 4] = 0;
2214                                 BKE_add_image_extension(name, R_IMF_IMTYPE_JPEG90);
2215                                 ibuf->planes = 24;
2216                                 BKE_imbuf_write_stamp(scene, camera, ibuf, name, &imf);
2217                                 printf("\nSaved: %s", name);
2218                         }
2219                         
2220                         /* imbuf knows which rects are not part of ibuf */
2221                         IMB_freeImBuf(ibuf);
2222                 }
2223         }
2224         
2225         RE_ReleaseResultImage(re);
2226
2227         BLI_timestr(re->i.lastframetime, name);
2228         printf(" Time: %s", name);
2229
2230         BLI_callback_exec(G.main, NULL, BLI_CB_EVT_RENDER_STATS);
2231
2232         fputc('\n', stdout);
2233         fflush(stdout); /* needed for renderd !! (not anymore... (ton)) */
2234
2235         return ok;
2236 }
2237
2238 /* saves images to disk */
2239 void RE_BlenderAnim(Render *re, Main *bmain, Scene *scene, Object *camera_override, unsigned int lay, int sfra, int efra, int tfra)
2240 {
2241         bMovieHandle *mh = BKE_movie_handle_get(scene->r.im_format.imtype);
2242         int cfrao = scene->r.cfra;
2243         int nfra, totrendered = 0, totskipped = 0;
2244         
2245         /* do not fully call for each frame, it initializes & pops output window */
2246         if (!render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 0, 1))
2247                 return;
2248         
2249         /* ugly global still... is to prevent renderwin events and signal subsurfs etc to make full resol */
2250         /* is also set by caller renderwin.c */
2251         G.rendering = 1;
2252
2253         re->flag |= R_ANIMATION;
2254
2255         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2256                 if (!mh->start_movie(scene, &re->r, re->rectx, re->recty, re->reports))
2257                         G.afbreek = 1;
2258
2259         if (mh->get_next_frame) {
2260                 while (!(G.afbreek == 1)) {
2261                         int nf = mh->get_next_frame(&re->r, re->reports);
2262                         if (nf >= 0 && nf >= scene->r.sfra && nf <= scene->r.efra) {
2263                                 scene->r.cfra = re->r.cfra = nf;
2264
2265                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2266
2267                                 do_render_all_options(re);
2268                                 totrendered++;
2269
2270                                 if (re->test_break(re->tbh) == 0) {
2271                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2272                                                 G.afbreek = 1;
2273                                 }
2274
2275                                 if (G.afbreek == 0) {
2276                                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2277                                 }
2278                         }
2279                         else {
2280                                 if (re->test_break(re->tbh))
2281                                         G.afbreek = 1;
2282                         }
2283                 }
2284         }
2285         else {
2286                 for (nfra = sfra, scene->r.cfra = sfra; scene->r.cfra <= efra; scene->r.cfra++) {
2287                         char name[FILE_MAX];
2288                         
2289                         /* only border now, todo: camera lens. (ton) */
2290                         render_initialize_from_main(re, bmain, scene, NULL, camera_override, lay, 1, 0);
2291
2292                         if (nfra != scene->r.cfra) {
2293                                 /*
2294                                  * Skip this frame, but update for physics and particles system.
2295                                  * From convertblender.c:
2296                                  * in localview, lamps are using normal layers, objects only local bits.
2297                                  */
2298                                 unsigned int updatelay;
2299
2300                                 if (re->lay & 0xFF000000)
2301                                         updatelay = re->lay & 0xFF000000;
2302                                 else
2303                                         updatelay = re->lay;
2304
2305                                 BKE_scene_update_for_newframe(bmain, scene, updatelay);
2306                                 continue;
2307                         }
2308                         else
2309                                 nfra += tfra;
2310
2311                         /* Touch/NoOverwrite options are only valid for image's */
2312                         if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2313                                 if (scene->r.mode & (R_NO_OVERWRITE | R_TOUCH))
2314                                         BKE_makepicstring(name, scene->r.pic, bmain->name, scene->r.cfra, scene->r.im_format.imtype, scene->r.scemode & R_EXTENSION, TRUE);
2315
2316                                 if (scene->r.mode & R_NO_OVERWRITE && BLI_exists(name)) {
2317                                         printf("skipping existing frame \"%s\"\n", name);
2318                                         totskipped++;
2319                                         continue;
2320                                 }
2321                                 if (scene->r.mode & R_TOUCH && !BLI_exists(name)) {
2322                                         BLI_make_existing_file(name); /* makes the dir if its not there */
2323                                         BLI_file_touch(name);
2324                                 }
2325                         }
2326
2327                         re->r.cfra = scene->r.cfra;     /* weak.... */
2328
2329                         /* run callbacs before rendering, before the scene is updated */
2330                         BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_PRE);
2331
2332                         
2333                         do_render_all_options(re);
2334                         totrendered++;
2335                         
2336                         if (re->test_break(re->tbh) == 0) {
2337                                 if (!G.afbreek)
2338                                         if (!do_write_image_or_movie(re, bmain, scene, mh, NULL))
2339                                                 G.afbreek = 1;
2340                         }
2341                         else
2342                                 G.afbreek = 1;
2343                 
2344                         if (G.afbreek == 1) {
2345                                 /* remove touched file */
2346                                 if (BKE_imtype_is_movie(scene->r.im_format.imtype) == 0) {
2347                                         if (scene->r.mode & R_TOUCH && BLI_exists(name) && BLI_file_size(name) == 0) {
2348                                                 BLI_delete(name, 0, 0);
2349                                         }
2350                                 }
2351                                 
2352                                 break;
2353                         }
2354
2355                         if (G.afbreek == 0) {
2356                                 BLI_callback_exec(re->main, (ID *)scene, BLI_CB_EVT_RENDER_POST); /* keep after file save */
2357                         }
2358                 }
2359         }
2360         
2361         /* end movie */
2362         if (BKE_imtype_is_movie(scene->r.im_format.imtype))
2363                 mh->end_movie();
2364         
2365         if (totskipped && totrendered == 0)
2366                 BKE_report(re->reports, RPT_INFO, "No frames rendered, skipped to not overwrite");
2367
2368         scene->r.cfra = cfrao;
2369
2370         re->flag &= ~R_ANIMATION;
2371
2372         BLI_callback_exec(re->main, (ID *)scene, G.afbreek ? BLI_CB_EVT_RENDER_CANCEL : BLI_CB_EVT_RENDER_COMPLETE);
2373
2374         /* UGLY WARNING */
2375         G.rendering = 0;
2376 }
2377
2378 void RE_PreviewRender(Render *re, Main *bmain, Scene *sce)
2379 {
2380         Object *camera;
2381         int winx, winy;
2382
2383         winx = (sce->r.size * sce->r.xsch) / 100;
2384         winy = (sce->r.size * sce->r.ysch) / 100;
2385
2386         RE_InitState(re, NULL, &sce->r, NULL, winx, winy, NULL);
2387
2388         re->main = bmain;
2389         re->scene = sce;
2390         re->lay = sce->lay;
2391
2392         camera = RE_GetCamera(re);
2393         RE_SetCamera(re, camera);
2394
2395         do_render_3d(re);
2396 }
2397
2398 /* note; repeated win/disprect calc... solve that nicer, also in compo */
2399
2400 /* only the temp file! */
2401 int RE_ReadRenderResult(Scene *scene, Scene *scenode)
2402 {
2403         Render *re;
2404         int winx, winy, success;
2405         rcti disprect;
2406         
2407         /* calculate actual render result and display size */
2408         winx = (scene->r.size * scene->r.xsch) / 100;
2409         winy = (scene->r.size * scene->r.ysch) / 100;
2410         
2411         /* only in movie case we render smaller part */
2412         if (scene->r.mode & R_BORDER) {
2413                 disprect.xmin = scene->r.border.xmin * winx;
2414                 disprect.xmax = scene->r.border.xmax * winx;
2415                 
2416                 disprect.ymin = scene->r.border.ymin * winy;
2417                 disprect.ymax = scene->r.border.ymax * winy;
2418         }
2419         else {
2420                 disprect.xmin = disprect.ymin = 0;
2421                 disprect.xmax = winx;
2422                 disprect.ymax = winy;
2423         }
2424         
2425         if (scenode)
2426                 scene = scenode;
2427         
2428         /* get render: it can be called from UI with draw callbacks */
2429         re = RE_GetRender(scene->id.name);
2430         if (re == NULL)
2431                 re = RE_NewRender(scene->id.name);
2432         RE_InitState(re, NULL, &scene->r, NULL, winx, winy, &disprect);
2433         re->scene = scene;
2434         
2435         BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
2436         success = render_result_exr_file_read(re, 0);
2437         BLI_rw_mutex_unlock(&re->resultmutex);
2438
2439         return success;
2440 }
2441
2442 void RE_set_max_threads(int threads)
2443 {
2444         if (threads == 0) {
2445                 RenderGlobal.threads = BLI_system_thread_count();
2446         }
2447         else if (threads >= 1 && threads <= BLENDER_MAX_THREADS) {
2448                 RenderGlobal.threads = threads;
2449         }
2450         else {
2451                 printf("Error, threads has to be in range 0-%d\n", BLENDER_MAX_THREADS);
2452         }
2453 }
2454
2455 void RE_init_threadcount(Render *re) 
2456 {
2457         if (RenderGlobal.threads >= 1) { /* only set as an arg in background mode */
2458                 re->r.threads = MIN2(RenderGlobal.threads, BLENDER_MAX_THREADS);
2459         }
2460         else if ((re->r.mode & R_FIXED_THREADS) == 0 || RenderGlobal.threads == 0) { /* Automatic threads */
2461                 re->r.threads = BLI_system_thread_count();
2462         }
2463 }
2464
2465 /* loads in image into a result, size must match
2466  * x/y offsets are only used on a partial copy when dimensions don't match */
2467 void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, const char *filename, int x, int y)
2468 {
2469         ImBuf *ibuf = IMB_loadiffname(filename, IB_rect);
2470
2471         if (ibuf && (ibuf->rect || ibuf->rect_float)) {
2472                 if (ibuf->x == layer->rectx && ibuf->y == layer->recty) {
2473                         if (ibuf->rect_float == NULL)
2474                                 IMB_float_from_rect(ibuf);
2475
2476                         memcpy(layer->rectf, ibuf->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2477                 }
2478                 else {
2479                         if ((ibuf->x - x >= layer->rectx) && (ibuf->y - y >= layer->recty)) {
2480                                 ImBuf *ibuf_clip;
2481
2482                                 if (ibuf->rect_float == NULL)
2483                                         IMB_float_from_rect(ibuf);
2484
2485                                 ibuf_clip = IMB_allocImBuf(layer->rectx, layer->recty, 32, IB_rectfloat);
2486                                 if (ibuf_clip) {
2487                                         IMB_rectcpy(ibuf_clip, ibuf, 0, 0, x, y, layer->rectx, layer->recty);
2488
2489                                         memcpy(layer->rectf, ibuf_clip->rect_float, sizeof(float) * 4 * layer->rectx * layer->recty);
2490                                         IMB_freeImBuf(ibuf_clip);
2491                                 }
2492                                 else {
2493                                         BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to allocate clip buffer '%s'\n", filename);
2494                                 }
2495                         }
2496                         else {
2497                                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: incorrect dimensions for partial copy '%s'\n", filename);
2498                         }
2499                 }
2500
2501                 IMB_freeImBuf(ibuf);
2502         }
2503         else {
2504                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
2505         }
2506 }
2507
2508 void RE_result_load_from_file(RenderResult *result, ReportList *reports, const char *filename)
2509 {
2510         if (!render_result_exr_file_read_path(result, filename)) {
2511                 BKE_reportf(reports, RPT_ERROR, "RE_result_rect_from_file: failed to load '%s'\n", filename);
2512                 return;
2513         }
2514 }
2515
2516 const float default_envmap_layout[] = { 0, 0, 1, 0, 2, 0, 0, 1, 1, 1, 2, 1 };
2517
2518 int RE_WriteEnvmapResult(struct ReportList *reports, Scene *scene, EnvMap *env, const char *relpath, const char imtype, float layout[12])
2519 {
2520         ImageFormatData imf;
2521         ImBuf *ibuf = NULL;
2522         int ok;
2523         int dx;
2524         int maxX = 0, maxY = 0, i = 0;
2525         char filepath[FILE_MAX];
2526
2527         if (env->cube[1] == NULL) {
2528                 BKE_report(reports, RPT_ERROR, "There is no generated environment map available to save");
2529                 return 0;
2530         }
2531
2532         imf = scene->r.im_format;
2533         imf.imtype = imtype;
2534
2535         dx = env->cube[1]->x;
2536
2537         if (env->type == ENV_CUBE) {
2538                 for (i = 0; i < 12; i += 2) {
2539                         maxX = MAX2(maxX, layout[i] + 1);
2540                         maxY = MAX2(maxY, layout[i + 1] + 1);
2541                 }
2542
2543                 ibuf = IMB_allocImBuf(maxX * dx, maxY * dx, 24, IB_rectfloat);
2544
2545                 for (i = 0; i < 12; i += 2)
2546                         if (layout[i] > -1 && layout[i + 1] > -1)
2547                                 IMB_rectcpy(ibuf, env->cube[i / 2], layout[i] * dx, layout[i + 1] * dx, 0, 0, dx, dx);
2548         }
2549         else if (env->type == ENV_PLANE) {
2550                 ibuf = IMB_allocImBuf(dx, dx, 24, IB_rectfloat);
2551                 IMB_rectcpy(ibuf, env->cube[1], 0, 0, 0, 0, dx, dx);
2552         }
2553         else {
2554                 BKE_report(reports, RPT_ERROR, "Invalid environment map type");
2555                 return 0;
2556         }
2557
2558         if (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT)
2559                 ibuf->profile = IB_PROFILE_LINEAR_RGB;
2560
2561         /* to save, we first get absolute path */
2562         BLI_strncpy(filepath, relpath, sizeof(filepath));
2563         BLI_path_abs(filepath, G.main->name);
2564
2565         ok = BKE_imbuf_write(ibuf, filepath, &imf);
2566
2567         IMB_freeImBuf(ibuf);
2568
2569         if (ok) {
2570                 return TRUE;
2571         }
2572         else {
2573                 BKE_report(reports, RPT_ERROR, "Error writing environment map.");
2574                 return FALSE;
2575         }
2576 }
2577