Sequencer: Add option to render OpenGL preview with DoF
[blender-staging.git] / source / blender / editors / render / render_opengl.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) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/editors/render/render_opengl.c
26  *  \ingroup edrend
27  */
28
29
30 #include <math.h>
31 #include <string.h>
32 #include <stddef.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_camera_types.h"
37 #include "BLI_math.h"
38 #include "BLI_math_color_blend.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_utildefines.h"
41 #include "BLI_threads.h"
42 #include "BLI_task.h"
43
44 #include "DNA_scene_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_gpencil_types.h"
47
48 #include "BKE_camera.h"
49 #include "BKE_context.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_main.h"
53 #include "BKE_report.h"
54 #include "BKE_scene.h"
55 #include "BKE_sequencer.h"
56 #include "BKE_writeavi.h"
57
58 #include "WM_api.h"
59 #include "WM_types.h"
60
61 #include "ED_screen.h"
62 #include "ED_view3d.h"
63 #include "ED_gpencil.h"
64
65 #include "RE_pipeline.h"
66 #include "IMB_imbuf_types.h"
67 #include "IMB_imbuf.h"
68 #include "IMB_colormanagement.h"
69
70 #include "RNA_access.h"
71 #include "RNA_define.h"
72
73 #include "GPU_glew.h"
74 #include "GPU_compositing.h"
75 #include "GPU_framebuffer.h"
76
77 #include "render_intern.h"
78
79 /* Define this to get timing information. */
80 // #undef DEBUG_TIME
81
82 #ifdef DEBUG_TIME
83 #  include "PIL_time.h"
84 #endif
85
86 // TODO(sergey): Find better approximation of the scheduled frames.
87 // For really highres renders it might fail still.
88 #define MAX_SCHEDULED_FRAMES 8
89
90 typedef struct OGLRender {
91         Main *bmain;
92         Render *re;
93         Scene *scene;
94
95         View3D *v3d;
96         RegionView3D *rv3d;
97         ARegion *ar;
98
99         ScrArea *prevsa;
100         ARegion *prevar;
101
102         int views_len;  /* multi-view views */
103
104         bool is_sequencer;
105         SpaceSeq *sseq;
106         struct {
107                 ImBuf **ibufs_arr;
108         } seq_data;
109
110
111         Image *ima;
112         ImageUser iuser;
113
114         GPUOffScreen *ofs;
115         int ofs_samples;
116         bool ofs_full_samples;
117         GPUFX *fx;
118         int sizex, sizey;
119         int write_still;
120
121         ReportList *reports;
122         bMovieHandle *mh;
123         int cfrao, nfra;
124
125         int totvideos;
126
127         /* quick lookup */
128         int view_id;
129
130         /* wm vars for timer and progress cursor */
131         wmWindowManager *wm;
132         wmWindow *win;
133
134         wmTimer *timer; /* use to check if running modal or not (invoke'd or exec'd)*/
135         void **movie_ctx_arr;
136
137         TaskScheduler *task_scheduler;
138         TaskPool *task_pool;
139         bool pool_ok;
140         bool is_animation;
141         SpinLock reports_lock;
142         unsigned int num_scheduled_frames;
143         ThreadMutex task_mutex;
144         ThreadCondition task_condition;
145
146 #ifdef DEBUG_TIME
147         double time_start;
148 #endif
149 } OGLRender;
150
151 /* added because v3d is not always valid */
152 static unsigned int screen_opengl_layers(OGLRender *oglrender)
153 {
154         if (oglrender->v3d) {
155                 return oglrender->scene->lay | oglrender->v3d->lay;
156         }
157         else {
158                 return oglrender->scene->lay;
159         }
160 }
161
162 static bool screen_opengl_is_multiview(OGLRender *oglrender)
163 {
164         View3D *v3d = oglrender->v3d;
165         RegionView3D *rv3d = oglrender->rv3d;
166         RenderData *rd = &oglrender->scene->r;
167
168         if ((rd == NULL) || ((!oglrender->is_sequencer) && ((rv3d == NULL) || (v3d == NULL))))
169                 return false;
170
171         return (rd->scemode & R_MULTIVIEW) && ((oglrender->is_sequencer) || (rv3d->persp == RV3D_CAMOB && v3d->camera));
172 }
173
174 static void screen_opengl_views_setup(OGLRender *oglrender)
175 {
176         RenderResult *rr;
177         RenderView *rv;
178         SceneRenderView *srv;
179         bool is_multiview;
180         Object *camera;
181         View3D *v3d = oglrender->v3d;
182
183         RenderData *rd = &oglrender->scene->r;
184
185         rr = RE_AcquireResultWrite(oglrender->re);
186
187         is_multiview = screen_opengl_is_multiview(oglrender);
188
189         if (!is_multiview) {
190                 /* we only have one view when multiview is off */
191                 rv = rr->views.first;
192
193                 if (rv == NULL) {
194                         rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
195                         BLI_addtail(&rr->views, rv);
196                 }
197
198                 while (rv->next) {
199                         RenderView *rv_del = rv->next;
200                         BLI_remlink(&rr->views, rv_del);
201
202                         if (rv_del->rectf)
203                                 MEM_freeN(rv_del->rectf);
204
205                         if (rv_del->rectz)
206                                 MEM_freeN(rv_del->rectz);
207
208                         if (rv_del->rect32)
209                                 MEM_freeN(rv_del->rect32);
210
211                         MEM_freeN(rv_del);
212                 }
213         }
214         else {
215                 if (!oglrender->is_sequencer)
216                         RE_SetOverrideCamera(oglrender->re, V3D_CAMERA_SCENE(oglrender->scene, v3d));
217
218                 /* remove all the views that are not needed */
219                 rv = rr->views.last;
220                 while (rv) {
221                         srv = BLI_findstring(&rd->views, rv->name, offsetof(SceneRenderView, name));
222                         if (BKE_scene_multiview_is_render_view_active(rd, srv)) {
223                                 rv = rv->prev;
224                         }
225                         else {
226                                 RenderView *rv_del = rv;
227                                 rv  = rv_del->prev;
228
229                                 BLI_remlink(&rr->views, rv_del);
230
231                                 if (rv_del->rectf)
232                                         MEM_freeN(rv_del->rectf);
233
234                                 if (rv_del->rectz)
235                                         MEM_freeN(rv_del->rectz);
236
237                                 if (rv_del->rect32)
238                                         MEM_freeN(rv_del->rect32);
239
240                                 MEM_freeN(rv_del);
241                         }
242                 }
243
244                 /* create all the views that are needed */
245                 for (srv = rd->views.first; srv; srv = srv->next) {
246                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
247                                 continue;
248
249                         rv = BLI_findstring(&rr->views, srv->name, offsetof(SceneRenderView, name));
250
251                         if (rv == NULL) {
252                                 rv = MEM_callocN(sizeof(RenderView), "new opengl render view");
253                                 BLI_strncpy(rv->name, srv->name, sizeof(rv->name));
254                                 BLI_addtail(&rr->views, rv);
255                         }
256                 }
257         }
258
259         if (!(is_multiview && BKE_scene_multiview_is_stereo3d(rd)))
260                 oglrender->iuser.flag &= ~IMA_SHOW_STEREO;
261
262         /* will only work for non multiview correctly */
263         if (v3d) {
264                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, "new opengl render view");
265                 BKE_render_result_stamp_info(oglrender->scene, camera, rr, false);
266         }
267         else {
268                 BKE_render_result_stamp_info(oglrender->scene, oglrender->scene->camera, rr, false);
269         }
270
271         RE_ReleaseResult(oglrender->re);
272 }
273
274 static void screen_opengl_render_doit(OGLRender *oglrender, RenderResult *rr)
275 {
276         Scene *scene = oglrender->scene;
277         ARegion *ar = oglrender->ar;
278         View3D *v3d = oglrender->v3d;
279         RegionView3D *rv3d = oglrender->rv3d;
280         Object *camera = NULL;
281         int sizex = oglrender->sizex;
282         int sizey = oglrender->sizey;
283         const short view_context = (v3d != NULL);
284         bool draw_bgpic = true;
285         bool draw_sky = (scene->r.alphamode == R_ADDSKY);
286         unsigned char *rect = NULL;
287         const char *viewname = RE_GetActiveRenderView(oglrender->re);
288         ImBuf *ibuf_result = NULL;
289
290         if (oglrender->is_sequencer) {
291                 SpaceSeq *sseq = oglrender->sseq;
292                 struct bGPdata *gpd = (sseq && (sseq->flag & SEQ_SHOW_GPENCIL)) ? sseq->gpd : NULL;
293
294                 /* use pre-calculated ImBuf (avoids deadlock), see: */
295                 ImBuf *ibuf = oglrender->seq_data.ibufs_arr[oglrender->view_id];
296
297                 if (ibuf) {
298                         ImBuf *out = IMB_dupImBuf(ibuf);
299                         IMB_freeImBuf(ibuf);
300                         /* OpenGL render is considered to be preview and should be
301                          * as fast as possible. So currently we're making sure sequencer
302                          * result is always byte to simplify color management pipeline.
303                          *
304                          * TODO(sergey): In the case of output to float container (EXR)
305                          * it actually makes sense to keep float buffer instead.
306                          */
307                         if (out->rect_float != NULL) {
308                                 IMB_rect_from_float(out);
309                                 imb_freerectfloatImBuf(out);
310                         }
311                         BLI_assert((oglrender->sizex == ibuf->x) && (oglrender->sizey == ibuf->y));
312                         RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
313                         IMB_freeImBuf(out);
314                 }
315                 else if (gpd) {
316                         /* If there are no strips, Grease Pencil still needs a buffer to draw on */
317                         ImBuf *out = IMB_allocImBuf(oglrender->sizex, oglrender->sizey, 32, IB_rect);
318                         RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
319                         IMB_freeImBuf(out);
320                 }
321
322                 if (gpd) {
323                         int i;
324                         unsigned char *gp_rect;
325                         unsigned char *render_rect = (unsigned char *)RE_RenderViewGetById(rr, oglrender->view_id)->rect32;
326
327                         GPU_offscreen_bind(oglrender->ofs, true);
328
329                         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
330                         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
331
332                         wmOrtho2(0, sizex, 0, sizey);
333                         glTranslatef(sizex / 2, sizey / 2, 0.0f);
334
335                         G.f |= G_RENDER_OGL;
336                         ED_gpencil_draw_ex(scene, gpd, sizex, sizey, scene->r.cfra, SPACE_SEQ);
337                         G.f &= ~G_RENDER_OGL;
338
339                         gp_rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect");
340                         GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, gp_rect);
341
342                         for (i = 0; i < sizex * sizey * 4; i += 4) {
343                                 blend_color_mix_byte(&render_rect[i], &render_rect[i], &gp_rect[i]);
344                         }
345                         GPU_offscreen_unbind(oglrender->ofs, true);
346
347                         MEM_freeN(gp_rect);
348                 }
349         }
350         else {
351                 /* shouldnt suddenly give errors mid-render but possible */
352                 char err_out[256] = "unknown";
353                 ImBuf *ibuf_view;
354                 const int alpha_mode = (draw_sky) ? R_ADDSKY : R_ALPHAPREMUL;
355
356                 unsigned int draw_flags = V3D_OFSDRAW_NONE;
357                 draw_flags |= (oglrender->ofs_full_samples) ? V3D_OFSDRAW_USE_FULL_SAMPLE : 0;
358
359                 if (view_context) {
360                         draw_flags |= (draw_bgpic) ? V3D_OFSDRAW_USE_BACKGROUND : 0;
361
362                         ibuf_view = ED_view3d_draw_offscreen_imbuf(
363                                scene, v3d, ar, sizex, sizey,
364                                IB_rect, draw_flags, alpha_mode, oglrender->ofs_samples, viewname,
365                                oglrender->fx, oglrender->ofs, err_out);
366
367                         /* for stamp only */
368                         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
369                                 camera = BKE_camera_multiview_render(oglrender->scene, v3d->camera, viewname);
370                         }
371                 }
372                 else {
373                         draw_flags |= (V3D_OFSDRAW_USE_GPENCIL | V3D_OFSDRAW_USE_BACKGROUND);
374                         ibuf_view = ED_view3d_draw_offscreen_imbuf_simple(
375                                 scene, scene->camera, oglrender->sizex, oglrender->sizey,
376                                 IB_rect, draw_flags, OB_SOLID,
377                                 alpha_mode, oglrender->ofs_samples, viewname,
378                                 oglrender->fx, oglrender->ofs, err_out);
379                         camera = scene->camera;
380                 }
381
382                 if (ibuf_view) {
383                         ibuf_result = ibuf_view;
384                         rect = (unsigned char *)ibuf_view->rect;
385                 }
386                 else {
387                         fprintf(stderr, "%s: failed to get buffer, %s\n", __func__, err_out);
388                 }
389         }
390
391         if (ibuf_result != NULL) {
392                 if ((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW)) {
393                         BKE_image_stamp_buf(scene, camera, NULL, rect, NULL, rr->rectx, rr->recty, 4);
394                 }
395                 RE_render_result_rect_from_ibuf(rr, &scene->r, ibuf_result, oglrender->view_id);
396                 IMB_freeImBuf(ibuf_result);
397         }
398 }
399
400 static void screen_opengl_render_write(OGLRender *oglrender)
401 {
402         Scene *scene = oglrender->scene;
403         RenderResult *rr;
404         bool ok;
405         char name[FILE_MAX];
406
407         rr = RE_AcquireResultRead(oglrender->re);
408
409         BKE_image_path_from_imformat(
410                 name, scene->r.pic, oglrender->bmain->name, scene->r.cfra,
411                 &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, false, NULL);
412
413         /* write images as individual images or stereo */
414         BKE_render_result_stamp_info(scene, scene->camera, rr, false);
415         ok = RE_WriteRenderViewsImage(oglrender->reports, rr, scene, false, name);
416
417         RE_ReleaseResultImage(oglrender->re);
418
419         if (ok) printf("OpenGL Render written to '%s'\n", name);
420         else printf("OpenGL Render failed to write '%s'\n", name);
421 }
422
423 static void addAlphaOverFloat(float dest[4], const float source[4])
424 {
425         /* d = s + (1-alpha_s)d*/
426         float mul;
427
428         mul = 1.0f - source[3];
429
430         dest[0] = (mul * dest[0]) + source[0];
431         dest[1] = (mul * dest[1]) + source[1];
432         dest[2] = (mul * dest[2]) + source[2];
433         dest[3] = (mul * dest[3]) + source[3];
434
435 }
436
437 /* add renderlayer and renderpass for each grease pencil layer for using in composition */
438 static void add_gpencil_renderpass(OGLRender *oglrender, RenderResult *rr, RenderView *rv)
439 {
440         bGPdata *gpd = oglrender->scene->gpd;
441         Scene *scene = oglrender->scene;
442
443         /* sanity checks */
444         if (gpd == NULL) {
445                 return;
446         }
447         if (scene == NULL) {
448                 return;
449         }
450         if (BLI_listbase_is_empty(&gpd->layers)) {
451                 return;
452         }
453         if (oglrender->v3d != NULL && (oglrender->v3d->flag2 & V3D_SHOW_GPENCIL) == 0) {
454                 return;
455         }
456
457         /* save old alpha mode */
458         short oldalphamode = scene->r.alphamode;
459         /* set alpha transparent for gp */
460         scene->r.alphamode = R_ALPHAPREMUL;
461         
462         /* saves layer status */
463         short *oldsts = MEM_mallocN(BLI_listbase_count(&gpd->layers) * sizeof(short), "temp_gplayers_flag");
464         int i = 0;
465         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
466                 oldsts[i] = gpl->flag;
467                 ++i;
468         }
469         /* loop all layers to create separate render */
470         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
471                 /* dont draw layer if hidden */
472                 if (gpl->flag & GP_LAYER_HIDE)
473                         continue;
474                 /* hide all layer except current */
475                 for (bGPDlayer *gph = gpd->layers.first; gph; gph = gph->next) {
476                         if (gpl != gph) {
477                                 gph->flag |= GP_LAYER_HIDE;
478                         }
479                 }
480
481                 /* render this gp layer */
482                 screen_opengl_render_doit(oglrender, rr);
483                 
484                 /* add RendePass composite */
485                 RenderPass *rp = RE_create_gp_pass(rr, gpl->info, rv->name);
486
487                 /* copy image data from rectf */
488                 // XXX: Needs conversion.
489                 unsigned char *src = (unsigned char *)RE_RenderViewGetById(rr, oglrender->view_id)->rect32;
490                 if (src != NULL) {
491                         float *dest = rp->rect;
492
493                         int x, y, rectx, recty;
494                         rectx = rr->rectx;
495                         recty = rr->recty;
496                         for (y = 0; y < recty; y++) {
497                                 for (x = 0; x < rectx; x++) {
498                                         unsigned char *pixSrc = src + 4 * (rectx * y + x);
499                                         if (pixSrc[3] > 0) {
500                                                 float *pixDest = dest + 4 * (rectx * y + x);
501                                                 float float_src[4];
502                                                 srgb_to_linearrgb_uchar4(float_src, pixSrc);
503                                                 addAlphaOverFloat(pixDest, float_src);
504                                         }
505                                 }
506                         }
507                 }
508                 /* back layer status */
509                 i = 0;
510                 for (bGPDlayer *gph = gpd->layers.first; gph; gph = gph->next) {
511                         gph->flag = oldsts[i];
512                         ++i;
513                 }
514         }
515         /* free memory */
516         MEM_freeN(oldsts);
517
518         /* back default alpha mode */
519         scene->r.alphamode = oldalphamode;
520 }
521
522 static void screen_opengl_render_apply(OGLRender *oglrender)
523 {
524         RenderResult *rr;
525         RenderView *rv;
526         int view_id;
527         ImBuf *ibuf;
528         void *lock;
529
530         if (oglrender->is_sequencer) {
531                 Scene *scene = oglrender->scene;
532
533                 SeqRenderData context;
534                 SpaceSeq *sseq = oglrender->sseq;
535                 int chanshown = sseq ? sseq->chanshown : 0;
536
537                 BKE_sequencer_new_render_data(
538                         oglrender->bmain->eval_ctx, oglrender->bmain, scene,
539                         oglrender->sizex, oglrender->sizey, 100.0f,
540                         &context);
541
542                 for (view_id = 0; view_id < oglrender->views_len; view_id++) {
543                         context.view_id = view_id;
544                         context.gpu_offscreen = oglrender->ofs;
545                         context.gpu_fx = oglrender->fx;
546                         context.gpu_full_samples = oglrender->ofs_full_samples;
547
548                         oglrender->seq_data.ibufs_arr[view_id] = BKE_sequencer_give_ibuf(&context, CFRA, chanshown);
549                 }
550         }
551
552         rr = RE_AcquireResultRead(oglrender->re);
553         for (rv = rr->views.first, view_id = 0; rv; rv = rv->next, view_id++) {
554                 BLI_assert(view_id < oglrender->views_len);
555                 RE_SetActiveRenderView(oglrender->re, rv->name);
556                 oglrender->view_id = view_id;
557                 /* add grease pencil passes. For sequencer, the render does not include renderpasses
558                  * TODO: The sequencer render of grease pencil should be rethought */
559                 if (!oglrender->is_sequencer) {
560                         add_gpencil_renderpass(oglrender, rr, rv);
561                 }
562                 /* render composite */
563                 screen_opengl_render_doit(oglrender, rr);
564         }
565
566         RE_ReleaseResult(oglrender->re);
567
568         ibuf = BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock);
569         if (ibuf) {
570                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
571         }
572         BKE_image_release_ibuf(oglrender->ima, ibuf, lock);
573
574         if (oglrender->write_still) {
575                 screen_opengl_render_write(oglrender);
576         }
577 }
578
579 static bool screen_opengl_render_init(bContext *C, wmOperator *op)
580 {
581         /* new render clears all callbacks */
582         wmWindowManager *wm = CTX_wm_manager(C);
583         wmWindow *win = CTX_wm_window(C);
584
585         Scene *scene = CTX_data_scene(C);
586         ScrArea *prevsa = CTX_wm_area(C);
587         ARegion *prevar = CTX_wm_region(C);
588         GPUOffScreen *ofs;
589         OGLRender *oglrender;
590         int sizex, sizey;
591         const int samples = (scene->r.mode & R_OSA) ? scene->r.osa : 0;
592         const bool full_samples = (samples != 0) && (scene->r.scemode & R_FULL_SAMPLE);
593         bool is_view_context = RNA_boolean_get(op->ptr, "view_context");
594         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
595         const bool is_sequencer = RNA_boolean_get(op->ptr, "sequencer");
596         const bool is_write_still = RNA_boolean_get(op->ptr, "write_still");
597         char err_out[256] = "unknown";
598
599         if (G.background) {
600                 BKE_report(op->reports, RPT_ERROR, "Cannot use OpenGL render in background mode (no opengl context)");
601                 return false;
602         }
603
604         /* only one render job at a time */
605         if (WM_jobs_test(wm, scene, WM_JOB_TYPE_RENDER))
606                 return false;
607
608         if (is_sequencer) {
609                 is_view_context = false;
610         }
611         else {
612                 /* ensure we have a 3d view */
613                 if (!ED_view3d_context_activate(C)) {
614                         RNA_boolean_set(op->ptr, "view_context", false);
615                         is_view_context = false;
616                 }
617
618                 if (!is_view_context && scene->camera == NULL) {
619                         BKE_report(op->reports, RPT_ERROR, "Scene has no camera");
620                         return false;
621                 }
622         }
623
624         if (!is_animation && is_write_still && BKE_imtype_is_movie(scene->r.im_format.imtype)) {
625                 BKE_report(op->reports, RPT_ERROR, "Cannot write a single file with an animation format selected");
626                 return false;
627         }
628
629         /* stop all running jobs, except screen one. currently previews frustrate Render */
630         WM_jobs_kill_all_except(wm, CTX_wm_screen(C));
631
632         /* create offscreen buffer */
633         sizex = (scene->r.size * scene->r.xsch) / 100;
634         sizey = (scene->r.size * scene->r.ysch) / 100;
635
636         /* corrects render size with actual size, not every card supports non-power-of-two dimensions */
637         ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, err_out);
638
639         if (!ofs) {
640                 BKE_reportf(op->reports, RPT_ERROR, "Failed to create OpenGL off-screen buffer, %s", err_out);
641                 return false;
642         }
643
644         /* allocate opengl render */
645         oglrender = MEM_callocN(sizeof(OGLRender), "OGLRender");
646         op->customdata = oglrender;
647
648         oglrender->ofs = ofs;
649         oglrender->ofs_samples = samples;
650         oglrender->ofs_full_samples = full_samples;
651         oglrender->sizex = sizex;
652         oglrender->sizey = sizey;
653         oglrender->bmain = CTX_data_main(C);
654         oglrender->scene = scene;
655         oglrender->cfrao = scene->r.cfra;
656
657         oglrender->write_still = is_write_still && !is_animation;
658         oglrender->is_animation = is_animation;
659
660         oglrender->views_len = BKE_scene_multiview_num_views_get(&scene->r);
661
662         oglrender->is_sequencer = is_sequencer;
663         if (is_sequencer) {
664                 oglrender->sseq = CTX_wm_space_seq(C);
665                 ImBuf **ibufs_arr = MEM_callocN(sizeof(*ibufs_arr) * oglrender->views_len, __func__);
666                 oglrender->seq_data.ibufs_arr = ibufs_arr;
667         }
668
669         oglrender->prevsa = prevsa;
670         oglrender->prevar = prevar;
671
672         if (is_view_context) {
673                 ED_view3d_context_user_region(C, &oglrender->v3d, &oglrender->ar); /* so quad view renders camera */
674                 oglrender->rv3d = oglrender->ar->regiondata;
675
676                 /* MUST be cleared on exit */
677                 oglrender->scene->customdata_mask_modal = ED_view3d_datamask(oglrender->scene, oglrender->v3d);
678
679                 /* apply immediately in case we're rendering from a script,
680                  * running notifiers again will overwrite */
681                 oglrender->scene->customdata_mask |= oglrender->scene->customdata_mask_modal;
682
683                 if (oglrender->v3d->fx_settings.fx_flag & (GPU_FX_FLAG_DOF | GPU_FX_FLAG_SSAO)) {
684                         oglrender->fx = GPU_fx_compositor_create();
685                 }
686         }
687         else if (is_sequencer) {
688                 if (scene->r.seq_flag & R_SEQ_CAMERA_DOF) {
689                         oglrender->fx = GPU_fx_compositor_create();
690                 }
691         }
692
693         /* create render */
694         oglrender->re = RE_NewSceneRender(scene);
695
696         /* create image and image user */
697         oglrender->ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
698         BKE_image_signal(oglrender->ima, NULL, IMA_SIGNAL_FREE);
699         BKE_image_backup_render(oglrender->scene, oglrender->ima, true);
700
701         oglrender->iuser.scene = scene;
702         oglrender->iuser.ok = 1;
703
704         /* create render result */
705         RE_InitState(oglrender->re, NULL, &scene->r, NULL, sizex, sizey, NULL);
706
707         /* create render views */
708         screen_opengl_views_setup(oglrender);
709
710         /* wm vars */
711         oglrender->wm = wm;
712         oglrender->win = win;
713
714         oglrender->totvideos = 0;
715         oglrender->mh = NULL;
716         oglrender->movie_ctx_arr = NULL;
717
718         if (is_animation) {
719                 TaskScheduler *task_scheduler = BLI_task_scheduler_get();
720                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
721                         task_scheduler = BLI_task_scheduler_create(1);
722                         oglrender->task_scheduler = task_scheduler;
723                         oglrender->task_pool = BLI_task_pool_create_background(task_scheduler,
724                                                                                oglrender);
725                 }
726                 else {
727                         oglrender->task_scheduler = NULL;
728                         oglrender->task_pool = BLI_task_pool_create(task_scheduler,
729                                                                     oglrender);
730                 }
731                 oglrender->pool_ok = true;
732                 BLI_spin_init(&oglrender->reports_lock);
733         }
734         else {
735                 oglrender->task_scheduler = NULL;
736                 oglrender->task_pool = NULL;
737         }
738         oglrender->num_scheduled_frames = 0;
739         BLI_mutex_init(&oglrender->task_mutex);
740         BLI_condition_init(&oglrender->task_condition);
741
742 #ifdef DEBUG_TIME
743         oglrender->time_start = PIL_check_seconds_timer();
744 #endif
745
746         return true;
747 }
748
749 static void screen_opengl_render_end(bContext *C, OGLRender *oglrender)
750 {
751         Main *bmain = CTX_data_main(C);
752         Scene *scene = oglrender->scene;
753         int i;
754
755         if (oglrender->is_animation) {
756                 /* Trickery part for movie output:
757                  *
758                  * We MUST write frames in an exact order, so we only let background
759                  * thread to work on that, and main thread is simply waits for that
760                  * thread to do all the dirty work.
761                  *
762                  * After this loop is done work_and_wait() will have nothing to do,
763                  * so we don't run into wrong order of frames written to the stream.
764                  */
765                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
766                         BLI_mutex_lock(&oglrender->task_mutex);
767                         while (oglrender->num_scheduled_frames > 0) {
768                                 BLI_condition_wait(&oglrender->task_condition,
769                                                    &oglrender->task_mutex);
770                         }
771                         BLI_mutex_unlock(&oglrender->task_mutex);
772                 }
773                 BLI_task_pool_work_and_wait(oglrender->task_pool);
774                 BLI_task_pool_free(oglrender->task_pool);
775                 /* Depending on various things we might or might not use global scheduler. */
776                 if (oglrender->task_scheduler != NULL) {
777                         BLI_task_scheduler_free(oglrender->task_scheduler);
778                 }
779                 BLI_spin_end(&oglrender->reports_lock);
780         }
781         BLI_mutex_end(&oglrender->task_mutex);
782         BLI_condition_end(&oglrender->task_condition);
783
784 #ifdef DEBUG_TIME
785         printf("Total render time: %f\n", PIL_check_seconds_timer() - oglrender->time_start);
786 #endif
787
788         if (oglrender->mh) {
789                 if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
790                         for (i = 0; i < oglrender->totvideos; i++) {
791                                 oglrender->mh->end_movie(oglrender->movie_ctx_arr[i]);
792                                 oglrender->mh->context_free(oglrender->movie_ctx_arr[i]);
793                         }
794                 }
795
796                 if (oglrender->movie_ctx_arr) {
797                         MEM_freeN(oglrender->movie_ctx_arr);
798                 }
799         }
800
801         if (oglrender->timer) { /* exec will not have a timer */
802                 scene->r.cfra = oglrender->cfrao;
803                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, screen_opengl_layers(oglrender));
804
805                 WM_event_remove_timer(oglrender->wm, oglrender->win, oglrender->timer);
806         }
807
808         WM_cursor_modal_restore(oglrender->win);
809
810         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
811
812         if (oglrender->fx)
813                 GPU_fx_compositor_destroy(oglrender->fx);
814
815         GPU_offscreen_free(oglrender->ofs);
816
817         if (oglrender->is_sequencer) {
818                 MEM_freeN(oglrender->seq_data.ibufs_arr);
819         }
820
821         oglrender->scene->customdata_mask_modal = 0;
822
823         CTX_wm_area_set(C, oglrender->prevsa);
824         CTX_wm_region_set(C, oglrender->prevar);
825
826         MEM_freeN(oglrender);
827 }
828
829 static void screen_opengl_render_cancel(bContext *C, wmOperator *op)
830 {
831         screen_opengl_render_end(C, op->customdata);
832 }
833
834 /* share between invoke and exec */
835 static bool screen_opengl_render_anim_initialize(bContext *C, wmOperator *op)
836 {
837         /* initialize animation */
838         OGLRender *oglrender;
839         Scene *scene;
840
841         oglrender = op->customdata;
842         scene = oglrender->scene;
843         oglrender->totvideos = BKE_scene_multiview_num_videos_get(&scene->r);
844
845         oglrender->reports = op->reports;
846
847         if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
848                 size_t width, height;
849                 int i;
850
851                 BKE_scene_multiview_videos_dimensions_get(&scene->r, oglrender->sizex, oglrender->sizey, &width, &height);
852                 oglrender->mh = BKE_movie_handle_get(scene->r.im_format.imtype);
853
854                 if (oglrender->mh == NULL) {
855                         BKE_report(oglrender->reports, RPT_ERROR, "Movie format unsupported");
856                         screen_opengl_render_end(C, oglrender);
857                         return false;
858                 }
859
860                 oglrender->movie_ctx_arr = MEM_mallocN(sizeof(void *) * oglrender->totvideos, "Movies");
861
862                 for (i = 0; i < oglrender->totvideos; i++) {
863                         const char *suffix = BKE_scene_multiview_view_id_suffix_get(&scene->r, i);
864
865                         oglrender->movie_ctx_arr[i] = oglrender->mh->context_create();
866                         if (!oglrender->mh->start_movie(oglrender->movie_ctx_arr[i], scene, &scene->r, oglrender->sizex,
867                                                         oglrender->sizey, oglrender->reports, PRVRANGEON != 0, suffix))
868                         {
869                                 screen_opengl_render_end(C, oglrender);
870                                 return false;
871                         }
872                 }
873         }
874
875         oglrender->cfrao = scene->r.cfra;
876         oglrender->nfra = PSFRA;
877         scene->r.cfra = PSFRA;
878
879         return true;
880 }
881
882 typedef struct WriteTaskData {
883         RenderResult *rr;
884         Scene tmp_scene;
885 } WriteTaskData;
886
887 static void write_result_func(TaskPool * __restrict pool,
888                               void *task_data_v,
889                               int UNUSED(thread_id))
890 {
891         OGLRender *oglrender = (OGLRender *) BLI_task_pool_userdata(pool);
892         WriteTaskData *task_data = (WriteTaskData *) task_data_v;
893         Scene *scene = &task_data->tmp_scene;
894         RenderResult *rr = task_data->rr;
895         const bool is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
896         const int cfra = scene->r.cfra;
897         bool ok;
898         /* Don't attempt to write if we've got an error. */
899         if (!oglrender->pool_ok) {
900                 RE_FreeRenderResult(rr);
901                 BLI_mutex_lock(&oglrender->task_mutex);
902                 oglrender->num_scheduled_frames--;
903                 BLI_condition_notify_all(&oglrender->task_condition);
904                 BLI_mutex_unlock(&oglrender->task_mutex);
905                 return;
906         }
907         /* Construct local thread0safe copy of reports structure which we can
908          * safely pass to the underlying functions.
909          */
910         ReportList reports;
911         BKE_reports_init(&reports, oglrender->reports->flag & ~RPT_PRINT);
912         /* Do actual save logic here, depending on the file format.
913          *
914          * NOTE: We have to construct temporary scene with proper scene->r.cfra.
915          * This is because underlying calls do not use r.cfra but use scene
916          * for that.
917          */
918         if (is_movie) {
919                 ok = RE_WriteRenderViewsMovie(&reports,
920                                               rr,
921                                               scene,
922                                               &scene->r,
923                                               oglrender->mh,
924                                               oglrender->movie_ctx_arr,
925                                               oglrender->totvideos,
926                                               PRVRANGEON != 0);
927         }
928         else {
929                 /* TODO(sergey): We can in theory save some CPU ticks here because we
930                  * calculate file name again here.
931                  */
932                 char name[FILE_MAX];
933                 BKE_image_path_from_imformat(name,
934                                              scene->r.pic,
935                                              oglrender->bmain->name,
936                                              cfra,
937                                              &scene->r.im_format,
938                                              (scene->r.scemode & R_EXTENSION) != 0,
939                                              true,
940                                              NULL);
941
942                 BKE_render_result_stamp_info(scene, scene->camera, rr, false);
943                 ok = RE_WriteRenderViewsImage(NULL, rr, scene, true, name);
944                 if (!ok) {
945                         BKE_reportf(&reports,
946                                     RPT_ERROR,
947                                     "Write error: cannot save %s",
948                                     name);
949                 }
950         }
951         if (reports.list.first != NULL) {
952                 BLI_spin_lock(&oglrender->reports_lock);
953                 for (Report *report = reports.list.first;
954                      report != NULL;
955                      report = report->next)
956                 {
957                         BKE_report(oglrender->reports,
958                                    report->type,
959                                    report->message);
960                 }
961                 BLI_spin_unlock(&oglrender->reports_lock);
962         }
963         if (!ok) {
964                 oglrender->pool_ok = false;
965         }
966         RE_FreeRenderResult(rr);
967         BLI_mutex_lock(&oglrender->task_mutex);
968         oglrender->num_scheduled_frames--;
969         BLI_condition_notify_all(&oglrender->task_condition);
970         BLI_mutex_unlock(&oglrender->task_mutex);
971 }
972
973 static bool schedule_write_result(OGLRender *oglrender, RenderResult *rr)
974 {
975         if (!oglrender->pool_ok) {
976                 RE_FreeRenderResult(rr);
977                 return false;
978         }
979         Scene *scene = oglrender->scene;
980         WriteTaskData *task_data = MEM_mallocN(sizeof(WriteTaskData), "write task data");
981         task_data->rr = rr;
982         task_data->tmp_scene = *scene;
983         BLI_mutex_lock(&oglrender->task_mutex);
984         oglrender->num_scheduled_frames++;
985         if (oglrender->num_scheduled_frames > MAX_SCHEDULED_FRAMES) {
986                 BLI_condition_wait(&oglrender->task_condition,
987                                    &oglrender->task_mutex);
988         }
989         BLI_mutex_unlock(&oglrender->task_mutex);
990         BLI_task_pool_push(oglrender->task_pool,
991                            write_result_func,
992                            task_data,
993                            true,
994                            TASK_PRIORITY_LOW);
995         return true;
996 }
997
998 static bool screen_opengl_render_anim_step(bContext *C, wmOperator *op)
999 {
1000         Main *bmain = CTX_data_main(C);
1001         OGLRender *oglrender = op->customdata;
1002         Scene *scene = oglrender->scene;
1003         char name[FILE_MAX];
1004         bool ok = false;
1005         const bool view_context = (oglrender->v3d != NULL);
1006         bool is_movie;
1007         RenderResult *rr;
1008
1009         /* go to next frame */
1010         if (CFRA < oglrender->nfra)
1011                 CFRA++;
1012         while (CFRA < oglrender->nfra) {
1013                 unsigned int lay = screen_opengl_layers(oglrender);
1014
1015                 if (lay & 0xFF000000)
1016                         lay &= 0xFF000000;
1017
1018                 BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, lay);
1019                 CFRA++;
1020         }
1021
1022         is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
1023
1024         if (!is_movie) {
1025                 BKE_image_path_from_imformat(
1026                         name, scene->r.pic, oglrender->bmain->name, scene->r.cfra,
1027                         &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, true, NULL);
1028
1029                 if ((scene->r.mode & R_NO_OVERWRITE) && BLI_exists(name)) {
1030                         BLI_spin_lock(&oglrender->reports_lock);
1031                         BKE_reportf(op->reports, RPT_INFO, "Skipping existing frame \"%s\"", name);
1032                         BLI_spin_unlock(&oglrender->reports_lock);
1033                         ok = true;
1034                         goto finally;
1035                 }
1036         }
1037
1038         WM_cursor_time(oglrender->win, scene->r.cfra);
1039
1040         BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, screen_opengl_layers(oglrender));
1041
1042         if (view_context) {
1043                 if (oglrender->rv3d->persp == RV3D_CAMOB && oglrender->v3d->camera && oglrender->v3d->scenelock) {
1044                         /* since BKE_scene_update_for_newframe() is used rather
1045                          * then ED_update_for_newframe() the camera needs to be set */
1046                         if (BKE_scene_camera_switch_update(scene)) {
1047                                 oglrender->v3d->camera = scene->camera;
1048                         }
1049                 }
1050         }
1051         else {
1052                 BKE_scene_camera_switch_update(scene);
1053         }
1054
1055         /* render into offscreen buffer */
1056         screen_opengl_render_apply(oglrender);
1057
1058         /* save to disk */
1059         rr = RE_AcquireResultRead(oglrender->re);
1060         RenderResult *new_rr = RE_DuplicateRenderResult(rr);
1061         RE_ReleaseResult(oglrender->re);
1062
1063         ok = schedule_write_result(oglrender, new_rr);
1064
1065 finally:  /* Step the frame and bail early if needed */
1066
1067         /* go to next frame */
1068         oglrender->nfra += scene->r.frame_step;
1069
1070         /* stop at the end or on error */
1071         if (CFRA >= PEFRA || !ok) {
1072                 screen_opengl_render_end(C, op->customdata);
1073                 return 0;
1074         }
1075
1076         return 1;
1077 }
1078
1079
1080 static int screen_opengl_render_modal(bContext *C, wmOperator *op, const wmEvent *event)
1081 {
1082         OGLRender *oglrender = op->customdata;
1083         const bool anim = RNA_boolean_get(op->ptr, "animation");
1084         bool ret;
1085
1086         switch (event->type) {
1087                 case ESCKEY:
1088                         /* cancel */
1089                         oglrender->pool_ok = false;  /* Flag pool for cancel. */
1090                         screen_opengl_render_end(C, op->customdata);
1091                         return OPERATOR_FINISHED;
1092                 case TIMER:
1093                         /* render frame? */
1094                         if (oglrender->timer == event->customdata)
1095                                 break;
1096                         ATTR_FALLTHROUGH;
1097                 default:
1098                         /* nothing to do */
1099                         return OPERATOR_RUNNING_MODAL;
1100         }
1101
1102         /* run first because screen_opengl_render_anim_step can free oglrender */
1103         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, oglrender->scene);
1104         
1105         if (anim == 0) {
1106                 screen_opengl_render_apply(op->customdata);
1107                 screen_opengl_render_end(C, op->customdata);
1108                 return OPERATOR_FINISHED;
1109         }
1110         else {
1111                 ret = screen_opengl_render_anim_step(C, op);
1112         }
1113
1114         /* stop at the end or on error */
1115         if (ret == false) {
1116                 return OPERATOR_FINISHED;
1117         }
1118
1119         return OPERATOR_RUNNING_MODAL;
1120 }
1121
1122 static int screen_opengl_render_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1123 {
1124         OGLRender *oglrender;
1125         const bool anim = RNA_boolean_get(op->ptr, "animation");
1126
1127         if (!screen_opengl_render_init(C, op))
1128                 return OPERATOR_CANCELLED;
1129
1130         if (anim) {
1131                 if (!screen_opengl_render_anim_initialize(C, op))
1132                         return OPERATOR_CANCELLED;
1133         }
1134         
1135         oglrender = op->customdata;
1136         render_view_open(C, event->x, event->y, op->reports);
1137         
1138         /* view may be changed above (R_OUTPUT_WINDOW) */
1139         oglrender->win = CTX_wm_window(C);
1140
1141         WM_event_add_modal_handler(C, op);
1142         oglrender->timer = WM_event_add_timer(oglrender->wm, oglrender->win, TIMER, 0.01f);
1143         
1144         return OPERATOR_RUNNING_MODAL;
1145 }
1146
1147 /* executes blocking render */
1148 static int screen_opengl_render_exec(bContext *C, wmOperator *op)
1149 {
1150         const bool is_animation = RNA_boolean_get(op->ptr, "animation");
1151
1152         if (!screen_opengl_render_init(C, op))
1153                 return OPERATOR_CANCELLED;
1154
1155         if (!is_animation) { /* same as invoke */
1156                 /* render image */
1157                 screen_opengl_render_apply(op->customdata);
1158                 screen_opengl_render_end(C, op->customdata);
1159
1160                 return OPERATOR_FINISHED;
1161         }
1162         else {
1163                 bool ret = true;
1164
1165                 if (!screen_opengl_render_anim_initialize(C, op))
1166                         return OPERATOR_CANCELLED;
1167
1168                 while (ret) {
1169                         ret = screen_opengl_render_anim_step(C, op);
1170                 }
1171         }
1172
1173         /* no redraw needed, we leave state as we entered it */
1174 //      ED_update_for_newframe(C, 1);
1175         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, CTX_data_scene(C));
1176
1177         return OPERATOR_FINISHED;
1178 }
1179
1180 void RENDER_OT_opengl(wmOperatorType *ot)
1181 {
1182         PropertyRNA *prop;
1183
1184         /* identifiers */
1185         ot->name = "OpenGL Render";
1186         ot->description = "OpenGL render active viewport";
1187         ot->idname = "RENDER_OT_opengl";
1188
1189         /* api callbacks */
1190         ot->invoke = screen_opengl_render_invoke;
1191         ot->exec = screen_opengl_render_exec; /* blocking */
1192         ot->modal = screen_opengl_render_modal;
1193         ot->cancel = screen_opengl_render_cancel;
1194
1195         ot->poll = ED_operator_screenactive;
1196
1197         prop = RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
1198         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1199         prop = RNA_def_boolean(ot->srna, "sequencer", 0, "Sequencer", "Render using the sequencer's OpenGL display");
1200         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1201         prop = RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
1202         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1203         prop = RNA_def_boolean(ot->srna, "view_context", 1, "View Context", "Use the current 3D view for rendering, else use scene settings");
1204         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1205
1206 }
1207
1208 /* function for getting an opengl buffer from a View3D, used by sequencer */
1209 // extern void *sequencer_view3d_cb;