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