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